context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using WindowsAzure.ServiceManagement; using Model; using IaasCmdletInfo; using ConfigDataInfo; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties; using Sync.Download; using Microsoft.WindowsAzure.Management.Utilities.Common; public class ServiceManagementCmdletTestHelper { /// <summary> /// Run a powershell cmdlet that returns the first PSObject as a return value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmdlet"></param> /// <returns></returns> private T RunPSCmdletAndReturnFirst<T>(PowershellCore.CmdletsInfo cmdlet) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdlet); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (T) result[0].BaseObject; } return default(T); } /// <summary> /// Run a powershell cmdlet that returns a collection of PSObjects as a return value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmdlet"></param> /// <returns></returns> private Collection<T> RunPSCmdletAndReturnAll<T>(PowershellCore.CmdletsInfo cmdlet) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdlet); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<T> resultCollection = new Collection<T>(); foreach (PSObject re in result) { resultCollection.Add((T)re.BaseObject); } return resultCollection; } public Collection <PSObject> RunPSScript(string script) { List<string> st = new List<string>(); st.Add(script); WindowsAzurePowershellScript azurePowershellCmdlet = new WindowsAzurePowershellScript(st); return azurePowershellCmdlet.Run(); } public bool TestAzureServiceName(string serviceName) { return RunPSCmdletAndReturnFirst<bool>(new TestAzureNameCmdletInfo("Service", serviceName)); } public Collection<LocationsContext> GetAzureLocation() { return RunPSCmdletAndReturnAll<LocationsContext>(new GetAzureLocationCmdletInfo()); } public string GetAzureLocationName(string[] keywords, bool exactMatch = true) { Collection<LocationsContext> locations = GetAzureLocation(); if (keywords != null) { foreach (LocationsContext location in locations) { if (Utilities.MatchKeywords(location.Name, keywords, exactMatch) >= 0) { return location.Name; } } } else { if (locations.Count == 1) { return locations[0].Name; } } return null; } public Collection<OSVersionsContext> GetAzureOSVersion() { return RunPSCmdletAndReturnAll<OSVersionsContext>(new GetAzureOSVersionCmdletInfo()); } #region CertificateSetting, VMConifig, ProvisioningConfig public CertificateSetting NewAzureCertificateSetting(string store, string thumbprint) { return RunPSCmdletAndReturnFirst<CertificateSetting>(new NewAzureCertificateSettingCmdletInfo(store, thumbprint)); } public PersistentVM NewAzureVMConfig(AzureVMConfigInfo vmConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new NewAzureVMConfigCmdletInfo(vmConfig)); } public PersistentVM AddAzureProvisioningConfig(AzureProvisioningConfigInfo provConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureProvisioningConfigCmdletInfo(provConfig)); } #endregion #region AzureAffinityGroup public ManagementOperationContext NewAzureAffinityGroup(string name, string location, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext> (new NewAzureAffinityGroupCmdletInfo(name, location, label, description)); } public Collection<AffinityGroupContext> GetAzureAffinityGroup(string name) { return RunPSCmdletAndReturnAll<AffinityGroupContext>(new GetAzureAffinityGroupCmdletInfo(name)); } public ManagementOperationContext SetAzureAffinityGroup(string name, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext> (new SetAzureAffinityGroupCmdletInfo(name, label, description)); } public ManagementOperationContext RemoveAzureAffinityGroup(string name) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureAffinityGroupCmdletInfo(name)); } #endregion #region AzureAvailabilitySet public PersistentVM SetAzureAvailabilitySet(string vmName, string serviceName, string availabilitySetName) { if (!string.IsNullOrEmpty(availabilitySetName)) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureAvailabilitySetCmdletInfo(availabilitySetName, vm)); } else { return null; } } #endregion AzureAvailabilitySet #region AzureCertificate public ManagementOperationContext AddAzureCertificate(string serviceName, PSObject cert, string password = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new AddAzureCertificateCmdletInfo(serviceName, cert, password)); } public Collection <CertificateContext> GetAzureCertificate(string serviceName, string thumbprint = null, string algorithm = null) { return RunPSCmdletAndReturnAll<CertificateContext> (new GetAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm)); } public ManagementOperationContext RemoveAzureCertificate(string serviceName, string thumbprint, string algorithm) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm)); } #endregion #region AzureDataDisk public PersistentVM AddAzureDataDisk(AddAzureDataDiskConfig diskConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureDataDiskCmdletInfo(diskConfig)); } public void AddDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig [] diskConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AddAzureDataDiskConfig config in diskConfigs) { config.Vm = vm; vm = AddAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } public PersistentVM SetAzureDataDisk(SetAzureDataDiskConfig discCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureDataDiskCmdletInfo(discCfg)); } public void SetDataDisk(string vmName, string serviceName, HostCaching hc, int lun) { SetAzureDataDiskConfig config = new SetAzureDataDiskConfig(hc, lun); config.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureDataDisk(config)); } public Collection<DataVirtualHardDisk> GetAzureDataDisk(string vmName, string serviceName) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); return RunPSCmdletAndReturnAll<DataVirtualHardDisk>(new GetAzureDataDiskCmdletInfo(vmRolectx.VM)); } private PersistentVM RemoveAzureDataDisk(RemoveAzureDataDiskConfig discCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new RemoveAzureDataDiskCmdletInfo(discCfg)); } public void RemoveDataDisk(string vmName, string serviceName, int [] lunSlots) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (int lun in lunSlots) { RemoveAzureDataDiskConfig config = new RemoveAzureDataDiskConfig(lun, vm); RemoveAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } #endregion #region AzureDeployment public ManagementOperationContext NewAzureDeployment(string serviceName, string packagePath, string configPath, string slot, string label, string name, bool doNotStart, bool warning) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureDeploymentCmdletInfo(serviceName, packagePath, configPath, slot, label, name, doNotStart, warning)); } public DeploymentInfoContext GetAzureDeployment(string serviceName, string slot) { return RunPSCmdletAndReturnFirst<DeploymentInfoContext>(new GetAzureDeploymentCmdletInfo(serviceName, slot)); } public DeploymentInfoContext GetAzureDeployment(string serviceName) { return GetAzureDeployment(serviceName, DeploymentSlotType.Production); } private ManagementOperationContext SetAzureDeployment(SetAzureDeploymentCmdletInfo cmdletInfo) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(cmdletInfo); } public ManagementOperationContext SetAzureDeploymentStatus(string serviceName, string slot, string newStatus) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentStatusCmdletInfo(serviceName, slot, newStatus)); } public ManagementOperationContext SetAzureDeploymentConfig(string serviceName, string slot, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentConfigCmdletInfo(serviceName, slot, configPath)); } public ManagementOperationContext SetAzureDeploymentUpgrade(string serviceName, string slot, string mode, string packagePath, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentUpgradeCmdletInfo(serviceName, slot, mode, packagePath, configPath)); } public ManagementOperationContext SetAzureDeployment(string option, string serviceName, string packagePath, string newStatus, string configName, string slot, string mode, string label, string roleName, bool force) { return SetAzureDeployment(new SetAzureDeploymentCmdletInfo(option, serviceName, packagePath, newStatus, configName, slot, mode, label, roleName, force)); } public ManagementOperationContext RemoveAzureDeployment(string serviceName, string slot, bool force) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureDeploymentCmdletInfo(serviceName, slot, force)); } public ManagementOperationContext MoveAzureDeployment(string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new MoveAzureDeploymentCmdletInfo(serviceName)); } public ManagementOperationContext SetAzureWalkUpgradeDomain(string serviceName, string slot, int domainNumber) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureWalkUpgradeDomainCmdletInfo(serviceName, slot, domainNumber)); } #endregion #region AzureDisk // Add-AzureDisk public DiskContext AddAzureDisk(string diskName, string mediaPath, string label, string os) { return RunPSCmdletAndReturnFirst<DiskContext>(new AddAzureDiskCmdletInfo(diskName, mediaPath, label, os)); } // Get-AzureDisk public Collection<DiskContext> GetAzureDisk(string diskName) { return GetAzureDisk(new GetAzureDiskCmdletInfo(diskName)); } public Collection<DiskContext> GetAzureDisk() { return GetAzureDisk(new GetAzureDiskCmdletInfo((string)null)); } private Collection<DiskContext> GetAzureDisk(GetAzureDiskCmdletInfo getAzureDiskCmdletInfo) { return RunPSCmdletAndReturnAll<DiskContext>(getAzureDiskCmdletInfo); } public Collection<DiskContext> GetAzureDiskAttachedToRoleName(string[] roleName, bool exactMatch = true) { Collection<DiskContext> retDisks = new Collection<DiskContext>(); Collection<DiskContext> disks = GetAzureDisk(); foreach (DiskContext disk in disks) { if (disk.AttachedTo != null && disk.AttachedTo.RoleName != null) { if (Utilities.MatchKeywords(disk.AttachedTo.RoleName, roleName, exactMatch) >= 0) retDisks.Add(disk); } } return retDisks; } // Remove-AzureDisk public ManagementOperationContext RemoveAzureDisk(string diskName, bool deleteVhd) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureDiskCmdletInfo(diskName, deleteVhd)); } // Update-AzureDisk public DiskContext UpdateAzureDisk(string diskName, string label) { return RunPSCmdletAndReturnFirst<DiskContext>(new UpdateAzureDiskCmdletInfo(diskName, label)); } #endregion #region AzureDns public DnsServer NewAzureDns(string name, string ipAddress) { return RunPSCmdletAndReturnFirst<DnsServer>(new NewAzureDnsCmdletInfo(name, ipAddress)); } public DnsServerList GetAzureDns(DnsSettings settings) { GetAzureDnsCmdletInfo getAzureDnsCmdletInfo = new GetAzureDnsCmdletInfo(settings); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDnsCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); DnsServerList dnsList = new DnsServerList(); foreach (PSObject re in result) { dnsList.Add((DnsServer)re.BaseObject); } return dnsList; } #endregion #region AzureEndpoint public PersistentVM AddAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureEndpointCmdletInfo(endPointConfig)); } public void AddEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo [] endPointConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AzureEndPointConfigInfo config in endPointConfigs) { config.Vm = vm; vm = AddAzureEndPoint(config); } UpdateAzureVM(vmName, serviceName, vm); } public Collection <InputEndpointContext> GetAzureEndPoint(PersistentVMRoleContext vmRoleCtxt) { return RunPSCmdletAndReturnAll<InputEndpointContext>(new GetAzureEndpointCmdletInfo(vmRoleCtxt)); } public PersistentVM SetAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { if (null != endPointConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureEndpointCmdletInfo(endPointConfig)); } return null; } public void SetEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo endPointConfig) { endPointConfig.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureEndPoint(endPointConfig)); } public PersistentVMRoleContext RemoveAzureEndPoint(string epName, PersistentVMRoleContext vmRoleCtxt) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new RemoveAzureEndpointCmdletInfo(epName, vmRoleCtxt)); } public void RemoveEndPoint(string vmName, string serviceName, string [] epNames) { PersistentVMRoleContext vmRoleCtxt = GetAzureVM(vmName, serviceName); foreach (string ep in epNames) { vmRoleCtxt.VM = RemoveAzureEndPoint(ep, vmRoleCtxt).VM; } UpdateAzureVM(vmName, serviceName, vmRoleCtxt.VM); } #endregion #region AzureOSDisk public PersistentVM SetAzureOSDisk(HostCaching hc, PersistentVM vm) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureOSDiskCmdletInfo(hc, vm)); } public OSVirtualHardDisk GetAzureOSDisk(PersistentVM vm) { return RunPSCmdletAndReturnFirst<OSVirtualHardDisk>(new GetAzureOSDiskCmdletInfo(vm)); } #endregion #region AzureRole public ManagementOperationContext SetAzureRole(string serviceName, string slot, string roleName, int count) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureRoleCmdletInfo(serviceName, slot, roleName, count)); } public Collection<RoleContext> GetAzureRole(string serviceName, string slot, string roleName, bool details) { return RunPSCmdletAndReturnAll<RoleContext>(new GetAzureRoleCmdletInfo(serviceName, slot, roleName, details)); } #endregion #region AzureQuickVM public PersistentVMRoleContext NewAzureQuickVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName, InstanceSize? instanceSize) { NewAzureQuickVMCmdletInfo newAzureQuickVMCmdlet = new NewAzureQuickVMCmdletInfo(os, name, serviceName, imageName, userName, password, locationName, instanceSize); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureQuickVMCmdlet); SubscriptionData currentSubscription; if ((currentSubscription = GetCurrentAzureSubscription()) == null) { ImportAzurePublishSettingsFile(); currentSubscription = GetCurrentAzureSubscription(); } if (string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { StorageServicePropertiesOperationContext storageAccount = NewAzureStorageAccount(Utilities.GetUniqueShortName("storage"), locationName); if (storageAccount != null) { SetAzureSubscription(currentSubscription.SubscriptionName, storageAccount.StorageAccountName); currentSubscription = GetCurrentAzureSubscription(); } } if (!string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { azurePowershellCmdlet.Run(); return GetAzureVM(name, serviceName); } return null; } public PersistentVMRoleContext NewAzureQuickVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName) { return NewAzureQuickVM(os, name, serviceName, imageName, userName, password, locationName, null); } public PersistentVMRoleContext NewAzureQuickLinuxVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName) { return NewAzureQuickVM(os, name, serviceName, imageName, userName, password, locationName); } #endregion #region AzurePublishSettingsFile public void ImportAzurePublishSettingsFile() { string localFile = @".\temp.publishsettings"; // Delete the file if it exists. if (File.Exists(localFile)) { File.Delete(localFile); } if (String.IsNullOrEmpty(Resource.BlobKey)) { // Get a publish settings file from a local or shared directory. string publishSettingsFile = Resource.PublishSettingsFile; if (string.IsNullOrEmpty(publishSettingsFile)) { return; } else if (publishSettingsFile.StartsWith("\\\\")) { // A publish settings file is located in a shared directory. Copy it to a local directory and use it. File.Copy(publishSettingsFile, localFile, true); } else { // A publish settings file is located in a local directory. this.ImportAzurePublishSettingsFile(publishSettingsFile); return; } } else { // Get a publish settings file from a blob storage. BlobHandle blobRepo = Utilities.GetBlobHandle(Resource.BlobUrl + Resource.PublishSettingsFile, Resource.BlobKey); // Copy it to a local directory. using (FileStream fs = File.Create(localFile)) { blobRepo.Blob.DownloadToStream(fs); } } this.ImportAzurePublishSettingsFile(localFile); File.Delete(localFile); } internal void ImportAzurePublishSettingsFile(string publishSettingsFile) { ImportAzurePublishSettingsFileCmdletInfo importAzurePublishSettingsFileCmdlet = new ImportAzurePublishSettingsFileCmdletInfo(publishSettingsFile); WindowsAzurePowershellCmdlet importAzurePublishSettingsFile = new WindowsAzurePowershellCmdlet(importAzurePublishSettingsFileCmdlet); var i = importAzurePublishSettingsFile.Run(); Console.WriteLine(i.ToString()); } #endregion #region AzureSubscription public Collection<SubscriptionData> GetAzureSubscription() { return RunPSCmdletAndReturnAll<SubscriptionData>(new GetAzureSubscriptionCmdletInfo()); } public SubscriptionData GetCurrentAzureSubscription() { Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.IsDefault) { return subscription; } } return null; } public SubscriptionData SetAzureSubscription(string subscriptionName, string currentStorageAccount) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName, currentStorageAccount); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } public SubscriptionData SetDefaultAzureSubscription(string subscriptionName) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } #endregion #region AzureSubnet public SubnetNamesCollection GetAzureSubnet(PersistentVM vm) { GetAzureSubnetCmdletInfo getAzureSubnetCmdlet = new GetAzureSubnetCmdletInfo(vm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureSubnetCmdlet); Collection <PSObject> result = azurePowershellCmdlet.Run(); SubnetNamesCollection subnets = new SubnetNamesCollection(); foreach (PSObject re in result) { subnets.Add((string)re.BaseObject); } return subnets; } public PersistentVM SetAzureSubnet(PersistentVM vm, string [] subnetNames) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureSubnetCmdletInfo(vm, subnetNames)); } #endregion #region AzureStorageAccount public ManagementOperationContext NewAzureStorageAccount(string storageName, string locationName, string affinity, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureStorageAccountCmdletInfo(storageName, locationName, affinity, label, description)); } public StorageServicePropertiesOperationContext NewAzureStorageAccount(string storageName, string locationName) { NewAzureStorageAccount(storageName, locationName, null, null, null); Collection<StorageServicePropertiesOperationContext> storageAccounts = GetAzureStorageAccount(null); foreach (StorageServicePropertiesOperationContext storageAccount in storageAccounts) { if (storageAccount.StorageAccountName == storageName) return storageAccount; } return null; } public Collection<StorageServicePropertiesOperationContext> GetAzureStorageAccount(string accountName) { return RunPSCmdletAndReturnAll<StorageServicePropertiesOperationContext>(new GetAzureStorageAccountCmdletInfo(accountName)); } public ManagementOperationContext SetAzureStorageAccount(string accountName, string label, string description, bool geoReplication) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureStorageAccountCmdletInfo(accountName, label, description, geoReplication)); } public void RemoveAzureStorageAccount(string storageAccountName) { var removeAzureStorageAccountCmdletInfo = new RemoveAzureStorageAccountCmdletInfo(storageAccountName); var azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureStorageAccountCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); } #endregion #region AzureStorageKey public StorageServiceKeyOperationContext GetAzureStorageAccountKey(string stroageAccountName) { GetAzureStorageKeyCmdletInfo getAzureStorageKeyCmdletInfo = new GetAzureStorageKeyCmdletInfo(stroageAccountName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureStorageKeyCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (StorageServiceKeyOperationContext)result[0].BaseObject; } return null; } public StorageServiceKeyOperationContext NewAzureStorageAccountKey(string stroageAccountName, string keyType) { NewAzureStorageKeyCmdletInfo newAzureStorageKeyCmdletInfo = new NewAzureStorageKeyCmdletInfo(stroageAccountName, keyType); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureStorageKeyCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (StorageServiceKeyOperationContext)result[0].BaseObject; } return null; } #endregion #region AzureService public ManagementOperationContext NewAzureService(string serviceName, string location) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureServiceCmdletInfo(serviceName, location)); } internal void NewAzureService(string serviceName, string serviceLabel, string locationName) { NewAzureServiceCmdletInfo newAzureServiceCmdletInfo = new NewAzureServiceCmdletInfo(serviceName, serviceLabel, locationName); WindowsAzurePowershellCmdlet newAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(newAzureServiceCmdletInfo); Collection<PSObject> result = newAzureServiceCmdlet.Run(); } public void RemoveAzureService(string serviceName) { RemoveAzureServiceCmdletInfo removeAzureServiceCmdletInfo = new RemoveAzureServiceCmdletInfo(serviceName); WindowsAzurePowershellCmdlet removeAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(removeAzureServiceCmdletInfo); var result = removeAzureServiceCmdlet.Run(); } public HostedServiceDetailedContext GetAzureService(string serviceName) { return RunPSCmdletAndReturnFirst<HostedServiceDetailedContext>(new GetAzureServiceCmdletInfo(serviceName)); } #endregion #region AzureVM internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] VMs) { return NewAzureVM(serviceName, VMs, null, null, null, null, null, null, null, null); } internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] vms, string vnetName, DnsServer[] dnsSettings, string affinityGroup, string serviceLabel, string serviceDescription, string deploymentLabel, string deploymentDescription, string location) { return RunPSCmdletAndReturnAll<ManagementOperationContext>( new NewAzureVMCmdletInfo(serviceName, vms, vnetName, dnsSettings, affinityGroup, serviceLabel, serviceDescription, deploymentLabel, deploymentDescription, location)); } public PersistentVMRoleContext GetAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new GetAzureVMCmdletInfo(vmName, serviceName)); } public ManagementOperationContext RemoveAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVMCmdletInfo(vmName, serviceName)); } public void StartAzureVM(string vmName, string serviceName) { StartAzureVMCmdletInfo startAzureVMCmdlet = new StartAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(startAzureVMCmdlet); azurePowershellCmdlet.Run(); } public void StopAzureVM(string vmName, string serviceName) { StopAzureVMCmdletInfo stopAzureVMCmdlet = new StopAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(stopAzureVMCmdlet); azurePowershellCmdlet.Run(); } public void RestartAzureVM(string vmName, string serviceName) { RestartAzureVMCmdletInfo restartAzureVMCmdlet = new RestartAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(restartAzureVMCmdlet); azurePowershellCmdlet.Run(); } public PersistentVMRoleContext ExportAzureVM(string vmName, string serviceName, string path) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new ExportAzureVMCmdletInfo(vmName, serviceName, path)); } public Collection<PersistentVM> ImportAzureVM(string path) { return RunPSCmdletAndReturnAll<PersistentVM>(new ImportAzureVMCmdletInfo(path)); } public ManagementOperationContext UpdateAzureVM(string vmName, string serviceName, PersistentVM persistentVM) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new UpdateAzureVMCmdletInfo(vmName, serviceName, persistentVM)); } #endregion #region AzureVMImage public OSImageContext AddAzureVMImage(string imageName, string mediaLocation, OS os, string label = null) { return RunPSCmdletAndReturnFirst<OSImageContext>(new AddAzureVMImageCmdletInfo(imageName, mediaLocation, os, label)); } public OSImageContext AddAzureVMImage(string imageName, string mediaLocation, OS os, InstanceSize recommendedSize) { return RunPSCmdletAndReturnFirst<OSImageContext>(new AddAzureVMImageCmdletInfo(imageName, mediaLocation, os, null, recommendedSize)); } public OSImageContext UpdateAzureVMImage(string imageName, string label) { return RunPSCmdletAndReturnFirst<OSImageContext>(new UpdateAzureVMImageCmdletInfo(imageName, label)); } public OSImageContext UpdateAzureVMImage(string imageName, InstanceSize recommendedSize) { return RunPSCmdletAndReturnFirst<OSImageContext>(new UpdateAzureVMImageCmdletInfo(imageName, null, recommendedSize)); } public ManagementOperationContext RemoveAzureVMImage(string imageName, bool deleteVhd = false) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVMImageCmdletInfo(imageName, deleteVhd)); } public void SaveAzureVMImage(string serviceName, string vmName, string newVmName, string newImageName = null) { RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SaveAzureVMImageCmdletInfo(serviceName, vmName, newVmName, newImageName)); } public Collection<OSImageContext> GetAzureVMImage(string imageName = null) { return RunPSCmdletAndReturnAll<OSImageContext>(new GetAzureVMImageCmdletInfo(imageName)); } public string GetAzureVMImageName(string[] keywords, bool exactMatch = true) { Collection<OSImageContext> vmImages = GetAzureVMImage(); foreach (OSImageContext image in vmImages) { if (Utilities.MatchKeywords(image.ImageName, keywords, exactMatch) >= 0) return image.ImageName; } return null; } #endregion #region AzureVhd public string AddAzureVhdStop(FileInfo localFile, string destination, int ms) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, false, null)); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, false, null)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, string baseImage) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, false, baseImage)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, bool overwrite) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, overwrite, null)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, int numberOfUploaderThreads) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, numberOfUploaderThreads, false, null)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, int? numberOfUploaderThreads, bool overWrite) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, numberOfUploaderThreads, overWrite, null)); } public VhdDownloadContext SaveAzureVhd(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite) { return RunPSCmdletAndReturnFirst<VhdDownloadContext>(new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite)); } public string SaveAzureVhdStop(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite, int ms) { SaveAzureVhdCmdletInfo saveAzureVhdCmdletInfo = new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(saveAzureVhdCmdletInfo); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } #endregion #region AzureVnetConfig public Collection<VirtualNetworkConfigContext> GetAzureVNetConfig(string filePath) { return RunPSCmdletAndReturnAll<VirtualNetworkConfigContext>(new GetAzureVNetConfigCmdletInfo(filePath)); } public ManagementOperationContext SetAzureVNetConfig(string filePath) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureVNetConfigCmdletInfo(filePath)); } public ManagementOperationContext RemoveAzureVNetConfig() { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVNetConfigCmdletInfo()); } #endregion #region AzureVNetGateway public ManagementOperationContext NewAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureVNetGatewayCmdletInfo(vnetName)); } public Collection <VirtualNetworkGatewayContext> GetAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnAll<VirtualNetworkGatewayContext>(new GetAzureVNetGatewayCmdletInfo(vnetName)); } public ManagementOperationContext SetAzureVNetGateway(string option, string vnetName, string localNetwork) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureVNetGatewayCmdletInfo(option, vnetName, localNetwork)); } public ManagementOperationContext RemoveAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVNetGatewayCmdletInfo(vnetName)); } public SharedKeyContext GetAzureVNetGatewayKey(string vnetName, string localnet) { return RunPSCmdletAndReturnFirst<SharedKeyContext>(new GetAzureVNetGatewayKeyCmdletInfo(vnetName, localnet)); } #endregion #region AzureVNet public Collection<GatewayConnectionContext> GetAzureVNetConnection(string vnetName) { return RunPSCmdletAndReturnAll<GatewayConnectionContext>(new GetAzureVNetConnectionCmdletInfo(vnetName)); } public Collection<VirtualNetworkSiteContext> GetAzureVNetSite(string vnetName) { return RunPSCmdletAndReturnAll<VirtualNetworkSiteContext>(new GetAzureVNetSiteCmdletInfo(vnetName)); } #endregion public ManagementOperationContext GetAzureRemoteDesktopFile(string vmName, string serviceName, string localPath, bool launch) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new GetAzureRemoteDesktopFileCmdletInfo(vmName, serviceName, localPath, launch)); } internal PersistentVM GetPersistentVM(PersistentVMConfigInfo configInfo) { PersistentVM vm = null; if (null != configInfo) { if (configInfo.VmConfig != null) { vm = NewAzureVMConfig(configInfo.VmConfig); } if (configInfo.ProvConfig != null) { configInfo.ProvConfig.Vm = vm; vm = AddAzureProvisioningConfig(configInfo.ProvConfig); } if (configInfo.DiskConfig != null) { configInfo.DiskConfig.Vm = vm; vm = AddAzureDataDisk(configInfo.DiskConfig); } if (configInfo.EndPointConfig != null) { configInfo.EndPointConfig.Vm = vm; vm = AddAzureEndPoint(configInfo.EndPointConfig); } } return vm; } internal void AddVMDataDisks(string vmName, string serviceName, AddAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (AddAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = AddAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMDataDisks(string vmName, string serviceName, SetAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (SetAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMSize(string vmName, string serviceName, SetAzureVMSizeConfig vmSizeConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); vmSizeConfig.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureVMSize(vmSizeConfig); UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } private PersistentVM SetAzureVMSize(SetAzureVMSizeConfig sizeCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureVMSizeCmdletInfo(sizeCfg)); } internal void AddVMDataDisksAndEndPoint(string vmName, string serviceName, AddAzureDataDiskConfig[] dataDiskConfig, AzureEndPointConfigInfo endPointConfig) { AddVMDataDisks(vmName, serviceName, dataDiskConfig); AddEndPoint(vmName, serviceName, new [] {endPointConfig}); } } }
using System; using System.Globalization; using System.Numerics; using System.Text; using Reinterpret.Net; namespace Rs317.Sharp { public sealed class Default317Buffer : IBufferReadable, IBufferWriteable, IBuffer { /// <summary> /// Constant value that indicates if encryption is enabled. /// </summary> public const bool ENABLE_ENCRYPTION = false; //Luna-rs default RSA inputs. public static BigInteger? publicKey = BigInteger.Parse("1"); public static BigInteger? modulus = BigInteger.Parse("94306533927366675756465748344550949689550982334568289470527341681445613288505954291473168510012417401156971344988779343797488043615702971738296505168869556915772193568338164756326915583511871429998053169912492097791139829802309908513249248934714848531624001166946082342750924060600795950241816621880914628143"); //public static BigInteger? publicKey = null; //public static BigInteger? modulus = null; public byte[] buffer { get; } public int position { get; set; } public int bitPosition { get; private set; } private static int[] BIT_MASKS = { 0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 0x1ffff, 0x3ffff, 0x7ffff, 0xfffff, 0x1fffff, 0x3fffff, 0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff, 0x7ffffff, 0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, -1 }; internal Default317Buffer() { } public Default317Buffer(byte[] buf) { buffer = buf ?? throw new ArgumentNullException(nameof(buf)); position = 0; } public void finishBitAccess() { position = (bitPosition + 7) / 8; } public void generateKeys() { int tmpPos = position; position = 0; byte[] buf = new byte[tmpPos]; readBytes(tmpPos, 0, buf); BigInteger val1 = new BigInteger(buf); //MoparIsTheBest hackily only does RSA if input is defined //So we will do that too, for devs who want to enable RSA if (ENABLE_ENCRYPTION && publicKey != null && modulus != null) val1 = BigInteger.ModPow(val1, publicKey.Value, modulus.Value); byte[] finalBuf = val1.ToByteArray(); position = 0; put(finalBuf.Length); putBytes(finalBuf, finalBuf.Length, 0); } public byte get() { return buffer[position++]; } public int get3Bytes() { position += 3; return ((buffer[position - 3] & 0xff) << 16) + ((buffer[position - 2] & 0xff) << 8) + (buffer[position - 1] & 0xff); } public byte getByteC() { return (byte) (-buffer[position++]); } public void getBytes(int startPos, int endPos, byte[] buf) { for (int k = (endPos + startPos) - 1; k >= endPos; k--) buf[k] = buffer[position++]; } public byte getByteS() { return (byte) (128 - buffer[position++]); } public int getSignedLEShort() { position += 2; int j = ((buffer[position - 1] & 0xff) << 8) + (buffer[position - 2] & 0xff); if (j > 32767) j -= 0x10000; return j; } public int getSignedLEShortA() { position += 2; int j = ((buffer[position - 1] & 0xff) << 8) + (buffer[position - 2] - 128 & 0xff); if (j > 32767) j -= 0x10000; return j; } public int getInt() { position += 4; return ((buffer[position - 4] & 0xff) << 24) + ((buffer[position - 3] & 0xff) << 16) + ((buffer[position - 2] & 0xff) << 8) + (buffer[position - 1] & 0xff); } public int getMEBInt() { // Middle endian big int: C3 D4 A1 B2 (A1 smallest D4 biggest byte) position += 4; return ((buffer[position - 3] & 0xff) << 24) + ((buffer[position - 4] & 0xff) << 16) + ((buffer[position - 1] & 0xff) << 8) + (buffer[position - 2] & 0xff); } public int getMESInt() { // Middle endian small int: B2 A1 D4 C3 (A1 smallest D4 biggest byte) position += 4; return ((buffer[position - 2] & 0xff) << 24) + ((buffer[position - 1] & 0xff) << 16) + ((buffer[position - 4] & 0xff) << 8) + (buffer[position - 3] & 0xff); } public long getLong() { long ms = getInt() & 0xffffffffL; long ls = getInt() & 0xffffffffL; return (ms << 32) + ls; } public int getShort() { position += 2; int i = ((buffer[position - 2] & 0xff) << 8) + (buffer[position - 1] & 0xff); if (i > 32767) i -= 0x10000; return i; } public int getSmartA() { int i = buffer[position] & 0xff; if (i < 128) return getUnsignedByte() - 64; else return getUnsignedLEShort() - 49152; } public int getSmartB() { int i = buffer[position] & 0xff; if (i < 128) return getUnsignedByte(); else return getUnsignedLEShort() - 32768; } public String getString() { int i = position; while (buffer[position++] != 10) ; return Encoding.ASCII.GetString(buffer, i, position - i - 1); } public int getUnsignedByte() { return buffer[position++] & 0xff; } public int getUnsignedByteA() { return buffer[position++] - 128 & 0xff; } public int getUnsignedByteC() { return -buffer[position++] & 0xff; } public int getUnsignedByteS() { return 128 - buffer[position++] & 0xff; } public int getUnsignedLEShort() { position += 2; return ((buffer[position - 2] & 0xff) << 8) + (buffer[position - 1] & 0xff); } public int getUnsignedLEShortA() { position += 2; return ((buffer[position - 2] & 0xff) << 8) + (buffer[position - 1] - 128 & 0xff); } public int getUnsignedShort() { position += 2; return ((buffer[position - 1] & 0xff) << 8) + (buffer[position - 2] & 0xff); } public int getUnsignedShortA() { position += 2; return ((buffer[position - 1] & 0xff) << 8) + (buffer[position - 2] - 128 & 0xff); } public void initBitAccess() { bitPosition = position * 8; } public void put(int i) { buffer[position++] = (byte) i; } public void put24BitInt(int i) { buffer[position++] = (byte) (i >> 16); buffer[position++] = (byte) (i >> 8); buffer[position++] = (byte) i; } public void putByteC(int i) { buffer[position++] = (byte) (-i); } public void putBytes(byte[] buf, int length, int startPosition) { for (int k = startPosition; k < startPosition + length; k++) buffer[position++] = buf[k]; } public void putByteS(int j) { buffer[position++] = (byte) (128 - j); } public void putBytesA(int i, byte[] buf, int j) { for (int k = (i + j) - 1; k >= i; k--) buffer[position++] = (byte) (buf[k] + 128); } public void putInt(int i) { buffer[position++] = (byte) (i >> 24); buffer[position++] = (byte) (i >> 16); buffer[position++] = (byte) (i >> 8); buffer[position++] = (byte) i; } public void putLEInt(int j) { buffer[position++] = (byte) j; buffer[position++] = (byte) (j >> 8); buffer[position++] = (byte) (j >> 16); buffer[position++] = (byte) (j >> 24); } public void putLEShort(int i) { buffer[position++] = (byte) i; buffer[position++] = (byte) (i >> 8); } public void putLEShortA(int j) { buffer[position++] = (byte) (j + 128); buffer[position++] = (byte) (j >> 8); } public void putLong(long l) { try { buffer[position++] = (byte) (int) (l >> 56); buffer[position++] = (byte) (int) (l >> 48); buffer[position++] = (byte) (int) (l >> 40); buffer[position++] = (byte) (int) (l >> 32); buffer[position++] = (byte) (int) (l >> 24); buffer[position++] = (byte) (int) (l >> 16); buffer[position++] = (byte) (int) (l >> 8); buffer[position++] = (byte) (int) l; } catch (Exception ex) { Console.WriteLine("14395, " + 5 + ", " + l + ", " + ex.ToString()); throw new InvalidOperationException($"Failed to {nameof(putLong)}"); } } public void putOpcode(int i) { buffer[position++] = (byte)i; } public void putShort(int i) { buffer[position++] = (byte) (i >> 8); buffer[position++] = (byte) i; } public void putShortA(int j) { buffer[position++] = (byte) (j >> 8); buffer[position++] = (byte) (j + 128); } public void putSizeByte(int i) { buffer[position - i - 1] = (byte) i; } public void putString(String s) { // s.getBytes(0, s.length(), buffer, currentOffset); //deprecated System.Buffer.BlockCopy(s.Reinterpret(Encoding.ASCII), 0, buffer, position, s.Length); position += s.Length; buffer[position++] = 10; } public int readBits(int i) { int k = bitPosition >> 3; int l = 8 - (bitPosition & 7); int val = 0; bitPosition += i; for (; i > l; l = 8) { val += (buffer[k++] & BIT_MASKS[l]) << i - l; i -= l; } if (i == l) val += buffer[k] & BIT_MASKS[l]; else val += buffer[k] >> l - i & BIT_MASKS[i]; return val; } public byte[] readBytes() { int tmpPos = position; //Skip while (buffer[position++] != 10) { } byte[] buf = new byte[position - tmpPos - 1]; System.Buffer.BlockCopy(buffer, tmpPos, buf, tmpPos - tmpPos, position - 1 - tmpPos); return buf; } public void readBytes(int length, int startPosition, byte[] dest) { for (int i = startPosition; i < startPosition + length; i++) dest[i] = buffer[position++]; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HWPF.Model { using System; using NPOI.Util; using NPOI.HWPF.UserModel; using NPOI.HWPF.SPRM; using NPOI.HWPF.Model.IO; /** * Represents a document's stylesheet. A word documents formatting is stored as * compressed styles that are based on styles Contained in the stylesheet. This * class also Contains static utility functions to uncompress different * formatting properties. * * @author Ryan Ackley */ public class StyleSheet { public const int NIL_STYLE = 4095; private const int PAP_TYPE = 1; private const int CHP_TYPE = 2; private const int SEP_TYPE = 4; private const int TAP_TYPE = 5; private static ParagraphProperties NIL_PAP = new ParagraphProperties(); private static CharacterProperties NIL_CHP = new CharacterProperties(); private int _stshiLength; private int _baseLength; private int _flags; private int _maxIndex; private int _maxFixedIndex; private int _stylenameVersion; private int[] _rgftc; StyleDescription[] _styleDescriptions; /** * StyleSheet constructor. Loads a document's stylesheet information, * * @param tableStream A byte array Containing a document's raw stylesheet * info. Found by using FileInformationBlock.GetFcStshf() and * FileInformationBLock.GetLcbStshf() */ public StyleSheet(byte[] tableStream, int offset) { int startoffset = offset; _stshiLength = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; int stdCount = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _baseLength = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _flags = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _maxIndex = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _maxFixedIndex = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _stylenameVersion = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _rgftc = new int[3]; _rgftc[0] = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _rgftc[1] = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; _rgftc[2] = LittleEndian.GetShort(tableStream, offset); offset += LittleEndianConsts.SHORT_SIZE; offset = startoffset + LittleEndianConsts.SHORT_SIZE + _stshiLength; _styleDescriptions = new StyleDescription[stdCount]; for (int x = 0; x < stdCount; x++) { int stdSize = LittleEndian.GetShort(tableStream, offset); //get past the size offset += 2; if (stdSize > 0) { //byte[] std = new byte[stdSize]; StyleDescription aStyle = new StyleDescription(tableStream, _baseLength, offset, true); _styleDescriptions[x] = aStyle; } offset += stdSize; } for (int x = 0; x < _styleDescriptions.Length; x++) { if (_styleDescriptions[x] != null) { CreatePap(x); CreateChp(x); } } } public void WriteTo(HWPFStream out1) { int offset = 0; // add two bytes so we can prepend the stylesheet w/ its size byte[] buf = new byte[_stshiLength + 2]; LittleEndian.PutShort(buf, offset, (short)_stshiLength); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_styleDescriptions.Length); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_baseLength); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_flags); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_maxIndex); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_maxFixedIndex); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_stylenameVersion); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_rgftc[0]); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_rgftc[1]); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, (short)_rgftc[2]); out1.Write(buf); byte[] sizeHolder = new byte[2]; for (int x = 0; x < _styleDescriptions.Length; x++) { if (_styleDescriptions[x] != null) { byte[] std = _styleDescriptions[x].ToArray(); // adjust the size so it is always on a word boundary LittleEndian.PutShort(sizeHolder, (short)((std.Length) + (std.Length % 2))); out1.Write(sizeHolder); out1.Write(std); // Must always start on a word boundary. if (std.Length % 2 == 1) { out1.Write('\0'); } } else { sizeHolder[0] = 0; sizeHolder[1] = 0; out1.Write(sizeHolder); } } } public override bool Equals(Object o) { StyleSheet ss = (StyleSheet)o; if (ss._baseLength == _baseLength && ss._flags == _flags && ss._maxFixedIndex == _maxFixedIndex && ss._maxIndex == _maxIndex && ss._rgftc[0] == _rgftc[0] && ss._rgftc[1] == _rgftc[1] && ss._rgftc[2] == _rgftc[2] && ss._stshiLength == _stshiLength && ss._stylenameVersion == _stylenameVersion) { if (ss._styleDescriptions.Length == _styleDescriptions.Length) { for (int x = 0; x < _styleDescriptions.Length; x++) { // check for null if (ss._styleDescriptions[x] != _styleDescriptions[x]) { // check for Equality if (!ss._styleDescriptions[x].Equals(_styleDescriptions[x])) { return false; } } } return true; } } return false; } /** * Creates a PartagraphProperties object from a papx stored in the * StyleDescription at the index istd in the StyleDescription array. The PAP * is placed in the StyleDescription at istd after its been Created. Not * every StyleDescription will contain a papx. In these cases this function * does nothing * * @param istd The index of the StyleDescription to create the * ParagraphProperties from (and also place the finished PAP in) */ private void CreatePap(int istd) { StyleDescription sd = _styleDescriptions[istd]; ParagraphProperties pap = sd.GetPAP(); byte[] papx = sd.GetPAPX(); int baseIndex = sd.GetBaseStyle(); if (pap == null && papx != null) { ParagraphProperties parentPAP = new ParagraphProperties(); if (baseIndex != NIL_STYLE) { parentPAP = _styleDescriptions[baseIndex].GetPAP(); if (parentPAP == null) { if (baseIndex == istd) { // Oh dear, style claims that it is its own parent throw new InvalidOperationException("Pap style " + istd + " claimed to have itself as its parent, which isn't allowed"); } // Create the parent style CreatePap(baseIndex); parentPAP = _styleDescriptions[baseIndex].GetPAP(); } } pap = ParagraphSprmUncompressor.UncompressPAP(parentPAP, papx, 2); sd.SetPAP(pap); } } /** * Creates a CharacterProperties object from a chpx stored in the * StyleDescription at the index istd in the StyleDescription array. The * CharacterProperties object is placed in the StyleDescription at istd after * its been Created. Not every StyleDescription will contain a chpx. In these * cases this function does nothing. * * @param istd The index of the StyleDescription to create the * CharacterProperties object from. */ private void CreateChp(int istd) { StyleDescription sd = _styleDescriptions[istd]; CharacterProperties chp = sd.GetCHP(); byte[] chpx = sd.GetCHPX(); int baseIndex = sd.GetBaseStyle(); if (baseIndex == istd) { // Oh dear, this isn't allowed... // The word file seems to be corrupted // Switch to using the nil style so that // there's a chance we can read it baseIndex = NIL_STYLE; } // Build and decompress the Chp if required if (chp == null && chpx != null) { CharacterProperties parentCHP = new CharacterProperties(); if (baseIndex != NIL_STYLE) { parentCHP = _styleDescriptions[baseIndex].GetCHP(); if (parentCHP == null) { CreateChp(baseIndex); parentCHP = _styleDescriptions[baseIndex].GetCHP(); } } chp = CharacterSprmUncompressor.UncompressCHP(parentCHP, chpx, 0); sd.SetCHP(chp); } } /** * Gets the number of styles in the style sheet. * @return The number of styles in the style sheet. */ public int NumStyles() { return _styleDescriptions.Length; } /** * Gets the StyleDescription at index x. * * @param x the index of the desired StyleDescription. */ public StyleDescription GetStyleDescription(int x) { return _styleDescriptions[x]; } public CharacterProperties GetCharacterStyle(int x) { if (x == NIL_STYLE) { return NIL_CHP; } if (x >= _styleDescriptions.Length) { return NIL_CHP; } return (_styleDescriptions[x] != null ? _styleDescriptions[x].GetCHP() : NIL_CHP); } public ParagraphProperties GetParagraphStyle(int x) { if (x == NIL_STYLE) { return NIL_PAP; } if (x >= _styleDescriptions.Length) { return NIL_PAP; } if (_styleDescriptions[x] == null) { return NIL_PAP; } if (_styleDescriptions[x].GetPAP() == null) { return NIL_PAP; } return _styleDescriptions[x].GetPAP(); } } }
// FileSystemScanner.cs // // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. #if ZIPLIB using System; namespace ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> internal class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> internal class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields string name_; long processed_; long target_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments for directories. /// </summary> internal class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base (name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } #region Instance Fields bool hasMatchingFiles_; #endregion } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> internal class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; Exception exception_; bool continueRunning_; #endregion } #endregion #region Delegates /// <summary> /// Delegate invoked before starting to process a directory. /// </summary> internal delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> internal class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { fileFilter_ = new PathFilter(fileFilter); directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { fileFilter_ = fileFilter; directoryFilter_ = directoryFilter; } #endregion #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public ProcessDirectoryHandler ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if ( result ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); handler(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if ( result ){ ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if ( handler!= null ) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> void OnProcessDirectory(string directory, bool hasMatchingFiles) { ProcessDirectoryHandler handler = ProcessDirectory; if ( handler != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> public void Scan(string directory, bool recurse) { alive_ = true; ScanDir(directory, recurse); } void ScanDir(string directory, bool recurse) { try { string[] names = System.IO.Directory.GetFiles(directory); bool hasMatch = false; for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { if ( !fileFilter_.IsMatch(names[fileIndex]) ) { names[fileIndex] = null; } else { hasMatch = true; } } OnProcessDirectory(directory, hasMatch); if ( alive_ && hasMatch ) { foreach (string fileName in names) { try { if ( fileName != null ) { OnProcessFile(fileName); if ( !alive_ ) { break; } } } catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } if ( alive_ && recurse ) { try { string[] names = System.IO.Directory.GetDirectories(directory); foreach (string fulldir in names) { if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { ScanDir(fulldir, true); if ( !alive_ ) { break; } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } } } #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> bool alive_; #endregion } } #endif
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Configuration; using System.Data; namespace Desition { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { //private int count=1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Timer timer1; private int c=0; public int max; public string max_path; private System.ComponentModel.IContainer components; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.textBox5 = new System.Windows.Forms.TextBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.textBox7 = new System.Windows.Forms.TextBox(); this.textBox8 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(248, 40); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(32, 20); this.textBox1.TabIndex = 0; this.textBox1.Text = ""; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(376, 168); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(32, 20); this.textBox2.TabIndex = 3; this.textBox2.Text = ""; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(152, 208); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(32, 20); this.textBox3.TabIndex = 5; this.textBox3.Text = ""; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(112, 104); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(32, 20); this.textBox4.TabIndex = 7; this.textBox4.Text = ""; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(376, 144); this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(32, 20); this.textBox5.TabIndex = 9; this.textBox5.Text = ""; // // textBox6 // this.textBox6.Location = new System.Drawing.Point(288, 40); this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(32, 20); this.textBox6.TabIndex = 10; this.textBox6.Text = ""; // // textBox7 // this.textBox7.Location = new System.Drawing.Point(192, 208); this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(32, 20); this.textBox7.TabIndex = 11; this.textBox7.Text = ""; // // textBox8 // this.textBox8.Location = new System.Drawing.Point(112, 80); this.textBox8.Name = "textBox8"; this.textBox8.Size = new System.Drawing.Size(32, 20); this.textBox8.TabIndex = 12; this.textBox8.Text = ""; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(184, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(112, 24); this.label1.TabIndex = 1; this.label1.Text = "\'A1\' Path"; // // label2 // this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label2.Location = new System.Drawing.Point(424, 136); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(88, 24); this.label2.TabIndex = 2; this.label2.Text = "\'B1\' Path"; // // label3 // this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label3.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label3.Location = new System.Drawing.Point(104, 248); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(104, 32); this.label3.TabIndex = 4; this.label3.Text = "\'C2\' Path"; // // label4 // this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label4.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label4.Location = new System.Drawing.Point(16, 80); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(88, 24); this.label4.TabIndex = 6; this.label4.Text = "\'D2\' Path"; // // label5 // this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label5.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label5.Location = new System.Drawing.Point(16, 112); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(88, 24); this.label5.TabIndex = 13; this.label5.Text = "\'D1\' Path"; // // label6 // this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label6.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label6.Location = new System.Drawing.Point(424, 168); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(88, 24); this.label6.TabIndex = 14; this.label6.Text = "\'B2\' Path"; // // label7 // this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label7.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label7.Location = new System.Drawing.Point(296, 8); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(112, 24); this.label7.TabIndex = 15; this.label7.Text = "\'A2\' Path"; // // label8 // this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(0))); this.label8.Location = new System.Drawing.Point(192, 248); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(104, 32); this.label8.TabIndex = 16; this.label8.Text = "\'C1\' Path"; // // button1 // this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button1.ForeColor = System.Drawing.Color.Blue; this.button1.Location = new System.Drawing.Point(216, 112); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(72, 32); this.button1.TabIndex = 8; this.button1.Text = "Start"; this.button1.Click += new System.EventHandler(this.button1_Click); // // timer1 // this.timer1.Interval = 5000; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(512, 294); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.textBox8); this.Controls.Add(this.textBox7); this.Controls.Add(this.textBox6); this.Controls.Add(this.textBox5); this.Controls.Add(this.textBox4); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Desition Making"; this.ResumeLayout(false); } private void timer1_Tick(object sender, System.EventArgs e) { c++; Start_click(c); //display(c); } private void Start_click(int a) { int [] desition = new int[3]; int A1=Int32.Parse(textBox1.Text); int A2=Int32.Parse(textBox6.Text); int B1=Int32.Parse(textBox2.Text); int B2=Int32.Parse(textBox5.Text); int C1=Int32.Parse(textBox7.Text); int C2=Int32.Parse(textBox3.Text); int D1=Int32.Parse(textBox8.Text); int D2=Int32.Parse(textBox4.Text); if(c<2 ) { try { if (A1>A2 & A1>B1 & A1>B2 & A1>C1 & A1>C2 & A1>D1 & A1>D2) { //campare(A); max =A1; MessageBox.Show(max.ToString(),"Case 1"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="A1"; } else if (A2>A1 & A2>B1 & A2>B2 & A2>C1 & A2>C2 & A2>D1 & A2>D2) { max =A2; MessageBox.Show(max.ToString(),"Case 3"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="A2"; } else if (B1>A1 & B1>A2 & B1>B2 & B1>C1 & B1>C2 & B1>D1 & B1>D2) { max =B1; MessageBox.Show(max.ToString(),"Case 2"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="B1"; } else if (B2>A1 & B2>A2 & B2>B1 & B2>C1 & B2>C2 & B2>D1 & B2>D2) { max =B2; MessageBox.Show(max.ToString(),"Case 4"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="B2"; } else if (C1>A1 & C1>A2 & C1>B1 & C1>B2 & C1>C2 & C1>D1 & C1>D2) { max =C1; MessageBox.Show(max.ToString(),"Case 1"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="C1"; } else if (C2>A1 & C2>A2 & C2>B1 & C2>B2 & C2>C1 & C2>D1 & C2>D2) { max =C2; MessageBox.Show(max.ToString(),"Case 5"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="C2"; } else if (D1>A1 & D1>A2 & D1>B1 & D1>B2 & D1>C1 & D1>C2 & D1>D2) { max =D1; MessageBox.Show(max.ToString(),"Case 2"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="D1"; } else if (D2>A1 & D2>A2 & D2>B1 & D2>B2 & D2>C1 & D2>C2 & D2>D1) { max =D2; MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; max_path ="D2"; } else if ((A1==A2) & A1>B1 & A1>B2 & A1>C1 & A1>C2 & A1>D1 & A1>D2) { MessageBox.Show("A1A2"); MessageBox.Show(max.ToString(),"Case 3"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A1==B1) & A1>A2 & A1>B2 & A1>C1 & A1>C2 & A1>D1 & A1>D2) { MessageBox.Show("A1B1"); MessageBox.Show(max.ToString(),"Case 1"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A1==B2) & A1>A2 & A1>B1 & A1>C1 & A1>C2 & A1>D1 & A1>D2) { MessageBox.Show("A1B2"); MessageBox.Show(max.ToString(),"Case 4"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A1==C1) & A1>A2 & A1>B1 & A1>B2 & A1>C2 & A1>D1 & A1>D2) { MessageBox.Show("A1C1"); MessageBox.Show(max.ToString(),"Case 1"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A1==C2) & A1>A2 & A1>B1 & A1>B2 & A1>C1 & A1>D1 & A1>D2) { MessageBox.Show("A1C2"); MessageBox.Show(max.ToString(),"Case 5"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A1==D1) & A1>A2 & A1>B1 & A1>B2 & A1>C1 & A1>C2 & A1>D2) { MessageBox.Show("A1D1"); MessageBox.Show(max.ToString(),"Case 2"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A1==D2) & A1>A2 & A1>B1 & A1>B2 & A1>C1 & A1>C2 & A1>D1) { MessageBox.Show("A1D2"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A2==B1) & A2>A1 & A2>B2 & A2>C1 & A2>C2 & A2>D1 & A2>D2) { MessageBox.Show("A2B1"); MessageBox.Show(max.ToString(),"Case 3"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A2==B2) & A2>A1 & A2>B1 & A2>C1 & A2>C2 & A2>D1 & A2>D2) { MessageBox.Show("A2B2"); MessageBox.Show(max.ToString(),"Case 3"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A2==C1) & A2>A1 & A2>B1 & A2>B2 & A2>C2 & A2>D1 & A2>D2) { MessageBox.Show("A2C1"); MessageBox.Show(max.ToString(),"Case 1"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A2==C2) & A2>A1 & A2>B1 & A2>B2 & A2>C1 & A2>D1 & A2>D2) { MessageBox.Show("A2C2"); MessageBox.Show(max.ToString(),"Case 5"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A2==D1) & A2>A1 & A2>B1 & A2>B2 & A2>C1 & A2>C2 & A2>D2) { MessageBox.Show("A2D1"); MessageBox.Show(max.ToString(),"Case 2"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A2==D2) & A2>A1 & A2>B1 & A2>B2 & A2>C1 & A2>C2 & A2>D1) { MessageBox.Show("A2D2"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B1==B2) & B1>A1 & B1>A2 &B1>C1 &B1>C2 &B1>D1 & B1>D2) { MessageBox.Show("B1B2"); MessageBox.Show(max.ToString(),"Case 2"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B1==C1) & B1>A1 & B1>A2 & B1>B2 & B1>C2 & B1>D1 & B1>D2) { MessageBox.Show("B1C1"); MessageBox.Show(max.ToString(),"Case 4"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B1==C2) & B1>A1 & B1>A2 & B1>B2 & B1>C1 & B1>D1 & B1>D2) { MessageBox.Show("B1C2"); MessageBox.Show(max.ToString(),"Case 5"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B1==D1) & B1>A1 & B1>A2 & B1>B2 & B1>C1 & B1>C2 & B1>D2) { MessageBox.Show("B1D1"); MessageBox.Show(max.ToString(),"Case 2"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B1==D2) & B1>A1 & B1>A2 & B1>B2 & B1>C1 & B1>C2 & B1>D1) { MessageBox.Show("B1D2"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B2==C1) & B2>A1 & B2>A2 & B2>B1 & B2>C2 & B2>D1 & B2>D2) { MessageBox.Show("B2C1"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B2==C2) & B2>A1 & B2>A2 & B2>B1 & B2>C1 & B2>D1 & B2>D2) { MessageBox.Show("B2C2"); MessageBox.Show(max.ToString(),"Case 5"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B2==D1) & B2>A1 & B2>A2 & B2>B1 & B2>C1 & B2>C2 & B2>D2) { MessageBox.Show("B2D1"); MessageBox.Show(max.ToString(),"Case 2"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((B2==D2) & B2>A1 & B2>A2 & B2>B1 & B2>C1 & B2>C2 & B2>D1) { MessageBox.Show("B2D2"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((C1==C2) & C1>A1 & C1>A2 & C1>B1 & C1>B2 & C1>D1 & C1>D2) { MessageBox.Show("C1C2"); MessageBox.Show(max.ToString(),"Case 5"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((C1==D1) & C1>A1 & C1>A2 & C1>B1 & C1>B2 & C1>C2 & C1>D2) { MessageBox.Show("C1D1"); MessageBox.Show(max.ToString(),"Case 1"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((C1==D2) & C1>A1 & C1>A2 & C1>B1 & C1>B2 & C1>C2 & C1>D1) { MessageBox.Show("C1D2"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((C2==D1) & C2>A1 & C2>A2 & C2>B1 & C2>B2 & C2>C1 & C2>D2) { MessageBox.Show("C2D1"); MessageBox.Show(max.ToString(),"Case 5"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((C2==D2) & C2>A1 & C2>A2 & C2>B1 & C2>B2 & C2>C1 & C2>D1) { MessageBox.Show("C2D2"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((D1==D2) & D1>A1 &D1>A2 &D1>B1 &D1>B2 & D1>C1 & D1>C2) { MessageBox.Show("D1D2"); MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } else if ((A1==A2)& (A2==B1) & (A1==B1) & A1>B2 & A1>C1 & A1>C2 & A1>D1 & A1>D2) { MessageBox.Show(max.ToString(),"Case 6"); if (max == 15) this.timer1.Interval = 15000; if (max == (14 | 13)) this.timer1.Interval = 13000; if (max == (12 | 11)) this.timer1.Interval = 12000; if (max == (09 | 10)) this.timer1.Interval = 10000; if (max == (06 | 07 | 08)) this.timer1.Interval = 8000; if (max == (01 | 02 | 03 | 04 | 05)) this.timer1.Interval = 5000; } //need to add code here else if (((A1==A2)& (B1==B2)& (C1==C2)& (A1 ==B1) & (A1== C1)) & A1>D1 & A1>D2) { MessageBox.Show("A1A2B1B2C1C2"); } else if (((A1==A2)& (B1==B2)& (C1==D1)& (A1==B1) & (A1==C1)) & A1>C2 & A1>D2) { MessageBox.Show("A1A2B1B2C1D1"); } else if (((A1==A2)& (B1==B2)& (C1==D2)& (A1==B1) & (A1==C1)) & A1>C2 & A1>D1) { MessageBox.Show("A1A2B1B2C1D2"); } else if (((A1==A2)& (B1==B2)& (C2==D1)& (A1==B1) & (A1==C2)) & A1>C1 & A1>D2) { MessageBox.Show("A1A2B1B2C2D1"); } else if (((A1==A2)& (B1==B2)& (C2==D2)& (A1==B1) & (A1==C2)) & A1>C1 & A1>D1) { MessageBox.Show("A1A2B1B2C1D2"); } else if (((A1==A2)& (B1==B2)& (D1==D2)& (A1==B1) & (A1==D1)) & A1>C1 & A1>C2) { MessageBox.Show("A1A2B1B2D1D2"); } else if (((A1==A2)& (B1==C1)& (C2==D1)& (A1==B1) & (A1==C2)) & A1>B2 & A1>D2) { MessageBox.Show("A1A2B1C1C2D1"); } else if (((A1==A2)& (B1==C1)& (C2==D2)& (A1==B1) & (A1==C2)) & A1>B2 & A1>D1) { MessageBox.Show("A1A2B1C1C2D2"); } else if (((A1==A2)& (B1==C1)& (D1==D2)& (A1==B1) & (A1==D1)) & A1>B2 & A1>C2) { MessageBox.Show("A1A2B1C1D1D2"); } else if (((A1==A2)& (B1==C2)& (D1==D2)& (A1==B1) & (A1==D1)) & A1>B2 & A1>C1) { MessageBox.Show("A1A2B1C2D1D2"); } else if (((A1==A2)& (B2==C1)& (C2==D1)& (A1==B2) & (A1==C2)) & A1>B1 & A1>D2) { MessageBox.Show("A1A2B2C1C2D1"); } else if (((A1==A2)& (B2==C1)& (C2==D2)& (A1==B2) & (A1==C2)) & A1>B1 & A1>D1) { MessageBox.Show("A1A2B2C1C2D2"); } else if (((A1==A2)& (B2==C1)& (D1==D2)& (A1==B2) & (A1==D1)) & A1>B1 & A1>C2) { MessageBox.Show("A1A2B2C1D1D2"); } else if (((A1==A2)& (B2==C2)& (D1==D2)& (A1==B2) & (A1==D1)) & A1>B1 & A1>C1) { MessageBox.Show("A1A2B2C2D1D2"); } else if (((A1==A2)& (C1==C2)& (D1==D2)& (A1==C1) & (A1==D1)) & A1>B1 & A1>B2) { MessageBox.Show("A1A2C1C2D1D2"); } else if (((A1==B1)& (B2==C1)& (C2==D1)& (A1==B2) & (A1==C2)) & A1>A2 & A1>D2) { MessageBox.Show("A1B1B2C1C2D1"); } else if (((A1==B1)& (B2==C1)& (C2==D2)& (A1==B2) & (A1==C2)) & A1>A2 & A1>D1) { MessageBox.Show("A1B1B2C1C2D2"); } else if (((A1==B1)& (B2==C2)& (D1==D2)& (A1==B2) & (A1==D1)) & A1>A2 & A1>C1) { MessageBox.Show("A1B1B2C2D1D2"); } else if (((A1==B1)& (C1==C2)& (D1==D2)& (A1==C1) & (A1==D1)) & A1>A2 & A1>B2) { MessageBox.Show("A1B1C1C2D1D2"); } else if (((A1==B2)& (C1==C2)& (D1==D2)& (A1==C1) & (A1==D1)) & A1>A2 & A1>B1) { MessageBox.Show("A1B2C1C2D1D2"); } else if (((A2==B1)& (B2==C1)& (C2==D1)& (A2==B2) & (A2==C2)) & A2>A1 & A1>D2) { MessageBox.Show("A2B1B2C1C2D1"); } else if (((A2==B1)& (B2==C1)& (C2==D2)& (A2==B2) & (A2==C2)) & A2>A1 & A1>D1) { MessageBox.Show("A2B1B2C1C2D2"); } else if (((A2==B1)& (B2==C2)& (D1==D2)& (A2==B2) & (A2==D1)) & A2>A1 & A1>C1) { MessageBox.Show("A2B1B2C2D1D2"); } else if (((A2==B1)& (C1==C2)& (D1==D2)& (A2==C1) & (A2==D1)) & A2>A1 & A1>B2) { MessageBox.Show("A2B1C1C2D1D2"); } else if (((A2==B2)& (C1==C2)& (D1==D2)& (A2==C1) & (A2==D1)) & A2>A1 & A1>B1) { MessageBox.Show("A2B2C1C2D1D2"); } else if (((B1==B2)& (C1==C2)& (D1==D2)& (B1==C1) & (B1==D1)) & B1>A1 & B1>A2) { MessageBox.Show("B1B2C1C2D1D2"); } else if (((A1==A2)& (B1==B2)& (C1==C2)& (A1==B1) & (A1==C1) & (A1==D1)) & A1>D2) { MessageBox.Show("A1A2B1B2C1C2D1"); } else if (((A1==A2)& (B1==B2)& (C1==C2)& (A1==B1) & (A1==C1) & (A1==D2)) & A1>D1) { MessageBox.Show("A1A2B1B2C1C2D2"); } else if (((A1==A2)& (B1==B2)& (C1==D1)& (A1==B1) & (A1==C1) & (A1==D2)) & A1>C2) { MessageBox.Show("A1A2B1B2C1D1D2"); } else if (((A1==A2)& (B1==B2)& (C2==D1)& (A1==B1) & (A1==C2) & (A1==D2)) & A1>C1) { MessageBox.Show("A1A2B1B2C2D1D2"); } else if (((A1==A2)& (B1==C1)& (C2==D1)& (A1==B1) & (A1==C2) & (A1==D2)) & A1>B2) { MessageBox.Show("A1A2B2C1C2D1D2"); } else if (((A1==A2)& (B2==C1)& (C2==D1)& (A1==B2) & (A1==C2) & (A1==D2)) & A1>B1) { MessageBox.Show("A1A2B2C1C2D1D2"); } else if (((A1==B1)& (B2==C1)& (C2==D1)& (A1==B2) & (A1==C2) & (A1==D2)) & A1>A2) { MessageBox.Show("A1B1B2C1C2D1D2"); } else if (((A2==B1)& (B2==C1)& (C2==D1)& (A2==B2) & (A2==C2) & (A2==D2)) & A2>A1) { MessageBox.Show("A1B1B2C1C2D1D2"); } else if ((A1==A2) &(B1==B2) &(C1==C2) &(D1==D2) & (A1==B1) &(A1==C1) &(A1==D1)) { MessageBox.Show("All"); } else { MessageBox.Show("others"); } } /* private void label4_Click(object sender, System.EventArgs e) { } private void button1_Click(object sender, System.EventArgs e) { }*/ catch(Exception) { MessageBox.Show("Invalid Input"); } timer1.Start (); } else { c=0; Start_click(c); } /*int vehi1=2; int vehi2=4; int vehi3=6; int vehi4=8; int vehi5=10; int vehi6=12; int vehi7=14; int vehi8=16; int vehi9=18; int vehi10=20; int vehi11=22; int vehi12=24; int vehi13=26; int vehi14=28; int vehi15=30; int vehi16=32; int vehi17=34; int vehi18=36; int vehi19=38; int time; //int count=2; if(count = 1) time=2; else if(count = 2) time = 4; else if (count = 3) time = 6; else if (count = 4) time = 8; else if (count = 5) time = 10; else if (count = 6) time = 12; else if (count = 7) time = 14; else if (count = 8) time = 16; else if (count = 9) time = 18; else if (count = 10) time = 20; else if (count = 11) time = 22; else if (count = 12) time = 24; else if (count =13 ) time = 26; else if (count = 14) time =28; else if (count = 15) time = 30; else if (count = 16) time = 32; else if (count =17) time = 34; else if (count = 18) time = 36; else if (count = 19) time = 38; else if (count = 20) time = 40; */ } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void button1_Click(object sender, System.EventArgs e) { Start_click(c); } private void campare(int m) { int e=m; } } }
/* * Copyright (c) 2006-2008, Second Life Reverse Engineering Team * 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. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using libsecondlife; using libsecondlife.Packets; namespace libsecondlife { public partial class AgentManager { #region Enums /// <summary> /// Used to specify movement actions for your agent /// </summary> [Flags] public enum ControlFlags { /// <summary>Empty flag</summary> NONE = 0, /// <summary>Move Forward (SL Keybinding: W/Up Arrow)</summary> AGENT_CONTROL_AT_POS = 0x1 << CONTROL_AT_POS_INDEX, /// <summary>Move Backward (SL Keybinding: S/Down Arrow)</summary> AGENT_CONTROL_AT_NEG = 0x1 << CONTROL_AT_NEG_INDEX, /// <summary>Move Left (SL Keybinding: Shift-(A/Left Arrow))</summary> AGENT_CONTROL_LEFT_POS = 0x1 << CONTROL_LEFT_POS_INDEX, /// <summary>Move Right (SL Keybinding: Shift-(D/Right Arrow))</summary> AGENT_CONTROL_LEFT_NEG = 0x1 << CONTROL_LEFT_NEG_INDEX, /// <summary>Not Flying: Jump/Flying: Move Up (SL Keybinding: E)</summary> AGENT_CONTROL_UP_POS = 0x1 << CONTROL_UP_POS_INDEX, /// <summary>Not Flying: Croutch/Flying: Move Down (SL Keybinding: C)</summary> AGENT_CONTROL_UP_NEG = 0x1 << CONTROL_UP_NEG_INDEX, /// <summary>Unused</summary> AGENT_CONTROL_PITCH_POS = 0x1 << CONTROL_PITCH_POS_INDEX, /// <summary>Unused</summary> AGENT_CONTROL_PITCH_NEG = 0x1 << CONTROL_PITCH_NEG_INDEX, /// <summary>Unused</summary> AGENT_CONTROL_YAW_POS = 0x1 << CONTROL_YAW_POS_INDEX, /// <summary>Unused</summary> AGENT_CONTROL_YAW_NEG = 0x1 << CONTROL_YAW_NEG_INDEX, /// <summary>ORed with AGENT_CONTROL_AT_* if the keyboard is being used</summary> AGENT_CONTROL_FAST_AT = 0x1 << CONTROL_FAST_AT_INDEX, /// <summary>ORed with AGENT_CONTROL_LEFT_* if the keyboard is being used</summary> AGENT_CONTROL_FAST_LEFT = 0x1 << CONTROL_FAST_LEFT_INDEX, /// <summary>ORed with AGENT_CONTROL_UP_* if the keyboard is being used</summary> AGENT_CONTROL_FAST_UP = 0x1 << CONTROL_FAST_UP_INDEX, /// <summary>Fly</summary> AGENT_CONTROL_FLY = 0x1 << CONTROL_FLY_INDEX, /// <summary></summary> AGENT_CONTROL_STOP = 0x1 << CONTROL_STOP_INDEX, /// <summary>Finish our current animation</summary> AGENT_CONTROL_FINISH_ANIM = 0x1 << CONTROL_FINISH_ANIM_INDEX, /// <summary>Stand up from the ground or a prim seat</summary> AGENT_CONTROL_STAND_UP = 0x1 << CONTROL_STAND_UP_INDEX, /// <summary>Sit on the ground at our current location</summary> AGENT_CONTROL_SIT_ON_GROUND = 0x1 << CONTROL_SIT_ON_GROUND_INDEX, /// <summary>Whether mouselook is currently enabled</summary> AGENT_CONTROL_MOUSELOOK = 0x1 << CONTROL_MOUSELOOK_INDEX, /// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary> AGENT_CONTROL_NUDGE_AT_POS = 0x1 << CONTROL_NUDGE_AT_POS_INDEX, /// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary> AGENT_CONTROL_NUDGE_AT_NEG = 0x1 << CONTROL_NUDGE_AT_NEG_INDEX, /// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary> AGENT_CONTROL_NUDGE_LEFT_POS = 0x1 << CONTROL_NUDGE_LEFT_POS_INDEX, /// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary> AGENT_CONTROL_NUDGE_LEFT_NEG = 0x1 << CONTROL_NUDGE_LEFT_NEG_INDEX, /// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary> AGENT_CONTROL_NUDGE_UP_POS = 0x1 << CONTROL_NUDGE_UP_POS_INDEX, /// <summary>Legacy, used if a key was pressed for less than a certain amount of time</summary> AGENT_CONTROL_NUDGE_UP_NEG = 0x1 << CONTROL_NUDGE_UP_NEG_INDEX, /// <summary></summary> AGENT_CONTROL_TURN_LEFT = 0x1 << CONTROL_TURN_LEFT_INDEX, /// <summary></summary> AGENT_CONTROL_TURN_RIGHT = 0x1 << CONTROL_TURN_RIGHT_INDEX, /// <summary>Set when the avatar is idled or set to away. Note that the away animation is /// activated separately from setting this flag</summary> AGENT_CONTROL_AWAY = 0x1 << CONTROL_AWAY_INDEX, /// <summary></summary> AGENT_CONTROL_LBUTTON_DOWN = 0x1 << CONTROL_LBUTTON_DOWN_INDEX, /// <summary></summary> AGENT_CONTROL_LBUTTON_UP = 0x1 << CONTROL_LBUTTON_UP_INDEX, /// <summary></summary> AGENT_CONTROL_ML_LBUTTON_DOWN = 0x1 << CONTROL_ML_LBUTTON_DOWN_INDEX, /// <summary></summary> AGENT_CONTROL_ML_LBUTTON_UP = 0x1 << CONTROL_ML_LBUTTON_UP_INDEX } #endregion Enums #region AgentUpdate Constants private const int CONTROL_AT_POS_INDEX = 0; private const int CONTROL_AT_NEG_INDEX = 1; private const int CONTROL_LEFT_POS_INDEX = 2; private const int CONTROL_LEFT_NEG_INDEX = 3; private const int CONTROL_UP_POS_INDEX = 4; private const int CONTROL_UP_NEG_INDEX = 5; private const int CONTROL_PITCH_POS_INDEX = 6; private const int CONTROL_PITCH_NEG_INDEX = 7; private const int CONTROL_YAW_POS_INDEX = 8; private const int CONTROL_YAW_NEG_INDEX = 9; private const int CONTROL_FAST_AT_INDEX = 10; private const int CONTROL_FAST_LEFT_INDEX = 11; private const int CONTROL_FAST_UP_INDEX = 12; private const int CONTROL_FLY_INDEX = 13; private const int CONTROL_STOP_INDEX = 14; private const int CONTROL_FINISH_ANIM_INDEX = 15; private const int CONTROL_STAND_UP_INDEX = 16; private const int CONTROL_SIT_ON_GROUND_INDEX = 17; private const int CONTROL_MOUSELOOK_INDEX = 18; private const int CONTROL_NUDGE_AT_POS_INDEX = 19; private const int CONTROL_NUDGE_AT_NEG_INDEX = 20; private const int CONTROL_NUDGE_LEFT_POS_INDEX = 21; private const int CONTROL_NUDGE_LEFT_NEG_INDEX = 22; private const int CONTROL_NUDGE_UP_POS_INDEX = 23; private const int CONTROL_NUDGE_UP_NEG_INDEX = 24; private const int CONTROL_TURN_LEFT_INDEX = 25; private const int CONTROL_TURN_RIGHT_INDEX = 26; private const int CONTROL_AWAY_INDEX = 27; private const int CONTROL_LBUTTON_DOWN_INDEX = 28; private const int CONTROL_LBUTTON_UP_INDEX = 29; private const int CONTROL_ML_LBUTTON_DOWN_INDEX = 30; private const int CONTROL_ML_LBUTTON_UP_INDEX = 31; private const int TOTAL_CONTROLS = 32; #endregion AgentUpdate Constants /// <summary> /// Agent movement and camera control /// /// Agent movement is controlled by setting specific <seealso cref="T:AgentManager.ControlFlags"/> /// After the control flags are set, An AgentUpdate is required to update the simulator of the specified flags /// This is most easily accomplished by setting one or more of the AgentMovement properties /// /// Movement of an avatar is always based on a compass direction, for example AtPos will move the /// agent from West to East or forward on the X Axis, AtNeg will of course move agent from /// East to West or backward on the X Axis, LeftPos will be South to North or forward on the Y Axis /// The Z axis is Up, finer grained control of movements can be done using the Nudge properties /// </summary> public partial class AgentMovement { #region Properties /// <summary>Move agent positive along the X axis</summary> public bool AtPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_POS, value); } } /// <summary>Move agent negative along the X axis</summary> public bool AtNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG, value); } } /// <summary>Move agent positive along the Y axis</summary> public bool LeftPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS, value); } } /// <summary>Move agent negative along the Y axis</summary> public bool LeftNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG, value); } } /// <summary>Move agent positive along the Z axis</summary> public bool UpPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_POS, value); } } /// <summary>Move agent negative along the Z axis</summary> public bool UpNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG, value); } } /// <summary></summary> public bool PitchPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_POS, value); } } /// <summary></summary> public bool PitchNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_PITCH_NEG, value); } } /// <summary></summary> public bool YawPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS, value); } } /// <summary></summary> public bool YawNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG, value); } } /// <summary></summary> public bool FastAt { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_AT); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_AT, value); } } /// <summary></summary> public bool FastLeft { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_LEFT); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_LEFT, value); } } /// <summary></summary> public bool FastUp { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_UP); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FAST_UP, value); } } /// <summary>Causes simulator to make agent fly</summary> public bool Fly { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FLY); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FLY, value); } } /// <summary>Stop movement</summary> public bool Stop { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STOP); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STOP, value); } } /// <summary>Finish animation</summary> public bool FinishAnim { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FINISH_ANIM); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_FINISH_ANIM, value); } } /// <summary>Stand up from a sit</summary> public bool StandUp { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP, value); } } /// <summary>Tells simulator to sit agent on ground</summary> public bool SitOnGround { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND, value); } } /// <summary>Place agent into mouselook mode</summary> public bool Mouselook { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK, value); } } /// <summary>Nudge agent positive along the X axis</summary> public bool NudgeAtPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS, value); } } /// <summary>Nudge agent negative along the X axis</summary> public bool NudgeAtNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG, value); } } /// <summary>Nudge agent positive along the Y axis</summary> public bool NudgeLeftPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS, value); } } /// <summary>Nudge agent negative along the Y axis</summary> public bool NudgeLeftNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG, value); } } /// <summary>Nudge agent positive along the Z axis</summary> public bool NudgeUpPos { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS, value); } } /// <summary>Nudge agent negative along the Z axis</summary> public bool NudgeUpNeg { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG, value); } } /// <summary></summary> public bool TurnLeft { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT, value); } } /// <summary></summary> public bool TurnRight { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT, value); } } /// <summary>Tell simulator to mark agent as away</summary> public bool Away { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AWAY); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_AWAY, value); } } /// <summary></summary> public bool LButtonDown { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN, value); } } /// <summary></summary> public bool LButtonUp { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP, value); } } /// <summary></summary> public bool MLButtonDown { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN, value); } } /// <summary></summary> public bool MLButtonUp { get { return GetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP); } set { SetControlFlag(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP, value); } } /// <summary> /// Returns "always run" value, or changes it by sending a SetAlwaysRunPacket /// </summary> public bool AlwaysRun { get { return alwaysRun; } set { alwaysRun = value; SetAlwaysRunPacket run = new SetAlwaysRunPacket(); run.AgentData.AgentID = Client.Self.AgentID; run.AgentData.SessionID = Client.Self.SessionID; run.AgentData.AlwaysRun = alwaysRun; Client.Network.SendPacket(run); } } /// <summary>The current value of the agent control flags</summary> public uint AgentControls { get { return agentControls; } } /// <summary>Gets or sets the interval in milliseconds at which /// AgentUpdate packets are sent to the current simulator. Setting /// this to a non-zero value will also enable the packet sending if /// it was previously off, and setting it to zero will disable</summary> public int UpdateInterval { get { return updateInterval; } set { if (value > 0) { updateTimer.Change(value, value); updateInterval = value; } else { updateTimer.Change(Timeout.Infinite, Timeout.Infinite); updateInterval = 0; } } } /// <summary>Gets or sets whether AgentUpdate packets are sent to /// the current simulator</summary> public bool UpdateEnabled { get { return (updateInterval != 0); } } /// <summary>Reset movement controls every time we send an update</summary> public bool AutoResetControls { get { return autoResetControls; } set { autoResetControls = value; } } #endregion Properties /// <summary>Agent camera controls</summary> public AgentCamera Camera; /// <summary>Currently only used for hiding your group title</summary> public AgentFlags Flags = AgentFlags.None; /// <summary>Action state of the avatar, which can currently be /// typing and editing</summary> public AgentState State = AgentState.None; /// <summary></summary> public LLQuaternion BodyRotation = LLQuaternion.Identity; /// <summary></summary> public LLQuaternion HeadRotation = LLQuaternion.Identity; #region Change tracking /// <summary></summary> private LLQuaternion LastBodyRotation; /// <summary></summary> private LLQuaternion LastHeadRotation; /// <summary></summary> private LLVector3 LastCameraCenter; /// <summary></summary> private LLVector3 LastCameraXAxis; /// <summary></summary> private LLVector3 LastCameraYAxis; /// <summary></summary> private LLVector3 LastCameraZAxis; /// <summary></summary> private float LastFar; #endregion Change tracking private bool alwaysRun; private SecondLife Client; private uint agentControls; private int duplicateCount; private AgentState lastState; /// <summary>Timer for sending AgentUpdate packets</summary> private Timer updateTimer; private int updateInterval; private bool autoResetControls = true; /// <summary>Default constructor</summary> public AgentMovement(SecondLife client) { Client = client; Camera = new AgentCamera(); updateInterval = Settings.DEFAULT_AGENT_UPDATE_INTERVAL; updateTimer = new Timer(new TimerCallback(UpdateTimer_Elapsed), null, Settings.DEFAULT_AGENT_UPDATE_INTERVAL, Settings.DEFAULT_AGENT_UPDATE_INTERVAL); } /// <summary> /// Send an AgentUpdate with the camera set at the current agent /// position and pointing towards the heading specified /// </summary> /// <param name="heading">Camera rotation in radians</param> /// <param name="reliable">Whether to send the AgentUpdate reliable /// or not</param> public void UpdateFromHeading(double heading, bool reliable) { Camera.Position = Client.Self.SimPosition; Camera.LookDirection(heading); BodyRotation.Z = (float)Math.Sin(heading / 2.0d); BodyRotation.W = (float)Math.Cos(heading / 2.0d); HeadRotation = BodyRotation; SendUpdate(reliable); } /// <summary> /// Rotates the avatar body and camera toward a target position. /// This will also anchor the camera position on the avatar /// </summary> /// <param name="target">Region coordinates to turn toward</param> public bool TurnToward(LLVector3 target) { if (Client.Settings.SEND_AGENT_UPDATES) { LLVector3 myPos = Client.Self.SimPosition; LLVector3 forward = new LLVector3(1, 0, 0); LLVector3 offset = LLVector3.Norm(target - myPos); LLQuaternion newRot = LLVector3.RotBetween(forward, offset); BodyRotation = newRot; HeadRotation = newRot; Camera.LookAt(myPos, target); SendUpdate(); return true; } else { Logger.Log("Attempted TurnToward but agent updates are disabled", Helpers.LogLevel.Warning, Client); return false; } } /// <summary> /// Send new AgentUpdate packet to update our current camera /// position and rotation /// </summary> public void SendUpdate() { SendUpdate(false, Client.Network.CurrentSim); } /// <summary> /// Send new AgentUpdate packet to update our current camera /// position and rotation /// </summary> /// <param name="reliable">Whether to require server acknowledgement /// of this packet</param> public void SendUpdate(bool reliable) { SendUpdate(reliable, Client.Network.CurrentSim); } /// <summary> /// Send new AgentUpdate packet to update our current camera /// position and rotation /// </summary> /// <param name="reliable">Whether to require server acknowledgement /// of this packet</param> /// <param name="simulator">Simulator to send the update to</param> public void SendUpdate(bool reliable, Simulator simulator) { LLVector3 origin = Camera.Position; LLVector3 xAxis = Camera.LeftAxis; LLVector3 yAxis = Camera.AtAxis; LLVector3 zAxis = Camera.UpAxis; // Attempted to sort these in a rough order of how often they might change if (agentControls == 0 && yAxis == LastCameraYAxis && origin == LastCameraCenter && State == lastState && HeadRotation == LastHeadRotation && BodyRotation == LastBodyRotation && xAxis == LastCameraXAxis && Camera.Far == LastFar && zAxis == LastCameraZAxis) { ++duplicateCount; } else { duplicateCount = 0; } if (Client.Settings.DISABLE_AGENT_UPDATE_DUPLICATE_CHECK || duplicateCount < 10) { // Store the current state to do duplicate checking LastHeadRotation = HeadRotation; LastBodyRotation = BodyRotation; LastCameraYAxis = yAxis; LastCameraCenter = origin; LastCameraXAxis = xAxis; LastCameraZAxis = zAxis; LastFar = Camera.Far; lastState = State; // Build the AgentUpdate packet and send it AgentUpdatePacket update = new AgentUpdatePacket(); update.Header.Reliable = reliable; update.AgentData.AgentID = Client.Self.AgentID; update.AgentData.SessionID = Client.Self.SessionID; update.AgentData.HeadRotation = HeadRotation; update.AgentData.BodyRotation = BodyRotation; update.AgentData.CameraAtAxis = yAxis; update.AgentData.CameraCenter = origin; update.AgentData.CameraLeftAxis = xAxis; update.AgentData.CameraUpAxis = zAxis; update.AgentData.Far = Camera.Far; update.AgentData.State = (byte)State; update.AgentData.ControlFlags = agentControls; update.AgentData.Flags = (byte)Flags; Client.Network.SendPacket(update, simulator); if (autoResetControls) { ResetControlFlags(); } } } /// <summary> /// Builds an AgentUpdate packet entirely from parameters. This /// will not touch the state of Self.Movement or /// Self.Movement.Camera in any way /// </summary> /// <param name="controlFlags"></param> /// <param name="position"></param> /// <param name="forwardAxis"></param> /// <param name="leftAxis"></param> /// <param name="upAxis"></param> /// <param name="bodyRotation"></param> /// <param name="headRotation"></param> /// <param name="farClip"></param> /// <param name="reliable"></param> /// <param name="flags"></param> /// <param name="state"></param> public void SendManualUpdate(AgentManager.ControlFlags controlFlags, LLVector3 position, LLVector3 forwardAxis, LLVector3 leftAxis, LLVector3 upAxis, LLQuaternion bodyRotation, LLQuaternion headRotation, float farClip, AgentFlags flags, AgentState state, bool reliable) { AgentUpdatePacket update = new AgentUpdatePacket(); update.AgentData.AgentID = Client.Self.AgentID; update.AgentData.SessionID = Client.Self.SessionID; update.AgentData.BodyRotation = bodyRotation; update.AgentData.HeadRotation = headRotation; update.AgentData.CameraCenter = position; update.AgentData.CameraAtAxis = forwardAxis; update.AgentData.CameraLeftAxis = leftAxis; update.AgentData.CameraUpAxis = upAxis; update.AgentData.Far = farClip; update.AgentData.ControlFlags = (uint)controlFlags; update.AgentData.Flags = (byte)flags; update.AgentData.State = (byte)state; update.Header.Reliable = reliable; Client.Network.SendPacket(update); } private bool GetControlFlag(ControlFlags flag) { return (agentControls & (uint)flag) != 0; } private void SetControlFlag(ControlFlags flag, bool value) { if (value) agentControls |= (uint)flag; else agentControls &= ~((uint)flag); } private void ResetControlFlags() { // Reset all of the flags except for persistent settings like // away, fly, mouselook, and crouching agentControls &= (uint)(ControlFlags.AGENT_CONTROL_AWAY | ControlFlags.AGENT_CONTROL_FLY | ControlFlags.AGENT_CONTROL_MOUSELOOK | ControlFlags.AGENT_CONTROL_UP_NEG); } private void UpdateTimer_Elapsed(object obj) { if (Client.Network.Connected && Client.Settings.SEND_AGENT_UPDATES) { //Send an AgentUpdate packet SendUpdate(false, Client.Network.CurrentSim); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // // Purpose: This class implements a set of methods for comparing // strings. // // //////////////////////////////////////////////////////////////////////////// using System.Reflection; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { [Flags] public enum CompareOptions { None = 0x00000000, IgnoreCase = 0x00000001, IgnoreNonSpace = 0x00000002, IgnoreSymbols = 0x00000004, IgnoreKanaType = 0x00000008, // ignore kanatype IgnoreWidth = 0x00000010, // ignore width OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags. StringSort = 0x20000000, // use string sort method Ordinal = 0x40000000, // This flag can not be used with other flags. } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial class CompareInfo : IDeserializationCallback { // Mask used to check if IndexOf()/LastIndexOf()/IsPrefix()/IsPostfix() has the right flags. private const CompareOptions ValidIndexMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if Compare() has the right flags. private const CompareOptions ValidCompareMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // Mask used to check if GetHashCodeOfString() has the right flags. private const CompareOptions ValidHashCodeOfStringMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType); // Mask used to check if we have the right flags. private const CompareOptions ValidSortkeyCtorMaskOffFlags = ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort); // // CompareInfos have an interesting identity. They are attached to the locale that created them, // ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US. // The interesting part is that since haw-US doesn't have its own sort, it has to point at another // locale, which is what SCOMPAREINFO does. [OptionalField(VersionAdded = 2)] private string m_name; // The name used to construct this CompareInfo. Do not rename (binary serialization) [NonSerialized] private string _sortName; // The name that defines our behavior. [OptionalField(VersionAdded = 3)] private SortVersion m_sortVersion; // Do not rename (binary serialization) // _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant [NonSerialized] private readonly bool _invariantMode = GlobalizationMode.Invariant; internal CompareInfo(CultureInfo culture) { m_name = culture._name; InitSort(culture); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. ** Warning: The assembly versioning mechanism is dead! **Returns: The CompareInfo for the specified culture. **Arguments: ** culture the ID of the culture ** assembly the assembly which contains the sorting table. **Exceptions: ** ArugmentNullException when the assembly is null ** ArgumentException if culture is invalid. ============================================================================*/ // Assembly constructor should be deprecated, we don't act on the assembly information any more public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { // Parameter checking. if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (assembly != typeof(Object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } Contract.EndContractBlock(); return GetCompareInfo(culture); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture. ** The purpose of this method is to provide version for CompareInfo tables. **Returns: The CompareInfo for the specified culture. **Arguments: ** name the name of the culture ** assembly the assembly which contains the sorting table. **Exceptions: ** ArugmentNullException when the assembly is null ** ArgumentException if name is invalid. ============================================================================*/ // Assembly constructor should be deprecated, we don't act on the assembly information any more public static CompareInfo GetCompareInfo(string name, Assembly assembly) { if (name == null || assembly == null) { throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly)); } Contract.EndContractBlock(); if (assembly != typeof(Object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } return GetCompareInfo(name); } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo for the specified culture. ** This method is provided for ease of integration with NLS-based software. **Returns: The CompareInfo for the specified culture. **Arguments: ** culture the ID of the culture. **Exceptions: ** ArgumentException if culture is invalid. ============================================================================*/ // People really shouldn't be calling LCID versions, no custom support public static CompareInfo GetCompareInfo(int culture) { if (CultureData.IsCustomCultureId(culture)) { // Customized culture cannot be created by the LCID. throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture)); } return CultureInfo.GetCultureInfo(culture).CompareInfo; } /*=================================GetCompareInfo========================== **Action: Get the CompareInfo for the specified culture. **Returns: The CompareInfo for the specified culture. **Arguments: ** name the name of the culture. **Exceptions: ** ArgumentException if name is invalid. ============================================================================*/ public static CompareInfo GetCompareInfo(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); return CultureInfo.GetCultureInfo(name).CompareInfo; } public static unsafe bool IsSortable(char ch) { if (GlobalizationMode.Invariant) { return true; } char *pChar = &ch; return IsSortable(pChar, 1); } public static unsafe bool IsSortable(string text) { if (text == null) { // A null param is invalid here. throw new ArgumentNullException(nameof(text)); } if (text.Length == 0) { // A zero length string is not invalid, but it is also not sortable. return (false); } if (GlobalizationMode.Invariant) { return true; } fixed (char *pChar = text) { return IsSortable(pChar, text.Length); } } [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_name = null; } void IDeserializationCallback.OnDeserialization(Object sender) { OnDeserialized(); } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { OnDeserialized(); } private void OnDeserialized() { if (m_name != null) { InitSort(CultureInfo.GetCultureInfo(m_name)); } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { } ///////////////////////////----- Name -----///////////////////////////////// // // Returns the name of the culture (well actually, of the sort). // Very important for providing a non-LCID way of identifying // what the sort is. // // Note that this name isn't dereferenced in case the CompareInfo is a different locale // which is consistent with the behaviors of earlier versions. (so if you ask for a sort // and the locale's changed behavior, then you'll get changed behavior, which is like // what happens for a version update) // //////////////////////////////////////////////////////////////////////// public virtual string Name { get { Debug.Assert(m_name != null, "CompareInfo.Name Expected _name to be set"); if (m_name == "zh-CHT" || m_name == "zh-CHS") { return m_name; } return _sortName; } } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the two strings with the given options. Returns 0 if the // two strings are equal, a number less than 0 if string1 is less // than string2, and a number greater than 0 if string1 is greater // than string2. // //////////////////////////////////////////////////////////////////////// public virtual int Compare(string string1, string string2) { return (Compare(string1, string2, CompareOptions.None)); } public unsafe virtual int Compare(string string1, string string2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase); } // Verify the options before we do any real comparison. if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } return String.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } //Our paradigm is that null sorts less than any other string and //that two nulls sort as equal. if (string1 == null) { if (string2 == null) { return (0); // Equal } return (-1); // null < non-null } if (string2 == null) { return (1); // non-null > null } if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length); return String.CompareOrdinal(string1, string2); } return CompareString(string1, 0, string1.Length, string2, 0, string2.Length, options); } //////////////////////////////////////////////////////////////////////// // // Compare // // Compares the specified regions of the two strings with the given // options. // Returns 0 if the two strings are equal, a number less than 0 if // string1 is less than string2, and a number greater than 0 if // string1 is greater than string2. // //////////////////////////////////////////////////////////////////////// public unsafe virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2) { return Compare(string1, offset1, length1, string2, offset2, length2, 0); } public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options) { return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1, string2, offset2, string2 == null ? 0 : string2.Length - offset2, options); } public virtual int Compare(string string1, int offset1, string string2, int offset2) { return Compare(string1, offset1, string2, offset2, 0); } public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) { int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase); if ((length1 != length2) && result == 0) return (length1 > length2 ? 1 : -1); return (result); } // Verify inputs if (length1 < 0 || length2 < 0) { throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 < 0 || offset2 < 0) { throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 > (string1 == null ? 0 : string1.Length) - length1) { throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength); } if (offset2 > (string2 == null ? 0 : string2.Length) - length2) { throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength); } if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options)); } } else if ((options & ValidCompareMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } // // Check for the null case. // if (string1 == null) { if (string2 == null) { return (0); } return (-1); } if (string2 == null) { return (1); } if (options == CompareOptions.Ordinal) { return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); } if (_invariantMode) { if ((options & CompareOptions.IgnoreCase) != 0) return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2); return CompareOrdinal(string1, offset1, length1, string2, offset2, length2); } return CompareString(string1, offset1, length1, string2, offset2, length2, options); } private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2) { int result = String.CompareOrdinal(string1, offset1, string2, offset2, (length1 < length2 ? length1 : length2)); if ((length1 != length2) && result == 0) { return (length1 > length2 ? 1 : -1); } return (result); } // // CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case. // it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by // calling the OS. // internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB) { Debug.Assert(indexA + lengthA <= strA.Length); Debug.Assert(indexB + lengthB <= strB.Length); int length = Math.Min(lengthA, lengthB); int range = length; fixed (char* ap = strA) fixed (char* bp = strB) { char* a = ap + indexA; char* b = bp + indexB; // in InvariantMode we support all range and not only the ascii characters. char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x80); while (length != 0 && (*a <= maxChar) && (*b <= maxChar)) { int charA = *a; int charB = *b; if (charA == charB) { a++; b++; length--; continue; } // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; // Return the (case-insensitive) difference between them. if (charA != charB) return charA - charB; // Next char a++; b++; length--; } if (length == 0) return lengthA - lengthB; Debug.Assert(!GlobalizationMode.Invariant); range -= length; return CompareStringOrdinalIgnoreCase(a, lengthA - range, b, lengthB - range); } } //////////////////////////////////////////////////////////////////////// // // IsPrefix // // Determines whether prefix is a prefix of string. If prefix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsPrefix(string source, string prefix, CompareOptions options) { if (source == null || prefix == null) { throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)), SR.ArgumentNull_String); } Contract.EndContractBlock(); if (prefix.Length == 0) { return (true); } if (source.Length == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.StartsWith(prefix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return StartsWith(source, prefix, options); } public virtual bool IsPrefix(string source, string prefix) { return (IsPrefix(source, prefix, 0)); } //////////////////////////////////////////////////////////////////////// // // IsSuffix // // Determines whether suffix is a suffix of string. If suffix equals // String.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsSuffix(string source, string suffix, CompareOptions options) { if (source == null || suffix == null) { throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)), SR.ArgumentNull_String); } Contract.EndContractBlock(); if (suffix.Length == 0) { return (true); } if (source.Length == 0) { return false; } if (options == CompareOptions.OrdinalIgnoreCase) { return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase); } if (options == CompareOptions.Ordinal) { return source.EndsWith(suffix, StringComparison.Ordinal); } if ((options & ValidIndexMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } if (_invariantMode) { return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return EndsWith(source, suffix, options); } public virtual bool IsSuffix(string source, string suffix) { return (IsSuffix(source, suffix, 0)); } //////////////////////////////////////////////////////////////////////// // // IndexOf // // Returns the first index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // startIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public virtual int IndexOf(string source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public virtual int IndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); } public virtual int IndexOf(string source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); } public virtual int IndexOf(string source, string value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); } public virtual int IndexOf(string source, char value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } public virtual int IndexOf(string source, string value, int startIndex) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); } public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public virtual int IndexOf(string source, char value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int IndexOf(string source, string value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException(nameof(source)); if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); Contract.EndContractBlock(); if (options == CompareOptions.OrdinalIgnoreCase) { return source.IndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); if (_invariantMode) return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return IndexOfCore(source, new string(value, 1), startIndex, count, options, null); } public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) throw new ArgumentNullException(nameof(source)); if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex > source.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); // In Everett we used to return -1 for empty string even if startIndex is negative number so we keeping same behavior here. // We return 0 if both source and value are empty strings for Everett compatibility too. if (source.Length == 0) { if (value.Length == 0) { return 0; } return -1; } if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > source.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); if (_invariantMode) return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return IndexOfCore(source, value, startIndex, count, options, null); } // The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated // and the caller is passing a valid matchLengthPtr pointer. internal unsafe int IndexOf(string source, string value, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(source != null); Debug.Assert(value != null); Debug.Assert(startIndex >= 0); Debug.Assert(matchLengthPtr != null); *matchLengthPtr = 0; if (source.Length == 0) { if (value.Length == 0) { return 0; } return -1; } if (startIndex >= source.Length) { return -1; } if (options == CompareOptions.OrdinalIgnoreCase) { int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); if (res >= 0) { *matchLengthPtr = value.Length; } return res; } if (_invariantMode) { int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); if (res >= 0) { *matchLengthPtr = value.Length; } return res; } return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr); } internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { if (_invariantMode) { return InvariantIndexOf(source, value, startIndex, count, ignoreCase); } return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase); } //////////////////////////////////////////////////////////////////////// // // LastIndexOf // // Returns the last index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if // the specified value is not found. If value equals String.Empty, // endIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. // //////////////////////////////////////////////////////////////////////// public virtual int LastIndexOf(String source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(string source, string value) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public virtual int LastIndexOf(string source, string value, CompareOptions options) { if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. return LastIndexOf(source, value, source.Length - 1, source.Length, options); } public virtual int LastIndexOf(string source, char value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public virtual int LastIndexOf(string source, string value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public virtual int LastIndexOf(string source, char value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int LastIndexOf(string source, string value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase); } if (_invariantMode) return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return LastIndexOfCore(source, value.ToString(), startIndex, count, options); } public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) throw new ArgumentNullException(nameof(source)); if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) { startIndex--; if (count > 0) count--; // If we are looking for nothing, just return 0 if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) return startIndex; } // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); if (options == CompareOptions.OrdinalIgnoreCase) { return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true); } if (_invariantMode) return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); return LastIndexOfCore(source, value, startIndex, count, options); } internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { if (_invariantMode) { return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase); } return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase); } //////////////////////////////////////////////////////////////////////// // // GetSortKey // // Gets the SortKey for the given string with the given options. // //////////////////////////////////////////////////////////////////////// public virtual SortKey GetSortKey(string source, CompareOptions options) { if (_invariantMode) return InvariantCreateSortKey(source, options); return CreateSortKey(source, options); } public virtual SortKey GetSortKey(string source) { if (_invariantMode) return InvariantCreateSortKey(source, CompareOptions.None); return CreateSortKey(source, CompareOptions.None); } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same CompareInfo as the current // instance. // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { CompareInfo that = value as CompareInfo; if (that != null) { return this.Name == that.Name; } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CompareInfo. The hash code is guaranteed to be the same for // CompareInfo A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // GetHashCodeOfString // // This internal method allows a method that allows the equivalent of creating a Sortkey for a // string from CompareInfo, and generate a hashcode value from it. It is not very convenient // to use this method as is and it creates an unnecessary Sortkey object that will be GC'ed. // // The hash code is guaranteed to be the same for string A and B where A.Equals(B) is true and both // the CompareInfo and the CompareOptions are the same. If two different CompareInfo objects // treat the string the same way, this implementation will treat them differently (the same way that // Sortkey does at the moment). // // This method will never be made public itself, but public consumers of it could be created, e.g.: // // string.GetHashCode(CultureInfo) // string.GetHashCode(CompareInfo) // string.GetHashCode(CultureInfo, CompareOptions) // string.GetHashCode(CompareInfo, CompareOptions) // etc. // // (the methods above that take a CultureInfo would use CultureInfo.CompareInfo) // //////////////////////////////////////////////////////////////////////// internal int GetHashCodeOfString(string source, CompareOptions options) { // // Parameter validation // if (null == source) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidHashCodeOfStringMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } Contract.EndContractBlock(); return GetHashCodeOfStringCore(source, options); } public virtual int GetHashCode(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (options == CompareOptions.Ordinal) { return source.GetHashCode(); } if (options == CompareOptions.OrdinalIgnoreCase) { return TextInfo.GetHashCodeOrdinalIgnoreCase(source); } // // GetHashCodeOfString does more parameters validation. basically will throw when // having Ordinal, OrdinalIgnoreCase and StringSort // return GetHashCodeOfString(source, options); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns a string describing the // CompareInfo. // //////////////////////////////////////////////////////////////////////// public override string ToString() { return ("CompareInfo - " + this.Name); } public SortVersion Version { get { if (m_sortVersion == null) { if (_invariantMode) { m_sortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0, (byte) (CultureInfo.LOCALE_INVARIANT >> 24), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16), (byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8), (byte) (CultureInfo.LOCALE_INVARIANT & 0xFF))); } else { m_sortVersion = GetSortVersion(); } } return m_sortVersion; } } public int LCID { get { return CultureInfo.GetCultureInfo(Name).LCID; } } } }
// // TextEntry.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using System.ComponentModel; namespace Xwt { [BackendType (typeof(ITextEntryBackend))] public class TextEntry: Widget { EventHandler changed, activated, selectionChanged; static TextEntry () { MapEvent (TextEntryEvent.Changed, typeof(TextEntry), "OnChanged"); MapEvent (TextEntryEvent.Activated, typeof(TextEntry), "OnActivated"); MapEvent (TextEntryEvent.SelectionChanged, typeof(TextEntry), "OnSelectionChanged"); } protected new class WidgetBackendHost: Widget.WidgetBackendHost, ITextEntryEventSink { public void OnChanged () { ((TextEntry)Parent).OnChanged (EventArgs.Empty); } public void OnActivated () { ((TextEntry)Parent).OnActivated (EventArgs.Empty); } public void OnSelectionChanged () { ((TextEntry)Parent).OnSelectionChanged (EventArgs.Empty); } public override Size GetDefaultNaturalSize () { return DefaultNaturalSizes.TextEntry; } } public TextEntry () { } protected override BackendHost CreateBackendHost () { return new WidgetBackendHost (); } ITextEntryBackend Backend { get { return (ITextEntryBackend) BackendHost.Backend; } } [DefaultValue ("")] public string Text { get { return Backend.Text; } set { Backend.Text = value; } } public Alignment TextAlignment { get { return Backend.TextAlignment; } set { Backend.TextAlignment = value; } } [DefaultValue ("")] public string PlaceholderText { get { return Backend.PlaceholderText; } set { Backend.PlaceholderText = value; } } [DefaultValue (false)] public bool ReadOnly { get { return Backend.ReadOnly; } set { Backend.ReadOnly = value; } } [DefaultValue (true)] public bool ShowFrame { get { return Backend.ShowFrame; } set { Backend.ShowFrame = value; } } [DefaultValue (0)] public int CursorPosition { get { return Backend.CursorPosition; } set { Backend.CursorPosition = value; } } [DefaultValue (0)] public int SelectionStart { get { return Backend.SelectionStart; } set { Backend.SelectionStart = value; } } [DefaultValue (0)] public int SelectionLength { get { return Backend.SelectionLength; } set { Backend.SelectionLength = value; } } [DefaultValue ("")] public string SelectedText { get { return Backend.SelectedText; } set { Backend.SelectedText = value; } } [DefaultValue (true)] public bool MultiLine { get { return Backend.MultiLine; } set { Backend.MultiLine = value; } } public void SetCompletions (string[] completions) { Backend.SetCompletions (completions); } public void SetCompletionMatchFunction (Func<string, string, bool> matchFunc) { Backend.SetCompletionMatchFunc (matchFunc); } protected virtual void OnChanged (EventArgs e) { if (changed != null) changed (this, e); } public event EventHandler Changed { add { BackendHost.OnBeforeEventAdd (TextEntryEvent.Changed, changed); changed += value; } remove { changed -= value; BackendHost.OnAfterEventRemove (TextEntryEvent.Changed, changed); } } protected virtual void OnSelectionChanged (EventArgs e) { if (selectionChanged != null) selectionChanged (this, e); } public event EventHandler SelectionChanged { add { BackendHost.OnBeforeEventAdd (TextEntryEvent.SelectionChanged, selectionChanged); selectionChanged += value; } remove { selectionChanged -= value; BackendHost.OnAfterEventRemove (TextEntryEvent.SelectionChanged, selectionChanged); } } protected virtual void OnActivated (EventArgs e) { if (activated != null) activated (this, e); } public event EventHandler Activated { add { BackendHost.OnBeforeEventAdd (TextEntryEvent.Activated, activated); activated += value; } remove { activated -= value; BackendHost.OnAfterEventRemove (TextEntryEvent.Activated, activated); } } } }
// 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 Avalonia.Utilities; using Moq; using System; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using Xunit; namespace Avalonia.Base.UnitTests { public class PriorityValueTests { private static readonly AvaloniaProperty TestProperty = new StyledProperty<string>( "Test", typeof(PriorityValueTests), new StyledPropertyMetadata<string>()); [Fact] public void Initial_Value_Should_Be_UnsetValue() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); Assert.Same(AvaloniaProperty.UnsetValue, target.Value); } [Fact] public void First_Binding_Sets_Value() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); target.Add(Single("foo"), 0); Assert.Equal("foo", target.Value); } [Fact] public void Changing_Binding_Should_Set_Value() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var subject = new BehaviorSubject<string>("foo"); target.Add(subject, 0); Assert.Equal("foo", target.Value); subject.OnNext("bar"); Assert.Equal("bar", target.Value); } [Fact] public void Setting_Direct_Value_Should_Override_Binding() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); target.Add(Single("foo"), 0); target.SetValue("bar", 0); Assert.Equal("bar", target.Value); } [Fact] public void Binding_Firing_Should_Override_Direct_Value() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("initial"); target.Add(source, 0); Assert.Equal("initial", target.Value); target.SetValue("first", 0); Assert.Equal("first", target.Value); source.OnNext("second"); Assert.Equal("second", target.Value); } [Fact] public void Earlier_Binding_Firing_Should_Not_Override_Later() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var nonActive = new BehaviorSubject<object>("na"); var source = new BehaviorSubject<object>("initial"); target.Add(nonActive, 1); target.Add(source, 1); Assert.Equal("initial", target.Value); target.SetValue("first", 1); Assert.Equal("first", target.Value); nonActive.OnNext("second"); Assert.Equal("first", target.Value); } [Fact] public void Binding_Completing_Should_Revert_To_Direct_Value() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("initial"); target.Add(source, 0); Assert.Equal("initial", target.Value); target.SetValue("first", 0); Assert.Equal("first", target.Value); source.OnNext("second"); Assert.Equal("second", target.Value); source.OnCompleted(); Assert.Equal("first", target.Value); } [Fact] public void Binding_With_Lower_Priority_Has_Precedence() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); target.Add(Single("foo"), 1); target.Add(Single("bar"), 0); target.Add(Single("baz"), 1); Assert.Equal("bar", target.Value); } [Fact] public void Later_Binding_With_Same_Priority_Should_Take_Precedence() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); target.Add(Single("foo"), 1); target.Add(Single("bar"), 0); target.Add(Single("baz"), 0); target.Add(Single("qux"), 1); Assert.Equal("baz", target.Value); } [Fact] public void Changing_Binding_With_Lower_Priority_Should_Set_Not_Value() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var subject = new BehaviorSubject<string>("bar"); target.Add(Single("foo"), 0); target.Add(subject, 1); Assert.Equal("foo", target.Value); subject.OnNext("baz"); Assert.Equal("foo", target.Value); } [Fact] public void UnsetValue_Should_Fall_Back_To_Next_Binding() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var subject = new BehaviorSubject<object>("bar"); target.Add(subject, 0); target.Add(Single("foo"), 1); Assert.Equal("bar", target.Value); subject.OnNext(AvaloniaProperty.UnsetValue); Assert.Equal("foo", target.Value); } [Fact] public void Adding_Value_Should_Call_OnNext() { var owner = GetMockOwner(); var target = new PriorityValue(owner.Object, TestProperty, typeof(string)); target.Add(Single("foo"), 0); owner.Verify(x => x.Changed(target.Property, target.ValuePriority, AvaloniaProperty.UnsetValue, "foo")); } [Fact] public void Changing_Value_Should_Call_OnNext() { var owner = GetMockOwner(); var target = new PriorityValue(owner.Object, TestProperty, typeof(string)); var subject = new BehaviorSubject<object>("foo"); target.Add(subject, 0); subject.OnNext("bar"); owner.Verify(x => x.Changed(target.Property, target.ValuePriority, "foo", "bar")); } [Fact] public void Disposing_A_Binding_Should_Revert_To_Next_Value() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); target.Add(Single("foo"), 0); var disposable = target.Add(Single("bar"), 0); Assert.Equal("bar", target.Value); disposable.Dispose(); Assert.Equal("foo", target.Value); } [Fact] public void Disposing_A_Binding_Should_Remove_BindingEntry() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); target.Add(Single("foo"), 0); var disposable = target.Add(Single("bar"), 0); Assert.Equal(2, target.GetBindings().Count()); disposable.Dispose(); Assert.Single(target.GetBindings()); } [Fact] public void Completing_A_Binding_Should_Revert_To_Previous_Binding() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("bar"); target.Add(Single("foo"), 0); target.Add(source, 0); Assert.Equal("bar", target.Value); source.OnCompleted(); Assert.Equal("foo", target.Value); } [Fact] public void Completing_A_Binding_Should_Revert_To_Lower_Priority() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var source = new BehaviorSubject<object>("bar"); target.Add(Single("foo"), 1); target.Add(source, 0); Assert.Equal("bar", target.Value); source.OnCompleted(); Assert.Equal("foo", target.Value); } [Fact] public void Completing_A_Binding_Should_Remove_BindingEntry() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(string)); var subject = new BehaviorSubject<object>("bar"); target.Add(Single("foo"), 0); target.Add(subject, 0); Assert.Equal(2, target.GetBindings().Count()); subject.OnCompleted(); Assert.Single(target.GetBindings()); } [Fact] public void Direct_Value_Should_Be_Coerced() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(int), x => Math.Min((int)x, 10)); target.SetValue(5, 0); Assert.Equal(5, target.Value); target.SetValue(15, 0); Assert.Equal(10, target.Value); } [Fact] public void Bound_Value_Should_Be_Coerced() { var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(int), x => Math.Min((int)x, 10)); var source = new Subject<object>(); target.Add(source, 0); source.OnNext(5); Assert.Equal(5, target.Value); source.OnNext(15); Assert.Equal(10, target.Value); } [Fact] public void Revalidate_Should_ReCoerce_Value() { var max = 10; var target = new PriorityValue(GetMockOwner().Object, TestProperty, typeof(int), x => Math.Min((int)x, max)); var source = new Subject<object>(); target.Add(source, 0); source.OnNext(5); Assert.Equal(5, target.Value); source.OnNext(15); Assert.Equal(10, target.Value); max = 12; target.Revalidate(); Assert.Equal(12, target.Value); } /// <summary> /// Returns an observable that returns a single value but does not complete. /// </summary> /// <typeparam name="T">The type of the observable.</typeparam> /// <param name="value">The value.</param> /// <returns>The observable.</returns> private IObservable<T> Single<T>(T value) { return Observable.Never<T>().StartWith(value); } private static Mock<IPriorityValueOwner> GetMockOwner() { var owner = new Mock<IPriorityValueOwner>(); owner.SetupGet(o => o.Setter).Returns(new DeferredSetter<object>()); return owner; } } }
/* Copyright 2012-2022 Marco De Salvo 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 Microsoft.VisualStudio.TestTools.UnitTesting; using RDFSharp.Model; using System; using System.Linq; namespace RDFSharp.Test.Model { [TestClass] public class RDFMinInclusiveConstraintTest { #region Tests [TestMethod] public void ShouldCreateMinInclusiveResourceConstraint() { RDFMinInclusiveConstraint minInclusiveConstraint = new RDFMinInclusiveConstraint(new RDFResource("ex:value")); Assert.IsNotNull(minInclusiveConstraint); Assert.IsTrue(minInclusiveConstraint.Value.Equals(new RDFResource("ex:value"))); } [TestMethod] public void ShouldThrowExceptionOnCreatingMinInclusiveResourceConstraint() => Assert.ThrowsException<RDFModelException>(() => new RDFMinInclusiveConstraint(null as RDFResource)); [TestMethod] public void ShouldExportMinInclusiveResourceConstraint() { RDFMinInclusiveConstraint minInclusiveConstraint = new RDFMinInclusiveConstraint(new RDFResource("ex:value")); RDFGraph graph = minInclusiveConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape"))); Assert.IsNotNull(graph); Assert.IsTrue(graph.TriplesCount == 1); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE) && t.Value.Object.Equals(new RDFResource("ex:value")))); } [TestMethod] public void ShouldCreateMinInclusiveLiteralConstraint() { RDFMinInclusiveConstraint minInclusiveConstraint = new RDFMinInclusiveConstraint(new RDFPlainLiteral("value")); Assert.IsNotNull(minInclusiveConstraint); Assert.IsTrue(minInclusiveConstraint.Value.Equals(new RDFPlainLiteral("value"))); } [TestMethod] public void ShouldThrowExceptionOnCreatingMinInclusiveLiteralConstraint() => Assert.ThrowsException<RDFModelException>(() => new RDFMinInclusiveConstraint(null as RDFLiteral)); [TestMethod] public void ShouldExportMinInclusiveLiteralConstraint() { RDFMinInclusiveConstraint minInclusiveConstraint = new RDFMinInclusiveConstraint(new RDFPlainLiteral("value")); RDFGraph graph = minInclusiveConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape"))); Assert.IsNotNull(graph); Assert.IsTrue(graph.TriplesCount == 1); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE) && t.Value.Object.Equals(new RDFPlainLiteral("value")))); } //NS-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //PS-CONFORMS:TRUE [TestMethod] public void ShouldConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Alice"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //NS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } //PS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFResource("ex:Barry"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <ex:Barry>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } //MIXED-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), new RDFResource("ex:birthDate"), new RDFTypedLiteral("1999-12-24", RDFModelEnums.RDFDatatypes.XSD_DATE))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:birthDate"), new RDFTypedLiteral("1998-07-30", RDFModelEnums.RDFDatatypes.XSD_DATE))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:BeforeMillennialsShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:birthDate")); propShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFTypedLiteral("1998-07-30", RDFModelEnums.RDFDatatypes.XSD_DATE))); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //MIXED-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), new RDFResource("ex:birthDate"), new RDFTypedLiteral("1999-12-31", RDFModelEnums.RDFDatatypes.XSD_DATE))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), new RDFResource("ex:birthDate"), new RDFTypedLiteral("1998-07-30", RDFModelEnums.RDFDatatypes.XSD_DATE))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:BeforeMillennialsShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Bob"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:birthDate")); propShape.AddConstraint(new RDFMinInclusiveConstraint(new RDFTypedLiteral("1999-01-01", RDFModelEnums.RDFDatatypes.XSD_DATE))); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Must have values greater or equal than <1999-01-01Z^^http://www.w3.org/2001/XMLSchema#date>"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFTypedLiteral("1998-07-30", RDFModelEnums.RDFDatatypes.XSD_DATE))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:birthDate"))); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.MIN_INCLUSIVE_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape"))); } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedPublicDelegatedPrefixesClientSnippets { /// <summary>Snippet for AggregatedList</summary> public void AggregatedListRequestObject() { // Snippet: AggregatedList(AggregatedListPublicDelegatedPrefixesRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) AggregatedListPublicDelegatedPrefixesRequest request = new AggregatedListPublicDelegatedPrefixesRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<PublicDelegatedPrefixAggregatedList, KeyValuePair<string, PublicDelegatedPrefixesScopedList>> response = publicDelegatedPrefixesClient.AggregatedList(request); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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 (PublicDelegatedPrefixAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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<KeyValuePair<string, PublicDelegatedPrefixesScopedList>> 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 (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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 AggregatedListAsync</summary> public async Task AggregatedListRequestObjectAsync() { // Snippet: AggregatedListAsync(AggregatedListPublicDelegatedPrefixesRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) AggregatedListPublicDelegatedPrefixesRequest request = new AggregatedListPublicDelegatedPrefixesRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<PublicDelegatedPrefixAggregatedList, KeyValuePair<string, PublicDelegatedPrefixesScopedList>> response = publicDelegatedPrefixesClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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((PublicDelegatedPrefixAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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<KeyValuePair<string, PublicDelegatedPrefixesScopedList>> 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 (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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 AggregatedList</summary> public void AggregatedList() { // Snippet: AggregatedList(string, string, int?, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<PublicDelegatedPrefixAggregatedList, KeyValuePair<string, PublicDelegatedPrefixesScopedList>> response = publicDelegatedPrefixesClient.AggregatedList(project); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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 (PublicDelegatedPrefixAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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<KeyValuePair<string, PublicDelegatedPrefixesScopedList>> 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 (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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 AggregatedListAsync</summary> public async Task AggregatedListAsync() { // Snippet: AggregatedListAsync(string, string, int?, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<PublicDelegatedPrefixAggregatedList, KeyValuePair<string, PublicDelegatedPrefixesScopedList>> response = publicDelegatedPrefixesClient.AggregatedListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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((PublicDelegatedPrefixAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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<KeyValuePair<string, PublicDelegatedPrefixesScopedList>> 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 (KeyValuePair<string, PublicDelegatedPrefixesScopedList> 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 Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeletePublicDelegatedPrefixeRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) DeletePublicDelegatedPrefixeRequest request = new DeletePublicDelegatedPrefixeRequest { RequestId = "", Region = "", PublicDelegatedPrefix = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = publicDelegatedPrefixesClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = publicDelegatedPrefixesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeletePublicDelegatedPrefixeRequest, CallSettings) // Additional: DeleteAsync(DeletePublicDelegatedPrefixeRequest, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) DeletePublicDelegatedPrefixeRequest request = new DeletePublicDelegatedPrefixeRequest { RequestId = "", Region = "", PublicDelegatedPrefix = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await publicDelegatedPrefixesClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await publicDelegatedPrefixesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, string, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string publicDelegatedPrefix = ""; // Make the request lro::Operation<Operation, Operation> response = publicDelegatedPrefixesClient.Delete(project, region, publicDelegatedPrefix); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = publicDelegatedPrefixesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, string, CallSettings) // Additional: DeleteAsync(string, string, string, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string publicDelegatedPrefix = ""; // Make the request lro::Operation<Operation, Operation> response = await publicDelegatedPrefixesClient.DeleteAsync(project, region, publicDelegatedPrefix); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await publicDelegatedPrefixesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetPublicDelegatedPrefixeRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) GetPublicDelegatedPrefixeRequest request = new GetPublicDelegatedPrefixeRequest { Region = "", PublicDelegatedPrefix = "", Project = "", }; // Make the request PublicDelegatedPrefix response = publicDelegatedPrefixesClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetPublicDelegatedPrefixeRequest, CallSettings) // Additional: GetAsync(GetPublicDelegatedPrefixeRequest, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) GetPublicDelegatedPrefixeRequest request = new GetPublicDelegatedPrefixeRequest { Region = "", PublicDelegatedPrefix = "", Project = "", }; // Make the request PublicDelegatedPrefix response = await publicDelegatedPrefixesClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, string, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string publicDelegatedPrefix = ""; // Make the request PublicDelegatedPrefix response = publicDelegatedPrefixesClient.Get(project, region, publicDelegatedPrefix); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, string, CallSettings) // Additional: GetAsync(string, string, string, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string publicDelegatedPrefix = ""; // Make the request PublicDelegatedPrefix response = await publicDelegatedPrefixesClient.GetAsync(project, region, publicDelegatedPrefix); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertPublicDelegatedPrefixeRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) InsertPublicDelegatedPrefixeRequest request = new InsertPublicDelegatedPrefixeRequest { RequestId = "", PublicDelegatedPrefixResource = new PublicDelegatedPrefix(), Region = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = publicDelegatedPrefixesClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = publicDelegatedPrefixesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertPublicDelegatedPrefixeRequest, CallSettings) // Additional: InsertAsync(InsertPublicDelegatedPrefixeRequest, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) InsertPublicDelegatedPrefixeRequest request = new InsertPublicDelegatedPrefixeRequest { RequestId = "", PublicDelegatedPrefixResource = new PublicDelegatedPrefix(), Region = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await publicDelegatedPrefixesClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await publicDelegatedPrefixesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, string, PublicDelegatedPrefix, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix(); // Make the request lro::Operation<Operation, Operation> response = publicDelegatedPrefixesClient.Insert(project, region, publicDelegatedPrefixResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = publicDelegatedPrefixesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, string, PublicDelegatedPrefix, CallSettings) // Additional: InsertAsync(string, string, PublicDelegatedPrefix, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix(); // Make the request lro::Operation<Operation, Operation> response = await publicDelegatedPrefixesClient.InsertAsync(project, region, publicDelegatedPrefixResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await publicDelegatedPrefixesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListPublicDelegatedPrefixesRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) ListPublicDelegatedPrefixesRequest request = new ListPublicDelegatedPrefixesRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = publicDelegatedPrefixesClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (PublicDelegatedPrefix 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 (PublicDelegatedPrefixList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PublicDelegatedPrefix 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<PublicDelegatedPrefix> 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 (PublicDelegatedPrefix 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(ListPublicDelegatedPrefixesRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) ListPublicDelegatedPrefixesRequest request = new ListPublicDelegatedPrefixesRequest { Region = "", OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = publicDelegatedPrefixesClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PublicDelegatedPrefix 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((PublicDelegatedPrefixList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PublicDelegatedPrefix 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<PublicDelegatedPrefix> 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 (PublicDelegatedPrefix 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, string, int?, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = publicDelegatedPrefixesClient.List(project, region); // Iterate over all response items, lazily performing RPCs as required foreach (PublicDelegatedPrefix 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 (PublicDelegatedPrefixList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PublicDelegatedPrefix 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<PublicDelegatedPrefix> 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 (PublicDelegatedPrefix 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, string, int?, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; // Make the request PagedAsyncEnumerable<PublicDelegatedPrefixList, PublicDelegatedPrefix> response = publicDelegatedPrefixesClient.ListAsync(project, region); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((PublicDelegatedPrefix 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((PublicDelegatedPrefixList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (PublicDelegatedPrefix 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<PublicDelegatedPrefix> 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 (PublicDelegatedPrefix 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 Patch</summary> public void PatchRequestObject() { // Snippet: Patch(PatchPublicDelegatedPrefixeRequest, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) PatchPublicDelegatedPrefixeRequest request = new PatchPublicDelegatedPrefixeRequest { RequestId = "", PublicDelegatedPrefixResource = new PublicDelegatedPrefix(), Region = "", PublicDelegatedPrefix = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = publicDelegatedPrefixesClient.Patch(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = publicDelegatedPrefixesClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchRequestObjectAsync() { // Snippet: PatchAsync(PatchPublicDelegatedPrefixeRequest, CallSettings) // Additional: PatchAsync(PatchPublicDelegatedPrefixeRequest, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) PatchPublicDelegatedPrefixeRequest request = new PatchPublicDelegatedPrefixeRequest { RequestId = "", PublicDelegatedPrefixResource = new PublicDelegatedPrefix(), Region = "", PublicDelegatedPrefix = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await publicDelegatedPrefixesClient.PatchAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await publicDelegatedPrefixesClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Patch</summary> public void Patch() { // Snippet: Patch(string, string, string, PublicDelegatedPrefix, CallSettings) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = PublicDelegatedPrefixesClient.Create(); // Initialize request argument(s) string project = ""; string region = ""; string publicDelegatedPrefix = ""; PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix(); // Make the request lro::Operation<Operation, Operation> response = publicDelegatedPrefixesClient.Patch(project, region, publicDelegatedPrefix, publicDelegatedPrefixResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = publicDelegatedPrefixesClient.PollOncePatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PatchAsync</summary> public async Task PatchAsync() { // Snippet: PatchAsync(string, string, string, PublicDelegatedPrefix, CallSettings) // Additional: PatchAsync(string, string, string, PublicDelegatedPrefix, CancellationToken) // Create client PublicDelegatedPrefixesClient publicDelegatedPrefixesClient = await PublicDelegatedPrefixesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; string publicDelegatedPrefix = ""; PublicDelegatedPrefix publicDelegatedPrefixResource = new PublicDelegatedPrefix(); // Make the request lro::Operation<Operation, Operation> response = await publicDelegatedPrefixesClient.PatchAsync(project, region, publicDelegatedPrefix, publicDelegatedPrefixResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await publicDelegatedPrefixesClient.PollOncePatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } } }
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 RealMocking.Areas.HelpPage.ModelDescriptions; using RealMocking.Areas.HelpPage.Models; namespace RealMocking.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; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Xunit; using Microsoft.Xunit.Performance; [assembly: OptimizeForBenchmarks] namespace Span { public class SpanBench { #if DEBUG const int BubbleSortIterations = 1; const int QuickSortIterations = 1; const int FillAllIterations = 1; const int BaseIterations = 1; #else // Appropriately-scaled iteration counts for the various benchmarks const int BubbleSortIterations = 100; const int QuickSortIterations = 1000; const int FillAllIterations = 100000; const int BaseIterations = 10000000; #endif // Default length for arrays of mock input data const int DefaultLength = 1024; // Helpers #region Helpers [StructLayout(LayoutKind.Sequential)] private sealed class TestClass<T> { private double _d; public T[] C0; } // Copying the result of a computation to Sink<T>.Instance is a way // to prevent the jit from considering the computation dead and removing it. private sealed class Sink<T> { public T Data; public static Sink<T> Instance = new Sink<T>(); } // Use statics to smuggle some information from Main to Invoke when running tests // from the command line. static bool IsXunitInvocation = true; // xunit-perf leaves this true; command line Main sets to false static int CommandLineInnerIterationCount = 0; // used to communicate iteration count from BenchmarkAttribute // (xunit-perf exposes the same in static property Benchmark.InnerIterationCount) static bool DoWarmUp; // Main sets this when calling a new benchmark routine // Invoke routine to abstract away the difference between running under xunit-perf vs running from the // command line. Inner loop to be measured is taken as an Action<int>, and invoked passing the number // of iterations that the inner loop should execute. static void Invoke(Action<int> innerLoop, string nameFormat, params object[] nameArgs) { if (IsXunitInvocation) { foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) innerLoop((int)Benchmark.InnerIterationCount); } else { if (DoWarmUp) { // Run some warm-up iterations before measuring innerLoop(CommandLineInnerIterationCount); // Clear the flag since we're now warmed up (caller will // reset it before calling new code) DoWarmUp = false; } // Now do the timed run of the inner loop. Stopwatch sw = Stopwatch.StartNew(); innerLoop(CommandLineInnerIterationCount); sw.Stop(); // Print result. string name = String.Format(nameFormat, nameArgs); double timeInMs = sw.Elapsed.TotalMilliseconds; Console.WriteLine("{0}: {1}ms", name, timeInMs); } } // Helper for the sort tests to get some pseudo-random input static int[] GetUnsortedData(int length) { int[] unsortedData = new int[length]; Random r = new Random(42); for (int i = 0; i < unsortedData.Length; ++i) { unsortedData[i] = r.Next(); } return unsortedData; } #endregion // helpers // Tests that implement some vary basic algorithms (fill/sort) over spans and arrays #region Algorithm tests #region TestFillAllSpan [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllSpan(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { Span<byte> s = new Span<byte>(a); for (int i = 0; i < innerIterationCount; ++i) { TestFillAllSpan(s); } }, "TestFillAllSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllSpan(Span<byte> span) { for (int i = 0; i < span.Length; ++i) { span[i] = unchecked((byte)i); } } #endregion #region TestFillAllArray [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllArray(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; ++i) { TestFillAllArray(a); } }, "TestFillArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllArray(byte[] data) { for (int i = 0; i < data.Length; ++i) { data[i] = unchecked((byte)i); } } #endregion #region TestFillAllReverseSpan [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllReverseSpan(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { Span<byte> s = new Span<byte>(a); for (int i = 0; i < innerIterationCount; ++i) { TestFillAllReverseSpan(s); } }, "TestFillAllReverseSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllReverseSpan(Span<byte> span) { for (int i = span.Length; --i >= 0;) { span[i] = unchecked((byte)i); } } #endregion #region TestFillAllReverseArray [Benchmark(InnerIterationCount = FillAllIterations)] [InlineData(DefaultLength)] public static void FillAllReverseArray(int length) { byte[] a = new byte[length]; Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; ++i) { TestFillAllReverseArray(a); } }, "TestFillAllReverseArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestFillAllReverseArray(byte[] data) { for (int i = data.Length; --i >= 0;) { data[i] = unchecked((byte)i); } } #endregion #region TestQuickSortSpan [Benchmark(InnerIterationCount = QuickSortIterations)] [InlineData(DefaultLength)] public static void QuickSortSpan(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { Span<int> span = new Span<int>(data); for (int i = 0; i < innerIterationCount; ++i) { Array.Copy(unsortedData, data, length); TestQuickSortSpan(span); } }, "TestQuickSortSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestQuickSortSpan(Span<int> data) { if (data.Length <= 1) { return; } int lo = 0; int hi = data.Length - 1; int i, j; int pivot, temp; for (i = lo, j = hi, pivot = data[hi]; i < j;) { while (i < j && data[i] <= pivot) { ++i; } while (j > i && data[j] >= pivot) { --j; } if (i < j) { temp = data[i]; data[i] = data[j]; data[j] = temp; } } if (i != hi) { temp = data[i]; data[i] = pivot; data[hi] = temp; } TestQuickSortSpan(data.Slice(0, i)); TestQuickSortSpan(data.Slice(i + 1)); } #endregion #region TestBubbleSortSpan [Benchmark(InnerIterationCount = BubbleSortIterations)] [InlineData(DefaultLength)] public static void BubbleSortSpan(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { Span<int> span = new Span<int>(data); for (int i = 0; i < innerIterationCount; i++) { Array.Copy(unsortedData, data, length); TestBubbleSortSpan(span); } }, "TestBubbleSortSpan({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestBubbleSortSpan(Span<int> span) { bool swap; int temp; int n = span.Length - 1; do { swap = false; for (int i = 0; i < n; i++) { if (span[i] > span[i + 1]) { temp = span[i]; span[i] = span[i + 1]; span[i + 1] = temp; swap = true; } } --n; } while (swap); } #endregion #region TestQuickSortArray [Benchmark(InnerIterationCount = QuickSortIterations)] [InlineData(DefaultLength)] public static void QuickSortArray(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; i++) { Array.Copy(unsortedData, data, length); TestQuickSortArray(data, 0, data.Length - 1); } }, "TestQuickSortArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestQuickSortArray(int[] data, int lo, int hi) { if (lo >= hi) { return; } int i, j; int pivot, temp; for (i = lo, j = hi, pivot = data[hi]; i < j;) { while (i < j && data[i] <= pivot) { ++i; } while (j > i && data[j] >= pivot) { --j; } if (i < j) { temp = data[i]; data[i] = data[j]; data[j] = temp; } } if (i != hi) { temp = data[i]; data[i] = pivot; data[hi] = temp; } TestQuickSortArray(data, lo, i - 1); TestQuickSortArray(data, i + 1, hi); } #endregion #region TestBubbleSortArray [Benchmark(InnerIterationCount = BubbleSortIterations)] [InlineData(DefaultLength)] public static void BubbleSortArray(int length) { int[] data = new int[length]; int[] unsortedData = GetUnsortedData(length); Invoke((int innerIterationCount) => { for (int i = 0; i < innerIterationCount; i++) { Array.Copy(unsortedData, data, length); TestBubbleSortArray(data); } }, "TestBubbleSortArray({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestBubbleSortArray(int[] data) { bool swap; int temp; int n = data.Length - 1; do { swap = false; for (int i = 0; i < n; i++) { if (data[i] > data[i + 1]) { temp = data[i]; data[i] = data[i + 1]; data[i + 1] = temp; swap = true; } } --n; } while (swap); } #endregion #endregion // Algorithm tests // TestSpanAPIs (For comparison with Array and Slow Span) #region TestSpanAPIs #region TestSpanConstructor<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanConstructorByte(int length) { InvokeTestSpanConstructor<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanConstructorString(int length) { InvokeTestSpanConstructor<string>(length); } static void InvokeTestSpanConstructor<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanConstructor<T>(array, innerIterationCount, false), "TestSpanConstructor<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanConstructor<T>(T[] array, int iterationCount, bool untrue) { var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) { var span = new Span<T>(array); // Under a condition that we know is false but the jit doesn't, // add a read from 'span' to make sure it's not dead, and an assignment // to 'array' so the constructor call won't get hoisted. if (untrue) { sink.Data = span[0]; array = new T[iterationCount]; } } } #endregion #region TestSpanDangerousCreate<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousCreateByte(int length) { InvokeTestSpanDangerousCreate<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousCreateString(int length) { InvokeTestSpanDangerousCreate<string>(length); } static void InvokeTestSpanDangerousCreate<T>(int length) { TestClass<T> testClass = new TestClass<T>(); testClass.C0 = new T[length]; Invoke((int innerIterationCount) => TestSpanDangerousCreate<T>(testClass, innerIterationCount, false), "TestSpanDangerousCreate<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanDangerousCreate<T>(TestClass<T> testClass, int iterationCount, bool untrue) { var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) { var span = Span<T>.DangerousCreate(testClass, ref testClass.C0[0], testClass.C0.Length); // Under a condition that we know is false but the jit doesn't, // add a read from 'span' to make sure it's not dead, and an assignment // to 'testClass' so the DangerousCreate call won't get hoisted. if (untrue) { sink.Data = span[0]; testClass = new TestClass<T>(); } } } #endregion #region TestSpanDangerousGetPinnableReference<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousGetPinnableReferenceByte(int length) { InvokeTestSpanDangerousGetPinnableReference<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanDangerousGetPinnableReferenceString(int length) { InvokeTestSpanDangerousGetPinnableReference<string>(length); } static void InvokeTestSpanDangerousGetPinnableReference<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanDangerousGetPinnableReference<T>(array, innerIterationCount), "TestSpanDangerousGetPinnableReference<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanDangerousGetPinnableReference<T>(T[] array, int iterationCount) { var sink = Sink<T>.Instance; var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) { ref T temp = ref span.DangerousGetPinnableReference(); sink.Data = temp; } } #endregion #region TestSpanIndexHoistable<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexHoistableByte(int length) { InvokeTestSpanIndexHoistable<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexHoistableString(int length) { InvokeTestSpanIndexHoistable<string>(length); } static void InvokeTestSpanIndexHoistable<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanIndexHoistable<T>(array, length, innerIterationCount), "TestSpanIndexHoistable<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanIndexHoistable<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) sink.Data = span[length/2]; } #endregion #region TestArrayIndexHoistable<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexHoistableByte(int length) { InvokeTestArrayIndexHoistable<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexHoistableString(int length) { InvokeTestArrayIndexHoistable<string>(length); } static void InvokeTestArrayIndexHoistable<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestArrayIndexHoistable<T>(array, length, innerIterationCount), "TestArrayIndexHoistable<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayIndexHoistable<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) sink.Data = array[length / 2]; } #endregion #region TestSpanIndexVariant<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexVariantByte(int length) { InvokeTestSpanIndexVariant<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanIndexVariantString(int length) { InvokeTestSpanIndexVariant<string>(length); } static void InvokeTestSpanIndexVariant<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanIndexVariant<T>(array, length, innerIterationCount), "TestSpanIndexVariant<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanIndexVariant<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; var span = new Span<T>(array); int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7)); for (int i = 0; i < iterationCount; i++) sink.Data = span[i & mask]; } #endregion #region TestArrayIndexVariant<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexVariantByte(int length) { InvokeTestArrayIndexVariant<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestArrayIndexVariantString(int length) { InvokeTestArrayIndexVariant<string>(length); } static void InvokeTestArrayIndexVariant<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestArrayIndexVariant<T>(array, length, innerIterationCount), "TestArrayIndexVariant<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayIndexVariant<T>(T[] array, int length, int iterationCount) { var sink = Sink<T>.Instance; int mask = (length < 2 ? 0 : (length < 8 ? 1 : 7)); for (int i = 0; i < iterationCount; i++) { sink.Data = array[i & mask]; } } #endregion #region TestSpanSlice<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanSliceByte(int length) { InvokeTestSpanSlice<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanSliceString(int length) { InvokeTestSpanSlice<string>(length); } static void InvokeTestSpanSlice<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanSlice<T>(array, length, innerIterationCount, false), "TestSpanSlice<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanSlice<T>(T[] array, int length, int iterationCount, bool untrue) { var span = new Span<T>(array); var sink = Sink<T>.Instance; for (int i = 0; i < iterationCount; i++) { var slice = span.Slice(length / 2); // Under a condition that we know is false but the jit doesn't, // add a read from 'span' to make sure it's not dead, and an assignment // to 'array' so the slice call won't get hoisted. if (untrue) { sink.Data = slice[0]; array = new T[iterationCount]; } } } #endregion #region TestSpanToArray<T> [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanToArrayByte(int length) { InvokeTestSpanToArray<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanToArrayString(int length) { InvokeTestSpanToArray<string>(length); } static void InvokeTestSpanToArray<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanToArray<T>(array, length, innerIterationCount), "TestSpanToArray<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanToArray<T>(T[] array, int length, int iterationCount) { var span = new Span<T>(array); var sink = Sink<T[]>.Instance; for (int i = 0; i < iterationCount; i++) sink.Data = span.ToArray(); } #endregion #region TestSpanCopyTo<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestSpanCopyToByte(int length) { InvokeTestSpanCopyTo<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanCopyToString(int length) { InvokeTestSpanCopyTo<string>(length); } static void InvokeTestSpanCopyTo<T>(int length) { var array = new T[length]; var destArray = new T[array.Length]; Invoke((int innerIterationCount) => TestSpanCopyTo<T>(array, destArray, innerIterationCount), "TestSpanCopyTo<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanCopyTo<T>(T[] array, T[] destArray, int iterationCount) { var span = new Span<T>(array); var destination = new Span<T>(destArray); for (int i = 0; i < iterationCount; i++) span.CopyTo(destination); } #endregion #region TestArrayCopyTo<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestArrayCopyToByte(int length) { InvokeTestArrayCopyTo<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestArrayCopyToString(int length) { InvokeTestArrayCopyTo<string>(length); } static void InvokeTestArrayCopyTo<T>(int length) { var array = new T[length]; var destination = new T[array.Length]; Invoke((int innerIterationCount) => TestArrayCopyTo<T>(array, destination, innerIterationCount), "TestArrayCopyTo<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayCopyTo<T>(T[] array, T[] destination, int iterationCount) { for (int i = 0; i < iterationCount; i++) array.CopyTo(destination, 0); } #endregion #region TestSpanFill<T> [Benchmark(InnerIterationCount = BaseIterations * 10)] [InlineData(100)] public static void TestSpanFillByte(int length) { InvokeTestSpanFill<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 100)] [InlineData(100)] public static void TestSpanFillString(int length) { InvokeTestSpanFill<string>(length); } static void InvokeTestSpanFill<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanFill<T>(array, innerIterationCount), "TestSpanFill<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanFill<T>(T[] array, int iterationCount) { var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) span.Fill(default(T)); } #endregion #region TestSpanClear<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestSpanClearByte(int length) { InvokeTestSpanClear<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestSpanClearString(int length) { InvokeTestSpanClear<string>(length); } static void InvokeTestSpanClear<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanClear<T>(array, innerIterationCount), "TestSpanClear<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanClear<T>(T[] array, int iterationCount) { var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) span.Clear(); } #endregion #region TestArrayClear<T> [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestArrayClearByte(int length) { InvokeTestArrayClear<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations / 10)] [InlineData(100)] public static void TestArrayClearString(int length) { InvokeTestArrayClear<string>(length); } static void InvokeTestArrayClear<T>(int length) { var array = new T[length]; Invoke((int innerIterationCount) => TestArrayClear<T>(array, length, innerIterationCount), "TestArrayClear<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestArrayClear<T>(T[] array, int length, int iterationCount) { for (int i = 0; i < iterationCount; i++) Array.Clear(array, 0, length); } #endregion #region TestSpanAsBytes<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanAsBytesByte(int length) { InvokeTestSpanAsBytes<byte>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanAsBytesInt(int length) { InvokeTestSpanAsBytes<int>(length); } static void InvokeTestSpanAsBytes<T>(int length) where T : struct { var array = new T[length]; Invoke((int innerIterationCount) => TestSpanAsBytes<T>(array, innerIterationCount, false), "TestSpanAsBytes<{0}>({1})", typeof(T).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanAsBytes<T>(T[] array, int iterationCount, bool untrue) where T : struct { var sink = Sink<byte>.Instance; var span = new Span<T>(array); for (int i = 0; i < iterationCount; i++) { var byteSpan = span.AsBytes(); // Under a condition that we know is false but the jit doesn't, // add a read from 'byteSpan' to make sure it's not dead, and an assignment // to 'span' so the AsBytes call won't get hoisted. if (untrue) { sink.Data = byteSpan[0]; span = new Span<T>(); } } } #endregion #region TestSpanNonPortableCast<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanNonPortableCastFromByteToInt(int length) { InvokeTestSpanNonPortableCast<byte, int>(length); } [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanNonPortableCastFromIntToByte(int length) { InvokeTestSpanNonPortableCast<int, byte>(length); } static void InvokeTestSpanNonPortableCast<From, To>(int length) where From : struct where To : struct { var array = new From[length]; Invoke((int innerIterationCount) => TestSpanNonPortableCast<From, To>(array, innerIterationCount, false), "TestSpanNonPortableCast<{0}, {1}>({2})", typeof(From).Name, typeof(To).Name, length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanNonPortableCast<From, To>(From[] array, int iterationCount, bool untrue) where From : struct where To : struct { var sink = Sink<To>.Instance; var span = new Span<From>(array); for (int i = 0; i < iterationCount; i++) { var toSpan = span.NonPortableCast<From, To>(); // Under a condition that we know is false but the jit doesn't, // add a read from 'toSpan' to make sure it's not dead, and an assignment // to 'span' so the AsBytes call won't get hoisted. if (untrue) { sink.Data = toSpan[0]; span = new Span<From>(); } } } #endregion #region TestSpanAsReadOnlySpanStringChar<T> [Benchmark(InnerIterationCount = BaseIterations)] [InlineData(100)] public static void TestSpanAsReadOnlySpanStringCharWrapper(int length) { StringBuilder sb = new StringBuilder(); Random rand = new Random(42); char[] c = new char[1]; for (int i = 0; i < length; i++) { c[0] = (char)rand.Next(32, 126); sb.Append(new string(c)); } string s = sb.ToString(); Invoke((int innerIterationCount) => TestSpanAsReadOnlySpanStringChar(s, innerIterationCount, false), "TestSpanAsReadOnlySpanStringChar({0})", length); } [MethodImpl(MethodImplOptions.NoInlining)] static void TestSpanAsReadOnlySpanStringChar(string s, int iterationCount, bool untrue) { var sink = Sink<char>.Instance; for (int i = 0; i < iterationCount; i++) { var charSpan = s.AsReadOnlySpan(); // Under a condition that we know is false but the jit doesn't, // add a read from 'charSpan' to make sure it's not dead, and an assignment // to 's' so the AsBytes call won't get hoisted. if (untrue) { sink.Data = charSpan[0]; s = "block hoisting the call to AsReadOnlySpan()"; } } } #endregion #endregion // TestSpanAPIs public static int Main(string[] args) { // When we call into Invoke, it'll need to know this isn't xunit-perf running IsXunitInvocation = false; // Now simulate xunit-perf's benchmark discovery so we know what tests to invoke TypeInfo t = typeof(SpanBench).GetTypeInfo(); foreach(MethodInfo m in t.DeclaredMethods) { BenchmarkAttribute benchAttr = m.GetCustomAttribute<BenchmarkAttribute>(); if (benchAttr != null) { // All benchmark methods in this test set the InnerIterationCount on their BenchmarkAttribute. // Take max of specified count and 1 since some tests use expressions for their count that // evaluate to 0 under DEBUG. CommandLineInnerIterationCount = Math.Max((int)benchAttr.InnerIterationCount, 1); // Request a warm-up iteration before measuring this benchmark method. DoWarmUp = true; // Get the benchmark to measure as a delegate taking the number of inner-loop iterations to run var invokeMethod = m.CreateDelegate(typeof(Action<int>)) as Action<int>; // All the benchmarks methods in this test use [InlineData] to specify how many times and with // what arguments they should be run. foreach (InlineDataAttribute dataAttr in m.GetCustomAttributes<InlineDataAttribute>()) { foreach (object[] data in dataAttr.GetData(m)) { // All the benchmark methods in this test take a single int parameter invokeMethod((int)data[0]); } } } } // The only failure modes are crash/exception. return 100; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Wyam.Common; using Wyam.Common.Caching; using Wyam.Common.Documents; using Wyam.Common.IO; using Wyam.Common.Meta; using Wyam.Common.Execution; namespace Wyam.Modules.CodeAnalysis { internal class AnalyzeSymbolVisitor : SymbolVisitor { private readonly ConcurrentDictionary<ISymbol, IDocument> _symbolToDocument = new ConcurrentDictionary<ISymbol, IDocument>(); private readonly ConcurrentDictionary<string, IDocument> _commentIdToDocument = new ConcurrentDictionary<string, IDocument>(); private ImmutableArray<KeyValuePair<INamedTypeSymbol, IDocument>> _namedTypes; // This contains all of the NamedType symbols and documents obtained during the initial processing private readonly IExecutionContext _context; private readonly Func<ISymbol, bool> _symbolPredicate; private readonly Func<IMetadata, FilePath> _writePath; private readonly ConcurrentDictionary<string, string> _cssClasses; private readonly bool _docsForImplicitSymbols; private bool _finished; // When this is true, we're visiting external symbols and should omit certain metadata and don't descend public AnalyzeSymbolVisitor( IExecutionContext context, Func<ISymbol, bool> symbolPredicate, Func<IMetadata, FilePath> writePath, ConcurrentDictionary<string, string> cssClasses, bool docsForImplicitSymbols) { _context = context; _symbolPredicate = symbolPredicate; _writePath = writePath; _cssClasses = cssClasses; _docsForImplicitSymbols = docsForImplicitSymbols; } public IEnumerable<IDocument> Finish() { _finished = true; _namedTypes = _symbolToDocument .Where(x => x.Key.Kind == SymbolKind.NamedType) .Select(x => new KeyValuePair<INamedTypeSymbol, IDocument>((INamedTypeSymbol)x.Key, x.Value)) .ToImmutableArray(); return _symbolToDocument.Select(x => x.Value); } public bool TryGetDocument(ISymbol symbol, out IDocument document) { return _symbolToDocument.TryGetValue(symbol, out document); } public override void VisitNamespace(INamespaceSymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { AddDocument(symbol, true, new MetadataItems { { CodeAnalysisKeys.SpecificKind, (k, m) => symbol.Kind.ToString() }, { CodeAnalysisKeys.MemberNamespaces, DocumentsFor(symbol.GetNamespaceMembers()) }, { CodeAnalysisKeys.MemberTypes, DocumentsFor(symbol.GetTypeMembers()) } }); } // Descend if not finished, regardless if this namespace was included if (!_finished) { Parallel.ForEach(symbol.GetMembers(), s => s.Accept(this)); } } public override void VisitNamedType(INamedTypeSymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { MetadataItems metadata = new MetadataItems { { CodeAnalysisKeys.SpecificKind, (k, m) => symbol.TypeKind.ToString() }, { CodeAnalysisKeys.ContainingType, DocumentFor(symbol.ContainingType) }, { CodeAnalysisKeys.MemberTypes, DocumentsFor(symbol.GetTypeMembers()) }, { CodeAnalysisKeys.BaseType, DocumentFor(symbol.BaseType) }, { CodeAnalysisKeys.AllInterfaces, DocumentsFor(symbol.AllInterfaces) }, { CodeAnalysisKeys.Members, DocumentsFor(symbol.GetMembers().Where(MemberPredicate)) }, { CodeAnalysisKeys.Constructors, DocumentsFor(symbol.Constructors.Where(x => !x.IsImplicitlyDeclared)) }, { CodeAnalysisKeys.TypeParameters, DocumentsFor(symbol.TypeParameters) }, { CodeAnalysisKeys.Accessibility, (k, m) => symbol.DeclaredAccessibility.ToString() } }; if (!_finished) { metadata.AddRange(new [] { new MetadataItem(CodeAnalysisKeys.DerivedTypes, (k, m) => GetDerivedTypes(symbol), true), new MetadataItem(CodeAnalysisKeys.ImplementingTypes, (k, m) => GetImplementingTypes(symbol), true) }); } AddDocument(symbol, true, metadata); // Descend if not finished, and only if this type was included if (!_finished) { Parallel.ForEach(symbol.GetMembers() .Where(MemberPredicate) .Concat(symbol.Constructors.Where(x => !x.IsImplicitlyDeclared)), s => s.Accept(this)); } } } public override void VisitTypeParameter(ITypeParameterSymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { AddDocumentForMember(symbol, false, new MetadataItems { new MetadataItem(CodeAnalysisKeys.SpecificKind, (k, m) => symbol.TypeParameterKind.ToString()), new MetadataItem(CodeAnalysisKeys.DeclaringType, DocumentFor(symbol.DeclaringType)) }); } } public override void VisitParameter(IParameterSymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { AddDocumentForMember(symbol, false, new MetadataItems { new MetadataItem(CodeAnalysisKeys.SpecificKind, (k, m) => symbol.Kind.ToString()), new MetadataItem(CodeAnalysisKeys.Type, DocumentFor(symbol.Type)) }); } } public override void VisitMethod(IMethodSymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { AddDocumentForMember(symbol, true, new MetadataItems { new MetadataItem(CodeAnalysisKeys.SpecificKind, (k, m) => symbol.MethodKind == MethodKind.Ordinary ? "Method" : symbol.MethodKind.ToString()), new MetadataItem(CodeAnalysisKeys.TypeParameters, DocumentsFor(symbol.TypeParameters)), new MetadataItem(CodeAnalysisKeys.Parameters, DocumentsFor(symbol.Parameters)), new MetadataItem(CodeAnalysisKeys.ReturnType, DocumentFor(symbol.ReturnType)), new MetadataItem(CodeAnalysisKeys.OverriddenMethod, DocumentFor(symbol.OverriddenMethod)), new MetadataItem(CodeAnalysisKeys.Accessibility, (k, m) => symbol.DeclaredAccessibility.ToString()) }); } } public override void VisitField(IFieldSymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { AddDocumentForMember(symbol, true, new MetadataItems { new MetadataItem(CodeAnalysisKeys.SpecificKind, (k, m) => symbol.Kind.ToString()), new MetadataItem(CodeAnalysisKeys.Type, DocumentFor(symbol.Type)), new MetadataItem(CodeAnalysisKeys.Accessibility, (k, m) => symbol.DeclaredAccessibility.ToString()) }); } } public override void VisitEvent(IEventSymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { AddDocumentForMember(symbol, true, new MetadataItems { new MetadataItem(CodeAnalysisKeys.SpecificKind, (k, m) => symbol.Kind.ToString()), new MetadataItem(CodeAnalysisKeys.Type, DocumentFor(symbol.Type)), new MetadataItem(CodeAnalysisKeys.OverriddenMethod, DocumentFor(symbol.OverriddenEvent)), new MetadataItem(CodeAnalysisKeys.Accessibility, (k, m) => symbol.DeclaredAccessibility.ToString()) }); } } public override void VisitProperty(IPropertySymbol symbol) { if (_finished || _symbolPredicate == null || _symbolPredicate(symbol)) { AddDocumentForMember(symbol, true, new MetadataItems { new MetadataItem(CodeAnalysisKeys.SpecificKind, (k, m) => symbol.Kind.ToString()), new MetadataItem(CodeAnalysisKeys.Parameters, DocumentsFor(symbol.Parameters)), new MetadataItem(CodeAnalysisKeys.Type, DocumentFor(symbol.Type)), new MetadataItem(CodeAnalysisKeys.OverriddenMethod, DocumentFor(symbol.OverriddenProperty)), new MetadataItem(CodeAnalysisKeys.Accessibility, (k, m) => symbol.DeclaredAccessibility.ToString()) }); } } // Helpers below... private bool MemberPredicate(ISymbol symbol) { IPropertySymbol propertySymbol = symbol as IPropertySymbol; if (propertySymbol != null && propertySymbol.IsIndexer) { // Special case for indexers return true; } return symbol.CanBeReferencedByName && !symbol.IsImplicitlyDeclared; } private void AddDocumentForMember(ISymbol symbol, bool xmlDocumentation, MetadataItems items) { items.AddRange(new[] { new MetadataItem(CodeAnalysisKeys.ContainingType, DocumentFor(symbol.ContainingType)) }); AddDocument(symbol, xmlDocumentation, items); } private void AddDocument(ISymbol symbol, bool xmlDocumentation, MetadataItems items) { // Get universal metadata items.AddRange(new [] { // In general, cache the values that need calculation and don't cache the ones that are just properties of ISymbol new MetadataItem(CodeAnalysisKeys.IsResult, !_finished), new MetadataItem(CodeAnalysisKeys.SymbolId, (k, m) => GetId(symbol), true), new MetadataItem(CodeAnalysisKeys.Symbol, symbol), new MetadataItem(CodeAnalysisKeys.Name, (k, m) => symbol.Name), new MetadataItem(CodeAnalysisKeys.FullName, (k, m) => GetFullName(symbol), true), new MetadataItem(CodeAnalysisKeys.DisplayName, (k, m) => GetDisplayName(symbol), true), new MetadataItem(CodeAnalysisKeys.QualifiedName, (k, m) => GetQualifiedName(symbol), true), new MetadataItem(CodeAnalysisKeys.Kind, (k, m) => symbol.Kind.ToString()), new MetadataItem(CodeAnalysisKeys.ContainingNamespace, DocumentFor(symbol.ContainingNamespace)), new MetadataItem(CodeAnalysisKeys.Syntax, (k, m) => GetSyntax(symbol), true) }); // Add metadata that's specific to initially-processed symbols if (!_finished) { items.AddRange(new[] { new MetadataItem(Keys.WritePath, (k, m) => _writePath(m), true), new MetadataItem(Keys.RelativeFilePath, (k, m) => m.FilePath(Keys.WritePath)), new MetadataItem(Keys.RelativeFilePathBase, (k, m) => { FilePath writePath = m.FilePath(Keys.WritePath); return writePath.Directory.CombineFile(writePath.FileNameWithoutExtension); }), new MetadataItem(Keys.RelativeFileDir, (k, m) => m.FilePath(Keys.WritePath).Directory) }); } // XML Documentation if (xmlDocumentation && (!_finished || _docsForImplicitSymbols)) { AddXmlDocumentation(symbol, items); } // Create the document and add it to the cache IDocument document = _context.GetDocument(new FilePath(NormalizedPath.AbstractProvider, symbol.ToDisplayString(), true), null, items); _symbolToDocument.GetOrAdd(symbol, _ => document); // Map the comment ID to the document if (!_finished) { string documentationCommentId = symbol.GetDocumentationCommentId(); if (documentationCommentId != null) { _commentIdToDocument.GetOrAdd(documentationCommentId, _ => document); } } } private void AddXmlDocumentation(ISymbol symbol, MetadataItems metadata) { string documentationCommentXml = symbol.GetDocumentationCommentXml(expandIncludes: true); XmlDocumentationParser xmlDocumentationParser = new XmlDocumentationParser(_context, symbol, _commentIdToDocument, _cssClasses); IEnumerable<string> otherHtmlElementNames = xmlDocumentationParser.Parse(documentationCommentXml); // Add standard HTML elements metadata.AddRange(new [] { new MetadataItem(CodeAnalysisKeys.CommentXml, documentationCommentXml), new MetadataItem(CodeAnalysisKeys.Example, (k, m) => xmlDocumentationParser.Process().Example), new MetadataItem(CodeAnalysisKeys.Remarks, (k, m) => xmlDocumentationParser.Process().Remarks), new MetadataItem(CodeAnalysisKeys.Summary, (k, m) => xmlDocumentationParser.Process().Summary), new MetadataItem(CodeAnalysisKeys.Returns, (k, m) => xmlDocumentationParser.Process().Returns), new MetadataItem(CodeAnalysisKeys.Value, (k, m) => xmlDocumentationParser.Process().Value), new MetadataItem(CodeAnalysisKeys.Exceptions, (k, m) => xmlDocumentationParser.Process().Exceptions), new MetadataItem(CodeAnalysisKeys.Permissions, (k, m) => xmlDocumentationParser.Process().Permissions), new MetadataItem(CodeAnalysisKeys.Params, (k, m) => xmlDocumentationParser.Process().Params), new MetadataItem(CodeAnalysisKeys.TypeParams, (k, m) => xmlDocumentationParser.Process().TypeParams), new MetadataItem(CodeAnalysisKeys.SeeAlso, (k, m) => xmlDocumentationParser.Process().SeeAlso) }); // Add other HTML elements with keys of [ElementName]Html metadata.AddRange(otherHtmlElementNames.Select(x => new MetadataItem(FirstLetterToUpper(x) + "Comments", (k, m) => xmlDocumentationParser.Process().OtherComments[x]))); } public static string FirstLetterToUpper(string str) { if (str == null) { return null; } if (str.Length > 1) { return char.ToUpper(str[0]) + str.Substring(1); } return str.ToUpper(); } private static string GetId(ISymbol symbol) { return BitConverter.ToString(BitConverter.GetBytes(Crc32.Calculate(symbol.GetDocumentationCommentId() ?? GetFullName(symbol)))).Replace("-", string.Empty); } private static string GetFullName(ISymbol symbol) { return symbol.ToDisplayString(new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeType, memberOptions: SymbolDisplayMemberOptions.IncludeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes)); } private static string GetQualifiedName(ISymbol symbol) { return symbol.ToDisplayString(new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters)); } private static string GetDisplayName(ISymbol symbol) { if (symbol.Kind == SymbolKind.Namespace) { // Use "global" for the global namespace display name since it's a reserved keyword and it's used to refer to the global namespace in code return symbol.ContainingNamespace == null ? "global" : GetQualifiedName(symbol); } return GetFullName(symbol); } private IReadOnlyList<IDocument> GetDerivedTypes(INamedTypeSymbol symbol) { return _namedTypes .Where(x => x.Key.BaseType != null && x.Key.BaseType.Equals(symbol)) .Select(x => x.Value) .ToImmutableArray(); } private IReadOnlyList<IDocument> GetImplementingTypes(INamedTypeSymbol symbol) { return _namedTypes .Where(x => x.Key.AllInterfaces.Contains(symbol)) .Select(x => x.Value) .ToImmutableArray(); } private string GetSyntax(ISymbol symbol) { return SyntaxHelper.GetSyntax(symbol); } private SymbolDocumentValue DocumentFor(ISymbol symbol) { return new SymbolDocumentValue(symbol, this); } private SymbolDocumentValues DocumentsFor(IEnumerable<ISymbol> symbols) { return new SymbolDocumentValues(symbols, this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Moq; using System; using System.Buffers; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.AspNetCore.WebUtilities { public class HttpRequestStreamReaderTest { private static readonly char[] CharData = new char[] { char.MinValue, char.MaxValue, '\t', ' ', '$', '@', '#', '\0', '\v', '\'', '\u3190', '\uC3A0', 'A', '5', '\r', '\uFE70', '-', ';', '\r', '\n', 'T', '3', '\n', 'K', '\u00E6', }; [Fact] public static async Task ReadToEndAsync() { // Arrange var reader = new HttpRequestStreamReader(GetLargeStream(), Encoding.UTF8); var result = await reader.ReadToEndAsync(); Assert.Equal(5000, result.Length); } [Fact] public static async Task ReadToEndAsync_Reads_Asynchronously() { // Arrange var stream = new AsyncOnlyStreamWrapper(GetLargeStream()); var reader = new HttpRequestStreamReader(stream, Encoding.UTF8); var streamReader = new StreamReader(GetLargeStream()); string expected = await streamReader.ReadToEndAsync(); // Act var actual = await reader.ReadToEndAsync(); // Assert Assert.Equal(expected, actual); } [Fact] public static void TestRead() { // Arrange var reader = CreateReader(); // Act & Assert for (var i = 0; i < CharData.Length; i++) { var tmp = reader.Read(); Assert.Equal((int)CharData[i], tmp); } } [Fact] public static void TestPeek() { // Arrange var reader = CreateReader(); // Act & Assert for (var i = 0; i < CharData.Length; i++) { var peek = reader.Peek(); Assert.Equal((int)CharData[i], peek); reader.Read(); } } [Fact] public static void EmptyStream() { // Arrange var reader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8); var buffer = new char[10]; // Act var read = reader.Read(buffer, 0, 1); // Assert Assert.Equal(0, read); } [Fact] public static void Read_ReadAllCharactersAtOnce() { // Arrange var reader = CreateReader(); var chars = new char[CharData.Length]; // Act var read = reader.Read(chars, 0, chars.Length); // Assert Assert.Equal(chars.Length, read); for (var i = 0; i < CharData.Length; i++) { Assert.Equal(CharData[i], chars[i]); } } [Fact] public static async Task ReadAsync_ReadInTwoChunks() { // Arrange var reader = CreateReader(); var chars = new char[CharData.Length]; // Act var read = await reader.ReadAsync(chars, 4, 3); // Assert Assert.Equal(3, read); for (var i = 0; i < 3; i++) { Assert.Equal(CharData[i], chars[i + 4]); } } [Theory] [MemberData(nameof(ReadLineData))] public static async Task ReadLine_ReadMultipleLines(Func<HttpRequestStreamReader, Task<string>> action) { // Arrange var reader = CreateReader(); var valueString = new string(CharData); // Act & Assert var data = await action(reader); Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data); data = await action(reader); Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data); data = await action(reader); Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data); data = await action(reader); Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data); } [Theory] [MemberData(nameof(ReadLineData))] public static async Task ReadLine_ReadWithNoNewlines(Func<HttpRequestStreamReader, Task<string>> action) { // Arrange var reader = CreateReader(); var valueString = new string(CharData); var temp = new char[10]; // Act reader.Read(temp, 0, 1); var data = await action(reader); // Assert Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data); } [Theory] [MemberData(nameof(ReadLineData))] public static async Task ReadLine_MultipleContinuousLines(Func<HttpRequestStreamReader, Task<string>> action) { // Arrange var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write("\n\n\r\r\n\r"); writer.Flush(); stream.Position = 0; var reader = new HttpRequestStreamReader(stream, Encoding.UTF8); // Act & Assert for (var i = 0; i < 5; i++) { var data = await action(reader); Assert.Equal(string.Empty, data); } var eof = await action(reader); Assert.Null(eof); } [Theory] [MemberData(nameof(ReadLineData))] public static async Task ReadLine_CarriageReturnAndLineFeedAcrossBufferBundaries(Func<HttpRequestStreamReader, Task<string>> action) { // Arrange var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write("123456789\r\nfoo"); writer.Flush(); stream.Position = 0; var reader = new HttpRequestStreamReader(stream, Encoding.UTF8, 10); // Act & Assert var data = await action(reader); Assert.Equal("123456789", data); data = await action(reader); Assert.Equal("foo", data); var eof = await action(reader); Assert.Null(eof); } [Theory] [MemberData(nameof(ReadLineData))] public static async Task ReadLine_EOF(Func<HttpRequestStreamReader, Task<string>> action) { // Arrange var stream = new MemoryStream(); var reader = new HttpRequestStreamReader(stream, Encoding.UTF8); // Act & Assert var eof = await action(reader); Assert.Null(eof); } [Theory] [MemberData(nameof(ReadLineData))] public static async Task ReadLine_NewLineOnly(Func<HttpRequestStreamReader, Task<string>> action) { // Arrange var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write("\r\n"); writer.Flush(); stream.Position = 0; var reader = new HttpRequestStreamReader(stream, Encoding.UTF8); // Act & Assert var empty = await action(reader); Assert.Equal(string.Empty, empty); } [Fact] public static void Read_Span_ReadAllCharactersAtOnce() { // Arrange var reader = CreateReader(); var chars = new char[CharData.Length]; var span = new Span<char>(chars); // Act var read = reader.Read(span); // Assert Assert.Equal(chars.Length, read); for (var i = 0; i < CharData.Length; i++) { Assert.Equal(CharData[i], chars[i]); } } [Fact] public static void Read_Span_WithMoreDataThanInternalBufferSize() { // Arrange var reader = CreateReader(10); var chars = new char[CharData.Length]; var span = new Span<char>(chars); // Act var read = reader.Read(span); // Assert Assert.Equal(chars.Length, read); for (var i = 0; i < CharData.Length; i++) { Assert.Equal(CharData[i], chars[i]); } } [Fact] public static async Task ReadAsync_Memory_ReadAllCharactersAtOnce() { // Arrange var reader = CreateReader(); var chars = new char[CharData.Length]; var memory = new Memory<char>(chars); // Act var read = await reader.ReadAsync(memory); // Assert Assert.Equal(chars.Length, read); for (var i = 0; i < CharData.Length; i++) { Assert.Equal(CharData[i], chars[i]); } } [Fact] public static async Task ReadAsync_Memory_WithMoreDataThanInternalBufferSize() { // Arrange var reader = CreateReader(10); var chars = new char[CharData.Length]; var memory = new Memory<char>(chars); // Act var read = await reader.ReadAsync(memory); // Assert Assert.Equal(chars.Length, read); for (var i = 0; i < CharData.Length; i++) { Assert.Equal(CharData[i], chars[i]); } } [Theory] [MemberData(nameof(HttpRequestNullData))] public static void NullInputsInConstructor_ExpectArgumentNullException(Stream stream, Encoding encoding, ArrayPool<byte> bytePool, ArrayPool<char> charPool) { Assert.Throws<ArgumentNullException>(() => { var httpRequestStreamReader = new HttpRequestStreamReader(stream, encoding, 1, bytePool, charPool); }); } [Theory] [InlineData(0)] [InlineData(-1)] public static void NegativeOrZeroBufferSize_ExpectArgumentOutOfRangeException(int size) { Assert.Throws<ArgumentOutOfRangeException>(() => { var httpRequestStreamReader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8, size, ArrayPool<byte>.Shared, ArrayPool<char>.Shared); }); } [Fact] public static void StreamCannotRead_ExpectArgumentException() { var mockStream = new Mock<Stream>(); mockStream.Setup(m => m.CanRead).Returns(false); Assert.Throws<ArgumentException>(() => { var httpRequestStreamReader = new HttpRequestStreamReader(mockStream.Object, Encoding.UTF8, 1, ArrayPool<byte>.Shared, ArrayPool<char>.Shared); }); } [Theory] [MemberData(nameof(HttpRequestDisposeData))] public static void StreamDisposed_ExpectedObjectDisposedException(Action<HttpRequestStreamReader> action) { var httpRequestStreamReader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8, 10, ArrayPool<byte>.Shared, ArrayPool<char>.Shared); httpRequestStreamReader.Dispose(); Assert.Throws<ObjectDisposedException>(() => { action(httpRequestStreamReader); }); } [Theory] [MemberData(nameof(HttpRequestDisposeDataAsync))] public static async Task StreamDisposed_ExpectObjectDisposedExceptionAsync(Func<HttpRequestStreamReader, Task> action) { var httpRequestStreamReader = new HttpRequestStreamReader(new MemoryStream(), Encoding.UTF8, 10, ArrayPool<byte>.Shared, ArrayPool<char>.Shared); httpRequestStreamReader.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => action(httpRequestStreamReader)); } private static HttpRequestStreamReader CreateReader() { MemoryStream stream = CreateStream(); return new HttpRequestStreamReader(stream, Encoding.UTF8); } private static HttpRequestStreamReader CreateReader(int bufferSize) { MemoryStream stream = CreateStream(); return new HttpRequestStreamReader(stream, Encoding.UTF8, bufferSize); } private static MemoryStream CreateStream() { var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(CharData); writer.Flush(); stream.Position = 0; return stream; } private static MemoryStream GetSmallStream() { var testData = new byte[] { 72, 69, 76, 76, 79 }; return new MemoryStream(testData); } private static MemoryStream GetLargeStream() { var testData = new byte[] { 72, 69, 76, 76, 79 }; // System.Collections.Generic. var data = new List<byte>(); for (var i = 0; i < 1000; i++) { data.AddRange(testData); } return new MemoryStream(data.ToArray()); } public static IEnumerable<object?[]> HttpRequestNullData() { yield return new object?[] { null, Encoding.UTF8, ArrayPool<byte>.Shared, ArrayPool<char>.Shared }; yield return new object?[] { new MemoryStream(), null, ArrayPool<byte>.Shared, ArrayPool<char>.Shared }; yield return new object?[] { new MemoryStream(), Encoding.UTF8, null, ArrayPool<char>.Shared }; yield return new object?[] { new MemoryStream(), Encoding.UTF8, ArrayPool<byte>.Shared, null }; } public static IEnumerable<object[]> HttpRequestDisposeData() { yield return new object[] { new Action<HttpRequestStreamReader>((httpRequestStreamReader) => { var res = httpRequestStreamReader.Read(); })}; yield return new object[] { new Action<HttpRequestStreamReader>((httpRequestStreamReader) => { var res = httpRequestStreamReader.Read(new char[10], 0, 1); })}; yield return new object[] { new Action<HttpRequestStreamReader>((httpRequestStreamReader) => { var res = httpRequestStreamReader.Read(new Span<char>(new char[10], 0, 1)); })}; yield return new object[] { new Action<HttpRequestStreamReader>((httpRequestStreamReader) => { var res = httpRequestStreamReader.Peek(); })}; } public static IEnumerable<object[]> HttpRequestDisposeDataAsync() { yield return new object[] { new Func<HttpRequestStreamReader, Task>(async (httpRequestStreamReader) => { await httpRequestStreamReader.ReadAsync(new char[10], 0, 1); })}; yield return new object[] { new Func<HttpRequestStreamReader, Task>(async (httpRequestStreamReader) => { await httpRequestStreamReader.ReadAsync(new Memory<char>(new char[10], 0, 1)); })}; } public static IEnumerable<object[]> ReadLineData() { yield return new object[] { new Func<HttpRequestStreamReader, Task<string?>>((httpRequestStreamReader) => Task.FromResult(httpRequestStreamReader.ReadLine()) )}; yield return new object[] { new Func<HttpRequestStreamReader, Task<string?>>((httpRequestStreamReader) => httpRequestStreamReader.ReadLineAsync() )}; } private class AsyncOnlyStreamWrapper : Stream { private readonly Stream _inner; public AsyncOnlyStreamWrapper(Stream inner) { _inner = inner; } public override bool CanRead => _inner.CanRead; public override bool CanSeek => _inner.CanSeek; public override bool CanWrite => _inner.CanWrite; public override long Length => _inner.Length; public override long Position { get => _inner.Position; set => _inner.Position = value; } public override void Flush() { throw SyncOperationForbiddenException(); } public override Task FlushAsync(CancellationToken cancellationToken) { return _inner.FlushAsync(cancellationToken); } public override int Read(byte[] buffer, int offset, int count) { throw SyncOperationForbiddenException(); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _inner.ReadAsync(buffer, offset, count, cancellationToken); } public override long Seek(long offset, SeekOrigin origin) { return _inner.Seek(offset, origin); } public override void SetLength(long value) { _inner.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { throw SyncOperationForbiddenException(); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _inner.WriteAsync(buffer, offset, count, cancellationToken); } protected override void Dispose(bool disposing) { _inner.Dispose(); } public override ValueTask DisposeAsync() { return _inner.DisposeAsync(); } private Exception SyncOperationForbiddenException() { return new InvalidOperationException("The stream cannot be accessed synchronously"); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Xml.Serialization; namespace SIL.Text { public class MultiTextBase : INotifyPropertyChanged, IComparable { /// <summary> /// We have this pesky "backreference" solely to enable fast /// searching in our current version of db4o (5.5), which /// can find strings fast, but can't be queried for the owner /// quickly, if there is an intervening collection. Since /// each string in WeSay is part of a collection of writing /// system alternatives, that means we can't quickly get /// an answer, for example, to the question Get all /// the Entries that contain a senes which matches the gloss "cat". /// /// Using this field, we can do a query asking for all /// the LanguageForms matching "cat". /// This can all be done in a single, fast query. /// In code, we can then follow the /// LanguageForm._parent up to the MultiTextBase, then this _parent /// up to it's owner, etc., on up the hierarchy to get the Entries. /// /// Subclasses should provide a property which set the proper class. /// /// 23 Jan 07, note: starting to switch to using these for notifying parent of changes, too. /// </summary> /// <summary> /// For INotifyPropertyChanged /// </summary> public event PropertyChangedEventHandler PropertyChanged; private LanguageForm[] _forms; public MultiTextBase() { _forms = new LanguageForm[0]; } public void Add(Object objectFromSerializer) {} public static bool IsEmpty(MultiTextBase mt) { return mt == null || mt.Empty; } public static MultiTextBase Create(Dictionary<string, string> forms) { MultiTextBase m = new MultiTextBase(); CopyForms(forms, m); return m; } protected static void CopyForms(Dictionary<string, string> forms, MultiTextBase m) { if (forms != null && forms.Keys != null) { foreach (string key in forms.Keys) { LanguageForm f = m.Find(key); if (f != null) { f.Form = forms[key]; } else { m.SetAlternative(key, forms[key]); } } } } public bool GetAnnotationOfAlternativeIsStarred(string id) { LanguageForm alt = Find(id); if (alt == null) { return false; } return alt.IsStarred; } public void SetAnnotationOfAlternativeIsStarred(string id, bool isStarred) { LanguageForm alt = Find(id); if (isStarred) { if (alt == null) { AddLanguageForm(new LanguageForm(id, String.Empty, this)); alt = Find(id); Debug.Assert(alt != null); } alt.IsStarred = true; } else { if (alt != null) { if (alt.Form == String.Empty) //non-starred and empty? Nuke it. { RemoveLanguageForm(alt); } else { alt.IsStarred = false; } } else { //nothing to do. Missing altertive == not starred. } } NotifyPropertyChanged(id); } [XmlArrayItem(typeof (LanguageForm), ElementName = "tobedetermined")] public string this[string writingSystemId] { get { return GetExactAlternative(writingSystemId); } set { SetAlternative(writingSystemId, value); } } public LanguageForm Find(string writingSystemId) { foreach (LanguageForm f in Forms) { if (f.WritingSystemId.ToLowerInvariant() == writingSystemId.ToLowerInvariant()) { return f; } } return null; } /// <summary> /// Throws exception if alternative does not exist. /// </summary> /// <param name="writingSystemId"></param> /// <returns></returns> // public string GetExactAlternative(string writingSystemId) // { // if (!Contains(writingSystemId)) // { // throw new ArgumentOutOfRangeException("Use Contains() to first check if the MultiTextBase has a language form for this writing system."); // } // // return GetBestAlternative(writingSystemId, false, null); // } public bool ContainsAlternative(string writingSystemId) { return (Find(writingSystemId) != null); } /// <summary> /// Get exact alternative or String.Empty /// </summary> /// <param name="writingSystemId"></param> /// <returns></returns> public string GetExactAlternative(string writingSystemId) { return GetAlternative(writingSystemId, false, null); } /// <summary> /// Gets the Spans for the exact alternative or null. /// </summary> public List<LanguageForm.FormatSpan> GetExactAlternativeSpans(string writingSystemId) { LanguageForm alt = Find(writingSystemId); if (null == alt) return null; else return alt.Spans; } /// <summary> /// Gives the string of the requested id if it exists, else the 'first'(?) one that does exist, else Empty String /// </summary> /// <returns></returns> public string GetBestAlternative(string writingSystemId) { return GetAlternative(writingSystemId, true, string.Empty); } public string GetBestAlternative(string writingSystemId, string notFirstChoiceSuffix) { return GetAlternative(writingSystemId, true, notFirstChoiceSuffix); } /// <summary> /// Get a string out /// </summary> /// <returns>the string of the requested id if it exists, /// else the 'first'(?) one that does exist + the suffix, /// else the given suffix </returns> private string GetAlternative(string writingSystemId, bool doShowSomethingElseIfMissing, string notFirstChoiceSuffix) { LanguageForm alt = Find(writingSystemId); if (null == alt) { if (doShowSomethingElseIfMissing) { return GetFirstAlternative() + notFirstChoiceSuffix; } else { return string.Empty; } } string form = alt.Form; if (form == null || (form.Trim().Length == 0)) { if (doShowSomethingElseIfMissing) { return GetFirstAlternative() + notFirstChoiceSuffix; } else { return string.Empty; } } else { return form; } } public string GetFirstAlternative() { foreach (LanguageForm form in Forms) { if (form.Form.Trim().Length > 0) { return form.Form; } } return string.Empty; } public string GetBestAlternativeString(IEnumerable<string> orderedListOfWritingSystemIds) { LanguageForm form = GetBestAlternative(orderedListOfWritingSystemIds); if (form == null) return string.Empty; return form.Form; } /// <summary> /// Try to get an alternative according to the ws's given(e.g. the enabled writing systems for a field) /// </summary> /// <param name="orderedListOfWritingSystemIds"></param> /// <returns>May return null!</returns> public LanguageForm GetBestAlternative(IEnumerable<string> orderedListOfWritingSystemIds) { foreach (string id in orderedListOfWritingSystemIds) { LanguageForm alt = Find(id); if (null != alt) return alt; } // //just send back an empty // foreach (string id in orderedListOfWritingSystemIds) // { // return new LanguageForm(id, string.Empty ); // } return null; } public bool Empty { get { return Count == 0; } } public int Count { get { return Forms.Length; } } /// <summary> /// just for deserialization /// </summary> [XmlElement(typeof (LanguageForm), ElementName="form")] public LanguageForm[] Forms { get { if (_forms == null) { throw new ApplicationException("The LanguageForms[] attribute of this entry was null. This is a symptom of a mismatch between a cache and WeSay model. Please delete the cache."); } return _forms; } set { _forms = value; } } public void SetAlternative(string writingSystemId, string form) { Debug.Assert(!string.IsNullOrEmpty(writingSystemId), "The writing system id was empty."); Debug.Assert(writingSystemId.Trim() == writingSystemId, "The writing system id had leading or trailing whitespace"); //enhance: check to see if there has actually been a change LanguageForm alt = Find(writingSystemId); if (string.IsNullOrEmpty(form)) // we don't use space to store empty strings. { if (alt != null && !alt.IsStarred) { RemoveLanguageForm(alt); } } else { if (alt != null) { alt.Form = form; } else { AddLanguageForm(new LanguageForm(writingSystemId, form, this)); } } NotifyPropertyChanged(writingSystemId); } public void RemoveLanguageForm(LanguageForm languageForm) { Debug.Assert(Forms.Length > 0); LanguageForm[] forms = new LanguageForm[Forms.Length - 1]; for (int i = 0, j = 0; i < forms.Length; i++,j++) { if (Forms[j] == languageForm) { j++; } forms[i] = Forms[j]; } _forms = forms; } protected void AddLanguageForm(LanguageForm languageForm) { LanguageForm[] forms = new LanguageForm[Forms.Length + 1]; for (int i = 0; i < Forms.Length; i++) { forms[i] = Forms[i]; } //actually copy the contents, as we must now be the parent forms[Forms.Length] = new LanguageForm(languageForm, this); Array.Sort(forms); _forms = forms; } protected void NotifyPropertyChanged(string writingSystemId) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(writingSystemId)); } } public IEnumerator GetEnumerator() { return Forms.GetEnumerator(); } public int CompareTo(object o) { if(o == null) { return 1; } if (!(o is MultiTextBase)) { throw new ArgumentException("Can not compare to objects other than MultiTextBase."); } MultiTextBase other = (MultiTextBase) o; int formLengthOrder = this.Forms.Length.CompareTo(other.Forms.Length); if(formLengthOrder != 0) { return formLengthOrder; } for(int i = 0; i < Forms.Length; i++) { int languageFormOrder = Forms[i].CompareTo(other.Forms[i]); if(languageFormOrder != 0) { return languageFormOrder; } } return 0; } public override string ToString() { return GetFirstAlternative(); } public LanguageForm[] GetOrderedAndFilteredForms(IEnumerable<string> writingSystemIdsInOrder) { List<LanguageForm> forms = new List<LanguageForm>(); foreach (string id in writingSystemIdsInOrder) { LanguageForm form = Find(id); if(form!=null) { forms.Add(form); } } return forms.ToArray(); } public void MergeInWithAppend(MultiTextBase incoming, string separator) { foreach (LanguageForm form in incoming) { LanguageForm f = Find(form.WritingSystemId); if (f != null) { f.Form += separator + form.Form; } else { AddLanguageForm(form); //this actually copies the meat of the form } } } public void MergeIn(MultiTextBase incoming) { foreach (LanguageForm form in incoming) { LanguageForm f = Find(form.WritingSystemId); if (f != null) { f.Form = form.Form; } else { AddLanguageForm(form); //this actually copies the meat of the form } } } /// <summary> /// Will merge the two mt's if they are compatible; if they collide anywhere, leaves the original untouched /// and returns false /// </summary> /// <param name="incoming"></param> /// <returns></returns> public bool TryMergeIn(MultiTextBase incoming) { //abort if they collide if (!CanBeUnifiedWith(incoming)) return false; MergeIn(incoming); return true; } /// <summary> /// False if they have different forms on any single writing system. If true, they can be safely merged. /// </summary> /// <param name="incoming"></param> /// <returns></returns> public bool CanBeUnifiedWith(MultiTextBase incoming) { foreach (var form in incoming.Forms) { if (!ContainsAlternative(form.WritingSystemId)) continue;//no problem, we don't have one of those if (GetExactAlternative(form.WritingSystemId) != form.Form) return false; } return true; } public override bool Equals(Object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(MultiTextBase)) return false; return Equals((MultiTextBase)obj); } public bool Equals(MultiTextBase other) { if (other == null) return false; if (other.Count != Count) return false; if (!_forms.SequenceEqual(other.Forms)) return false; return true; } public bool HasFormWithSameContent(MultiTextBase other) { if (other.Count == 0 && Count == 0) { return true; } foreach (LanguageForm form in other) { if (ContainsEqualForm(form)) { return true; } } return false; } public bool ContainsEqualForm(LanguageForm other) { foreach (LanguageForm form in Forms) { if (other.Equals(form)) { return true; } } return false; } } }
using System; using System.Collections.Generic; using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Util; namespace Gcm.Client { public class GcmClient { private const string BackoffMs = "backoff_ms"; private const string GsfPackage = "com.google.android.gsf"; private const string Preferences = "com.google.android.gcm"; private const int DefaultBackoffMs = 3000; private const string PropertyRegId = "regId"; private const string PropertyAppVersion = "appVersion"; private const string PropertyOnServer = "onServer"; public static Activity MainActivity; //static GCMBroadcastReceiver sRetryReceiver; public static void CheckDevice(Context context) { var version = (int)Build.VERSION.SdkInt; if(version < 8) { throw new InvalidOperationException("Device must be at least API Level 8 (instead of " + version + ")"); } var packageManager = context.PackageManager; try { packageManager.GetPackageInfo(GsfPackage, 0); } catch { throw new InvalidOperationException("Device does not have package " + GsfPackage); } } public static void CheckManifest(Context context) { var packageManager = context.PackageManager; var packageName = context.PackageName; var permissionName = packageName + ".permission.C2D_MESSAGE"; if(string.IsNullOrEmpty(packageName)) { throw new NotSupportedException("Your Android app must have a package name!"); } if(char.IsUpper(packageName[0])) { throw new NotSupportedException("Your Android app package name MUST start with a lowercase character. Current Package Name: " + packageName); } try { packageManager.GetPermissionInfo(permissionName, PackageInfoFlags.Permissions); } catch { throw new AccessViolationException("Application does not define permission: " + permissionName); } PackageInfo receiversInfo; try { receiversInfo = packageManager.GetPackageInfo(packageName, PackageInfoFlags.Receivers); } catch { throw new InvalidOperationException("Could not get receivers for package " + packageName); } var receivers = receiversInfo.Receivers; if(receivers == null || receivers.Count <= 0) { throw new InvalidOperationException("No Receiver for package " + packageName); } //Logger.Debug("number of receivers for " + packageName + ": " + receivers.Count); var allowedReceivers = new HashSet<string>(); foreach(var receiver in receivers) { if(Constants.PermissionGcmIntents.Equals(receiver.Permission)) { allowedReceivers.Add(receiver.Name); } } if(allowedReceivers.Count <= 0) { throw new InvalidOperationException("No receiver allowed to receive " + Constants.PermissionGcmIntents); } CheckReceiver(context, allowedReceivers, Constants.IntentFromGcmRegistrationCallback); CheckReceiver(context, allowedReceivers, Constants.IntentFromGcmMessage); } private static void CheckReceiver(Context context, HashSet<string> allowedReceivers, string action) { var pm = context.PackageManager; var packageName = context.PackageName; var intent = new Intent(action); intent.SetPackage(packageName); var receivers = pm.QueryBroadcastReceivers(intent, PackageInfoFlags.IntentFilters); if(receivers == null || receivers.Count <= 0) { throw new InvalidOperationException("No receivers for action " + action); } //Logger.Debug("Found " + receivers.Count + " receivers for action " + action); foreach(var receiver in receivers) { var name = receiver.ActivityInfo.Name; if(!allowedReceivers.Contains(name)) { throw new InvalidOperationException("Receiver " + name + " is not set with permission " + Constants.PermissionGcmIntents); } } } public static void Register(Context context, params string[] senderIds) { SetRetryBroadcastReceiver(context); ResetBackoff(context); InternalRegister(context, senderIds); } internal static void InternalRegister(Context context, params string[] senderIds) { if(senderIds == null || senderIds.Length <= 0) { throw new ArgumentException("No senderIds"); } var senders = string.Join(",", senderIds); //Logger.Debug("Registering app " + context.PackageName + " of senders " + senders); var intent = new Intent(Constants.IntentToGcmRegistration); intent.SetPackage(GsfPackage); intent.PutExtra(Constants.ExtraApplicationPendingIntent, PendingIntent.GetBroadcast(context, 0, new Intent(), 0)); intent.PutExtra(Constants.ExtraSender, senders); context.StartService(intent); } public static void UnRegister(Context context) { SetRetryBroadcastReceiver(context); ResetBackoff(context); InternalUnRegister(context); } internal static void InternalUnRegister(Context context) { //Logger.Debug("Unregistering app " + context.PackageName); var intent = new Intent(Constants.IntentToGcmUnregistration); intent.SetPackage(GsfPackage); intent.PutExtra(Constants.ExtraApplicationPendingIntent, PendingIntent.GetBroadcast(context, 0, new Intent(), 0)); context.StartService(intent); } private static void SetRetryBroadcastReceiver(Context context) { //if (sRetryReceiver == null) //{ // sRetryReceiver = new GCMBroadcastReceiver(); // var category = context.PackageName; // var filter = new IntentFilter(GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); // filter.AddCategory(category); // var permission = category + ".permission.C2D_MESSAGE"; // Log.Verbose(TAG, "Registering receiver"); // context.RegisterReceiver(sRetryReceiver, filter, permission, null); //} } public static string GetRegistrationId(Context context) { var prefs = GetGcmPreferences(context); var registrationId = prefs.GetString(PropertyRegId, ""); var oldVersion = prefs.GetInt(PropertyAppVersion, int.MinValue); var newVersion = GetAppVersion(context); if(oldVersion != int.MinValue && oldVersion != newVersion) { //Logger.Debug("App version changed from " + oldVersion + " to " + newVersion + "; resetting registration id"); ClearRegistrationId(context); registrationId = string.Empty; } return registrationId; } public static bool IsRegistered(Context context) { var registrationId = GetRegistrationId(context); return !string.IsNullOrEmpty(registrationId); } internal static string ClearRegistrationId(Context context) { return SetRegistrationId(context, ""); } internal static string SetRegistrationId(Context context, string registrationId) { var prefs = GetGcmPreferences(context); var oldRegistrationId = prefs.GetString(PropertyRegId, ""); var appVersion = GetAppVersion(context); //Logger.Debug("Saving registrationId on app version " + appVersion); var editor = prefs.Edit(); editor.PutString(PropertyRegId, registrationId); editor.PutInt(PropertyAppVersion, appVersion); editor.Commit(); return oldRegistrationId; } public static void SetRegisteredOnServer(Context context, bool flag) { var prefs = GetGcmPreferences(context); // Logger.Debug("Setting registered on server status as: " + flag); var editor = prefs.Edit(); editor.PutBoolean(PropertyOnServer, flag); editor.Commit(); } public static bool IsRegisteredOnServer(Context context) { var prefs = GetGcmPreferences(context); var isRegistered = prefs.GetBoolean(PropertyOnServer, false); // Logger.Debug("Is registered on server: " + isRegistered); return isRegistered; } private static int GetAppVersion(Context context) { try { var packageInfo = context.PackageManager.GetPackageInfo(context.PackageName, 0); return packageInfo.VersionCode; } catch { throw new InvalidOperationException("Could not get package name"); } } internal static void ResetBackoff(Context context) { // Logger.Debug("resetting backoff for " + context.PackageName); SetBackoff(context, DefaultBackoffMs); } internal static int GetBackoff(Context context) { var prefs = GetGcmPreferences(context); return prefs.GetInt(BackoffMs, DefaultBackoffMs); } internal static void SetBackoff(Context context, int backoff) { var prefs = GetGcmPreferences(context); var editor = prefs.Edit(); editor.PutInt(BackoffMs, backoff); editor.Commit(); } private static ISharedPreferences GetGcmPreferences(Context context) { return context.GetSharedPreferences(Preferences, FileCreationMode.Private); } } }
//Copyright 2011 Cloud Sidekick // //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.DirectoryServices; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Globals; using System.Web.Security; using System.Data; using System.IO; using System.Xml.Linq; using System.Xml.XPath; using System.Linq; namespace Web { public partial class login : System.Web.UI.Page { dataAccess dc = new dataAccess(); acUI.acUI ui = new acUI.acUI(); acUI.AppGlobals ag = new acUI.AppGlobals(); string sSQL = ""; string sErr = ""; string sLoginDefaultError = ""; protected void Page_Load(object sender, EventArgs e) { /* * 9/8/2011 NSC * * This used to be in Globax.asax... so the db settings were only loaded once per startup of IIS. * * That was/will cause potential issues with Mono/Apache, so for now we'll just load it here. * * This leaves the possibility the environment.txt file could change and leave two different users in different databases. * * at the very least, we won't load it if it's already in Globals. * */ string sName = Globals.DatabaseSettings.DatabaseName; if (string.IsNullOrEmpty(sName)) { // This may be the first load, or we may have lost the connection string // try to load, and show any error here. if (!dc.InitDatabaseSettings(Server.MapPath("conf/cato.conf"), ref sErr)) { lblErrorMessage.Text = sErr.Replace("\\r\\n", ""); return; } } //If we are here because of a session error, there will be a querystring message. Display it. lblErrorMessage.Text = ui.GetQuerystringValue("msg", typeof(string)).ToString(); //continue ltTitle.Text = ag.APP_NAME; //NSC 8/19/2011 commenting out the postback catch. //Decided we need to fill these values and reset the session, whether it's a post back or not. //visiting the login page resets everything, period. //(there was a random error where the login page would be loaded and sitting in a browser, // and the server reset while it's sitting there. Somehow this ended up with IsPostBack being true, but the session // values were empty. This should fix that. //if (!Page.IsPostBack) //{ //FIRST THINGS FIRST... hitting the login page resets the session. HttpContext.Current.Session.Clear(); //now, for some reason we were having issues with the initial startup of apache //not able to perform the very first database hit. //this line serves as an inital db hit, but we aren't trapping it dc.TestDBConnection(ref sErr); if(sErr != "") Response.Write("<!--DATABASE TEST FAILED: " + sErr + "-->"); //load the site.master.xml file into the session. If it doesn't exist, we can't proceed. try { XDocument xSiteMaster = XDocument.Load(HttpContext.Current.Server.MapPath("~/pages/site.master.xml")); if (xSiteMaster == null) { lblErrorMessage.Text = "Error: Site master XML file is missing or unreadable."; btnLogin.Visible = false; } else { ui.SetSessionObject("site_master_xml", xSiteMaster, "Security"); } } catch (Exception ex) { lblErrorMessage.Text = "Error: ite master XML is invalid." + ex.Message; } //load the cloud_providers.xml file into the session. If it doesn't exist, we can't proceed. try { XDocument xProviders = XDocument.Load(HttpContext.Current.Server.MapPath("~/conf/cloud_providers.xml")); if (xProviders == null) { lblErrorMessage.Text = "Error: Cloud Providers XML file is missing or unreadable."; } else { CloudProviders cp = new CloudProviders(xProviders); ui.SetSessionObject("cloud_providers", cp, "Security"); } } catch (Exception ex) { lblErrorMessage.Text = "Error: Unable to load Cloud Providers XML." + ex.Message; } //get the login settings sSQL = "select login_message, page_view_logging, report_view_logging, log_days" + " from login_security_settings where id = 1"; DataRow dr = null; if (!dc.sqlGetDataRow(ref dr, sSQL, ref sErr)) { lblErrorMessage.Text = "Error: Unable to connect to the database.<br /><br />" + sErr; return; } if (dr != null) { //login message string sLoginMessage = object.ReferenceEquals(dr["login_message"], DBNull.Value) ? "Welcome to Cato" : dr["login_message"].ToString(); lblMessage.Text = sLoginMessage; //put it in the global DatabaseSettings.AppInstance = sLoginMessage; //page view settings //global_view_logging if (dc.IsTrue(dr["page_view_logging"].ToString())) ui.SetSessionObject("page_view_logging", "true", "Security"); else ui.SetSessionObject("page_view_logging", "false", "Security"); //user page_view logging if (dc.IsTrue(dr["report_view_logging"].ToString())) ui.SetSessionObject("report_view_logging", "true", "Security"); else ui.SetSessionObject("report_view_logging", "false", "Security"); //log depth if (!string.IsNullOrEmpty(dr["log_days"].ToString())) ui.SetSessionObject("log_days", dr["log_days"].ToString(), "Security"); else ui.SetSessionObject("log_days", "90", "Security"); } else { //this should never happen, if it does we weren't able to connect to the db but didn't have an error above? lblErrorMessage.Text = "Warning: Unable to read the login settings table."; } //} } private bool LdapAuthenticate(string sUserID, string sDomain, string sUsername, string sPassword, ref string sErr) { // using the sDomain string get the server address from the ldap_server setting string sLdapServerAddress = ""; string sSQL = ""; sSQL = "select address from ldap_domain where ldap_domain = '" + sDomain + "'"; if (!dc.sqlGetSingleString(ref sLdapServerAddress, sSQL, ref sErr)) { sErr = "Error:" + sErr; return false; } if (string.IsNullOrEmpty(sLdapServerAddress)) { sErr = "No server address for domain:" + sDomain; return false; } // verify the user using ldap DirectoryEntry entry = new DirectoryEntry("LDAP://" + sLdapServerAddress, sDomain + "\\" + sUsername, sPassword); try { //object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + sUsername + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if ((result == null)) { sErr = "User " + sUsername + " not found in domain " + sDomain; dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Ldap Error:LDAP://" + sLdapServerAddress + "//" + sDomain + "//" + sUsername + " user not found.", ref sErr); return false; } } catch (Exception ex) { dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Ldap Error:LDAP://" + sLdapServerAddress + "//" + sDomain + "//" + sUsername + " " + ex.Message.ToString(), ref sErr); // use the default message instead of the one returned from the ad inquiry. sErr = sLoginDefaultError; return false; } return true; } private void LoginComplete(string sUserID, string sUserName, ref string sErr) { string sClientIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(sClientIPAddress)) sClientIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; sSQL = "update users set failed_login_attempts=0, last_login_dt=now() where user_id='" + sUserID + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLogin, acObjectTypes.None, "", "Login from [" + sClientIPAddress + "] granted.", ref sErr); //put a crap load of static stuff in the session so we can use the values later without hitting the database a lot. //***SECURITY COLLECTION sSQL = "select full_name, user_role, email, last_login_dt from users where user_id = '" + sUserID + "'"; DataRow dr = null; if (!dc.sqlGetDataRow(ref dr, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (dr != null) { string sRole = dr["user_role"].ToString(); //like the user_id ui.SetSessionObject("user_id", sUserID, "Security"); //when we're ready to stop using the session, a global has proven to work. //CurrentUser.UserID = sUserID; //the role ui.SetSessionObject("user_role", sRole, "Security"); //the full name ui.SetSessionObject("user_full_name", dr["full_name"], "Security"); //the user name ui.SetSessionObject("user_name", sUserName, "Security"); //the IP address ui.SetSessionObject("ip_address", sClientIPAddress, "Security"); //last login ui.SetSessionObject("last_login", dr["last_login_dt"], "Security"); //email ui.SetSessionObject("user_email", dr["email"], "Security"); // user groups sSQL = "select tag_name from object_tags where object_type = 1 and object_id = '" + sUserID + "'"; string sUserTags = null; if (!dc.GetDelimitedData(ref sUserTags, sSQL, ",", ref sErr, false, false)) { lblErrorMessage.Text = sErr; return; } else { ui.SetSessionObject("user_tags", sUserTags, "Security"); } // admin emails for error reporting sSQL = "select admin_email from messenger_settings where id = 1"; string sAdminEmail = null; if (!dc.sqlGetSingleString(ref sAdminEmail, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } else { ui.SetSessionObject("admin_email", sAdminEmail, "Security"); } // CLOUD ACCOUNTS (data table) if (!ui.PutCloudAccountsInSession(ref sErr)) { lblErrorMessage.Text = sErr; return; } // allowed pages list (from the session) XDocument xSiteMaster = (XDocument)ui.GetSessionObject("site_master_xml", "Security"); if (xSiteMaster == null) { lblErrorMessage.Text = "Error: Site master XML is not in the session."; } else { string sAllowedPages = ""; foreach (XElement xPage in xSiteMaster.XPathSelectElements("//roles/" + sRole + "/allowedpages/page")) { sAllowedPages += xPage.Value.ToString().ToLower() + ","; } ui.SetSessionObject("allowed_pages", sAllowedPages, "Security"); } } else { lblErrorMessage.Text = "Error: Could not determine Name for this login. Unable to continue."; return; } //***END SECURITY COLLECTION //***GENERAL COLLECTION //these are settings we use in the gui //sSql = "select count(*) from resource_crit_group" //SetSessionObject("crit_group_count", dc.sqlGetSingleInteger(sSql, sErr), "General") //***END GENERAL COLLECTION // last step before authenticationg, update the user_session table if (!dc.sqlExecuteUpdate("delete from user_session where user_id = '" + sUserID + "';", ref sErr)) { lblErrorMessage.Text = sErr; return; } if (!dc.sqlExecuteUpdate("insert into user_session" + " (user_id, address, login_dt, heartbeat, kick)" + " values ('" + sUserID + "','" + sClientIPAddress + "', now(), now(), 0)", ref sErr)) { lblErrorMessage.Text = sErr; return; } //The GUI does it's own security log table maintenance string sLogDays = (string)ui.GetSessionObject("log_days", "Security"); if (string.IsNullOrEmpty(sLogDays)) sLogDays = "90"; if (!dc.sqlExecuteUpdate("delete from user_security_log" + " where log_dt < date_sub(now(), INTERVAL " + sLogDays + " DAY)", ref sErr)) { lblErrorMessage.Text = sErr; return; } // setup the forms authentication FormsAuthenticationTicket oTicket = new FormsAuthenticationTicket(1, sUserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, "member"); HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(oTicket))); HttpContext.Current.Response.Redirect("~/pages/home.aspx", false); } private void LoadPasswordRecovery() { string sAuthenticationType = ""; //string sEmail = ""; string sQuestion = ""; //string sAnswer = ""; pnlForgotPassword.Visible = true; //lblSecurityQuestion // // 1) make sure the user is valid sSQL = "select authentication_type,user_id, security_question,security_answer,email " + "from users where username = '" + txtLoginUser.Text.Replace("'", "''") + "'"; DataRow dr = null; if (!dc.sqlGetDataRow(ref dr, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } else { if (dr != null) { sAuthenticationType = (object.ReferenceEquals(dr["authentication_type"], DBNull.Value) ? "" : dr["authentication_type"].ToString()); //sEmail = (object.ReferenceEquals(dr["email"], DBNull.Value) ? "" : dr["email"].ToString()); sQuestion = (object.ReferenceEquals(dr["security_question"], DBNull.Value) ? "" : dc.DeCrypt(dr["security_question"].ToString())); //sAnswer = (object.ReferenceEquals(dr["security_answer"], DBNull.Value) ? "" : dr["security_answer"].ToString()); } else { // username invalid HttpContext.Current.Response.Redirect("login.aspx", false); return; } } // if we made it here we should have valid user info // 2) if the user is authentication_type = ldap // then give a message that the user can't change their password // in the system, contact the admin if (sAuthenticationType == "ldap") { HttpContext.Current.Response.Redirect("login.aspx?msg=LDAP/Active+Directory+users+can+not+change+their+passwords+in+this+system,+Please+contact+your+system+administrator.", false); return; } // 3) if the user is local and has a secruity q/a then prompt for that // and the new password. if (sQuestion != "") { lblSecurityQuestion.Text = sQuestion; lblRecoverMessage.Text = "To reset your password, enter the correct security answer and a new password."; pnlPasswordReset.Visible = true; return; } // no saved question pnlPasswordReset.Visible = false; lblRecoverMessage.Text = "No Security Question on file. Please contact your System Administrator to change your password."; pnlNoQaOnFile.Visible = true; // foregoing option 4 for now, after looking in 3.5.1 it did not exist there, (emailing a new password) } protected void ForgotPassword_Click(object sender, EventArgs e) { lblErrorMessage.Text = ""; // make sure we have a username to query with if (txtLoginUser.Text.Length == 0) { lblErrorMessage.Text = "Enter a valid user for password recovery."; } else { lblRecoverUserName.Text = txtLoginUser.Text; //hide and show the necessary panels pnlLogin.Visible = false; LoadPasswordRecovery(); } } protected void AttemptLogin() { string sUserID = null; string sUsername = txtLoginUser.Text.Replace("'", "''"); sUsername = sUsername.Replace(";", ""); lblErrorMessage.Text = ""; //first before anything, if the system is flagged as 'down', only "administrators" can log in. string sRole = ""; sSQL = "select user_role from users where username = '" + sUsername + "'"; if (!dc.sqlGetSingleString(ref sRole, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (sRole != "Administrator") { int iAllow = 0; sSQL = "select allow_login from login_security_settings limit 1"; if (!dc.sqlGetSingleInteger(ref iAllow, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (iAllow == 0) { //not an administrator and the system isn't allowing login... too bad :-( lblErrorMessage.Text = "The system is in maintenance mode and not accepting users at this time."; return; } } // get the default message for login errors sSQL = "select auth_error_message from login_security_settings"; sLoginDefaultError = "Invalid User or Password."; if (!dc.sqlGetSingleString(ref sLoginDefaultError, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } // see if this user is an ldap or local login type string sUserAuthType = ""; sSQL = "select authentication_type from users where username = '" + sUsername + "'"; if (!dc.sqlGetSingleString(ref sUserAuthType, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (string.IsNullOrEmpty(sUserAuthType)) { lblErrorMessage.Text = "Invalid User Name or Password."; return; } if (sUserAuthType == "local") { //get all of the values from the login_security_settings table DataTable dtLoginSecurity = new DataTable(); sSQL = "Select * from login_security_settings where id = 1"; if (!dc.sqlGetDataTable(ref dtLoginSecurity, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } else { // the security settings are required, if no row exists give an error if (dtLoginSecurity.Rows.Count == 0) { dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "System Setup error:no security setting row exists in the login_security_settings table.", ref sErr); lblErrorMessage.Text = "System setup error - no security settings. Contact a System Adminstrator."; return; } } //string sDecryptedPassword = null; string sEncryptedPassword = null; string sForceChange = null; sSQL = "select user_id, status, failed_login_attempts, user_password, expiration_dt,force_change" + " from users where username='" + sUsername + "'"; DataRow dr = null; if (!dc.sqlGetDataRow(ref dr, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (dr != null) { sUserID = dr["user_id"].ToString(); int iStatus = 0; int iFailedLogins = 0; iStatus = (int)dr["status"]; sForceChange = (string.IsNullOrEmpty(dr["force_change"].ToString()) ? "0" : dr["force_change"].ToString()); if ((iStatus != 1)) { lblErrorMessage.Text = "Your user account has been locked."; dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login denied - locked user account.", ref sErr); return; } if (!string.IsNullOrEmpty(dr["failed_login_attempts"].ToString())) { iFailedLogins = (int)dr["failed_login_attempts"]; } if (string.IsNullOrEmpty(dr["user_password"].ToString())) { int iHistoryCount = 0; if (!dc.sqlGetSingleInteger(ref iHistoryCount, "select count(*) from user_password_history where user_id = '" + sUserID + "'", ref sErr)) { lblErrorMessage.Text = sErr; return; } if (iHistoryCount > 0) { // Intentionally cryptic message because if the users password is NULL and the user has previous passwords // then the account has probably been hacked and the user is not allowed to login dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login denied - password is null but history shows previous passwords. The password should never be NULL.", ref sErr); lblErrorMessage.Text = sLoginDefaultError; } } else { //sDecryptedPassword = dc.DeCrypt(dr["user_password"].ToString()); sEncryptedPassword = dr["user_password"].ToString(); } if (!string.IsNullOrEmpty(dr["expiration_dt"].ToString())) { System.DateTime dtExpiration = (System.DateTime)dr["expiration_dt"]; if (dtExpiration < DateTime.Now) { sSQL = "update users set last_login_dt=now(), status=0 where user_id = '" + sUserID + "'"; dc.sqlExecuteUpdate(sSQL, ref sErr); dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login denied - account is expired.", ref sErr); lblErrorMessage.Text = "Your user account has expired."; return; } } // get the failed_login_attempts value from the centivia parameters string sMaxLoginAttemps = dtLoginSecurity.Rows[0]["pass_max_attempts"].ToString(); int iMaxLoginAttempts = Convert.ToInt32(sMaxLoginAttemps); if (iMaxLoginAttempts == 0) { lblErrorMessage.Text = "Error: System setting for max password attemtps is not set. Contact a System Administrator."; return; } if (iFailedLogins > iMaxLoginAttempts) { // Based on the security parameter "Password Policy automatic_lock_reset" (# of minutes) // reset the failed_login_attempts for this user, else lock them string sAutoResetLock = dtLoginSecurity.Rows[0]["auto_lock_reset"].ToString(); int iAutoResetLock = 0; if (int.TryParse(sAutoResetLock, out iAutoResetLock)) { sSQL = "select ((DATEDIFF(log_dt, now()) * 24) * 60) AS minutes " + "from user_security_log " + "where user_id = '" + sUserID + "' " + "and log_msg = 'Login denied - auto reset start message.' " + "order by log_id desc limit 1"; int iLastFail = 0; if (!dc.sqlGetSingleInteger(ref iLastFail, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (iLastFail > iAutoResetLock) { sSQL = "update users set failed_login_attempts = 0" + " where user_id = '" + sUserID + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } iFailedLogins = 0; dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login attempt - failed attempts counter automatically reset per timeout.", ref sErr); // have to remove the start message, so the whole thing starts over the next time sSQL = "delete from user_security_log where user_id = '" + sUserID + "' and log_msg = 'Login denied - auto reset start message.'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } } else { int iMinutesRemaining = iAutoResetLock - iLastFail; dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login denied - account is disabled. Minutes remaining till auto reset:" + iMinutesRemaining, ref sErr); // check to see if a counter message exists for this user, // if not create one. string sExists = null; sSQL = "select log_msg " + "from user_security_log " + "where user_id = '" + sUserID + "' " + "and log_msg = 'Login denied - auto reset start message.' " + "order by log_id desc"; if (!dc.sqlGetSingleString(ref sExists, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (string.IsNullOrEmpty(sExists)) { dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login denied - auto reset start message.", ref sErr); } lblErrorMessage.Text = "Your user account has been disabled due to numerous failed login attempts."; return; } } else { dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login denied - account is disabled due to numerous failed login attempts.", ref sErr); lblErrorMessage.Text = "Your user account has been disabled due to numerous failed login attempts."; return; } } else { //what happens if it wasn't a numberic? } string sTestPasswordString = null; if (hidUpdateLater.Value == "later") { sTestPasswordString = hidID.Value; } else { sTestPasswordString = dc.EnCrypt(txtLoginPassword.Text); } if (sEncryptedPassword != sTestPasswordString) { sSQL = "update users set failed_login_attempts=" + (iFailedLogins + 1).ToString() + ", last_login_dt=now() where user_id='" + sUserID + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } lblErrorMessage.Text = sLoginDefaultError; dc.addSecurityLog(sUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login denied - incorrect password.", ref sErr); return; } // bugzilla 1194 check the password aging. // compare the last password update to the value pass_max_age // in login_security_settings if the user needs to change their password prompt here. // this requires to checks, first if the password has expired give a message that // the password must be changed. // if the password expires within the pass_age_warn_days // then give an option to change the password or to change it later. string sMaxPassMaxAge = dtLoginSecurity.Rows[0]["pass_max_age"].ToString(); string sPassWarnDays = dtLoginSecurity.Rows[0]["pass_age_warn_days"].ToString(); // get the users last password update date. string sLastPasswordUpdate = null; sSQL = "select change_time from user_password_history where user_id = '" + sUserID + "' order by change_time desc limit 1"; if (!dc.sqlGetSingleString(ref sLastPasswordUpdate, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (string.IsNullOrEmpty(sLastPasswordUpdate)) { // no history exists for this user, so what should we do? //right now we just allow login, since a new user wouldn't have history anyway. //there was discussion about setting sForceChange = "1", but since //creating a new user emails out a random password and set the force_change flag anyway } else { // how many days old is the password System.DateTime dtPasswordAge = Convert.ToDateTime(sLastPasswordUpdate); //string sWarn = DateTime.Now.AddDays(Convert.ToDouble("-" + sMaxPassMaxAge)).ToString(); DateTime dtPasswordAgePlus = dtPasswordAge.AddDays(Convert.ToDouble(sMaxPassMaxAge)); // if password has expired and must be changed if (dtPasswordAgePlus < DateTime.Now) { lblUserName.Text = sUsername; pnlLogin.Visible = false; pnlForgotPassword.Visible = false; pnlResetPassword.Visible = true; lblResetMessage.Text = "You password has expired and must be changed."; return; } else { // if password expiration date is within the warn days. if (dtPasswordAgePlus < DateTime.Now.AddDays(Convert.ToDouble(sPassWarnDays))) { // if the user selected update later then continue if (hidUpdateLater.Value != "later") { TimeSpan ts = DateTime.Now.AddDays(Convert.ToDouble(sPassWarnDays)) - dtPasswordAgePlus; lblWarnUsername.Text = sUsername; pnlLogin.Visible = false; pnlForgotPassword.Visible = false; pnlResetPassword.Visible = false; pnlExpireWarning.Visible = true; hidID.Value = sTestPasswordString; lblExpireWarning.Text = "Your password expires in " + ts.Days.ToString() + " days."; return; } else { txtLoginPassword.Text = dc.DeCrypt(hidID.Value); } } } } // Bugzilla 830, once all validation is done, do a check for password complexity // to make sure the users password meets the rules in the current setting. string sMessage = ""; try { bool bComplex = dc.PasswordIsComplex(txtLoginPassword.Text.Replace("'", "''"), ref sMessage); if (!bComplex) { lblUserName.Text = sUsername; pnlLogin.Visible = false; pnlForgotPassword.Visible = false; pnlResetPassword.Visible = true; lblResetMessage.Text = "You must change your password.<br />" + sMessage; return; } } catch (Exception ex) { lblErrorMessage.Text = ex.Message; } // if the force_change is set, show the password change screen try { if (sForceChange == "1") { lblUserName.Text = sUsername; pnlLogin.Visible = false; pnlForgotPassword.Visible = false; pnlResetPassword.Visible = true; lblResetMessage.Text = "You must change your password.<br />" + sMessage; return; } } catch (Exception ex) { lblErrorMessage.Text = ex.Message; } //if we got here then we are successful. Yaaayyyy! LoginComplete(sUserID, sUsername, ref sErr); } else { //cryptic message so they won't know the attempted name is not a valid username. lblErrorMessage.Text = sLoginDefaultError; //addSecurityLog(iUserID, SecurityLogTypes.Security, SecurityLogActions.UserLoginAttempt, acObjectTypes.None, "", "Login attempt - username [" & sUserName & "] not found.") return; } } else if (sUserAuthType == "ldap") { string[] aUser = sUsername.Split('\\'); if (aUser.Length == 2) { sSQL = "select user_id from users where username='" + sUsername + "'"; if (!dc.sqlGetSingleString(ref sUserID, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (!LdapAuthenticate(sUserID, aUser[0].ToString(), aUser[1].ToString(), txtLoginPassword.Text, ref sErr)) { lblErrorMessage.Text = sErr; return; } else { LoginComplete(sUserID, aUser[1].ToString(), ref sErr); } } else { lblErrorMessage.Text = "Error: Unable to locate domain."; return; } } else { lblErrorMessage.Text = "Authentication method not defined."; return; } } protected void UpdatePassword(string sCurrentPassword, string sNewPassword, string sNewPasswordConfirm) { // make sure the new password is actually new. // make sure the user entered their existing password. if (sCurrentPassword == sNewPassword) { lblErrorMessage.Text = "New password must be different than the current password."; return; } // make sure the user entered their existing password. if (sCurrentPassword.Length == 0) { lblMessage.Text = "Enter the current password."; return; } // do the new passwords match if (sNewPassword != sNewPasswordConfirm) { lblErrorMessage.Text = "New Passwords do not match."; return; } // is the new password complex enough try { string sMessage = ""; bool bComplex = dc.PasswordIsComplex(sNewPassword, ref sMessage); if (!bComplex) { lblErrorMessage.Text = sMessage; return; } } catch (Exception ex) { lblErrorMessage.Text = ex.Message; } // make sure the username and password are correct, then update the users password and log them in. sSQL = "select user_id, status, failed_login_attempts, user_password, expiration_dt" + " from users where username='" + txtLoginUser.Text.Replace("'", "''").Replace(";", "") + "'"; DataRow dr = null; if (!dc.sqlGetDataRow(ref dr, sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } if (dr != null) { // bugzilla 1347 // check the user password history setting, and make sure the password was not used in the past x passwords if (dc.PasswordInHistory(dc.EnCrypt(sNewPassword), dr["user_id"].ToString(), ref sErr)) { lblErrorMessage.Text = "Passwords can not be reused. Please choose another password."; return; }; if (sErr != "") { lblErrorMessage.Text = sErr; return; }; string sDecryptedPassword = dc.DeCrypt(dr["user_password"].ToString()); if (sCurrentPassword == sDecryptedPassword) { sSQL = "update users set user_password = '" + dc.EnCrypt(sNewPassword) + "', force_change = 0 where user_id = '" + dr["user_id"].ToString() + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } else { // add Password history if it changed sSQL = "insert user_password_history (user_id, change_time,password) values ('" + dr["user_id"].ToString() + "',now(),'" + dc.EnCrypt(sNewPassword) + "')"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { lblErrorMessage.Text = sErr; return; } else { HttpContext.Current.Response.Redirect("login.aspx?msg=Password+updated,+you+may+now+log+in+with+the+new+password.", false); return; } } } else { lblErrorMessage.Text = "Invalid current password."; return; } } } #region "Buttons" protected void btnLogin_Click(object sender, System.EventArgs e) { AttemptLogin(); } protected void btnUpdatePassword_Click(object sender, EventArgs e) { UpdatePassword(txtCurrentPassword.Text, txtNewPassword.Text, txtNewPasswordConfirm.Text); } protected void btnResetPassword_Click(object sender, EventArgs e) { // this is the function that runs if a user has a q/a saved. // and they hit save password. lblRecoverMessage.Text = ""; // make sure the new password exists if (txtResetPassword.Text.Length == 0) { lblRecoverMessage.Text = "Please enter a password."; return; } // make sure the new passwords match if (txtResetPassword.Text != txtResetPasswordConfirm.Text) { lblRecoverMessage.Text = "Passwords do not match."; return; } // make sure the answer given matches the answer saved string sSecurityAnswer = ""; sSQL = "Select security_answer from users where username = '" + txtLoginUser.Text.Replace("'", "''").Replace(";", "") + "'"; if (!dc.sqlGetSingleString(ref sSecurityAnswer, sSQL, ref sErr)) { lblRecoverMessage.Text = sErr; } else { sSecurityAnswer = dc.DeCrypt(sSecurityAnswer); try { if (sSecurityAnswer == txtSecurityAnswer.Text) { // all good so far, check the password complexity, and save, and redirect to the login. if (!dc.PasswordIsComplex(txtResetPassword.Text, ref sErr)) { lblRecoverMessage.Text = sErr; return; } else { // update the users password and redirect to the login page. sSQL = "update users set user_password = '" + dc.EnCrypt(txtResetPassword.Text) + "' where username = '" + txtLoginUser.Text.Replace("'", "''").Replace(";", "") + "'"; if (!dc.sqlExecuteUpdate(sSQL, ref sErr)) { lblRecoverMessage.Text = sErr; return; } else { // we have to have the user_id to log this, if its not a valid user_id then we can't log it, seems like we need to log // all attempts, but there is a foreign key on user_id in the user_security_log table string sAttemptUserID = null; dc.sqlGetSingleString(ref sAttemptUserID, "Select user_id from users where username = '" + txtLoginUser.Text.Replace("'", "''").Replace(";", "") + "'", ref sErr); if (!string.IsNullOrEmpty(sAttemptUserID)) { dc.addSecurityLog(sAttemptUserID, SecurityLogTypes.Security, SecurityLogActions.UserPasswordChange, acObjectTypes.User, txtLoginUser.Text.Replace("'", "''").Replace(";", ""), "user changed password using the forgot password function.", ref sErr); } HttpContext.Current.Response.Redirect("login.aspx?msg=Password+updated,+you+may+now+log+in+with+the+new+password.", false); return; } } } else { // we have to have the user_id to log this, if its not a valid user_id then we can't log it, seems like we need to log // all attempts, but there is a foreign key on user_id in the user_security_log table string sAttemptUserID = null; dc.sqlGetSingleString(ref sAttemptUserID, "select user_id from users where username = '" + txtLoginUser.Text.Replace("'", "''").Replace(";", "") + "'", ref sErr); if (!string.IsNullOrEmpty(sAttemptUserID)) { dc.addSecurityLog(sAttemptUserID, SecurityLogTypes.Security, SecurityLogActions.UserPasswordChange, acObjectTypes.User, txtLoginUser.Text.Replace("'", "''").Replace(";", ""), "Forgot password attempt, incorrect answer given.", ref sErr); } lblRecoverMessage.Text = "Incorrect Answer."; } } catch (Exception ex) { lblErrorMessage.Text = ex.Message; } } } protected void btnCancelPasswordReset_Click(object sender, EventArgs e) { HttpContext.Current.Response.Redirect("login.aspx", false); } protected void btnExpiredPassword_Click(object sender, EventArgs e) { UpdatePassword(txtWarningCurrentPassword.Text, txtWarningNewPassword.Text, txtWarningNewPasswordConfirm.Text); } protected void btnUpdateLater_Click(object sender, EventArgs e) { hidUpdateLater.Value = "later"; txtLoginPassword.Text = txtCurrentPassword.Text; //string sTest = txtWarningCurrentPassword.Text; AttemptLogin(); } #endregion } }
#region Changes /* Changed by Miha Strehar in 2016: x.Key.IsInterface to x.Key.GetTypeInfo().IsInterface added using Sysrem.Reflection; */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using DotLiquidCore.FileSystems; using DotLiquidCore.Util; using DotLiquidCore.NamingConventions; using System.Reflection; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member #pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) namespace DotLiquidCore { /// <summary> /// Templates are central to liquid. /// Interpreting templates is a two step process. First you compile the /// source code you got. During compile time some extensive error checking is performed. /// your code should expect to get some SyntaxErrors. /// /// After you have a compiled template you can then <tt>render</tt> it. /// You can use a compiled template over and over again and keep it cached. /// /// Example: /// /// template = Liquid::Template.parse(source) /// template.render('user_name' => 'bob') /// </summary> public class Template { public static INamingConvention NamingConvention; public static IFileSystem FileSystem { get; set; } private static Dictionary<string, Type> Tags { get; set; } private static readonly Dictionary<Type, Func<object, object>> SafeTypeTransformers; private static readonly Dictionary<Type, Func<object, object>> ValueTypeTransformers; static Template() { NamingConvention = new RubyNamingConvention(); FileSystem = new BlankFileSystem(); Tags = new Dictionary<string, Type>(); SafeTypeTransformers = new Dictionary<Type, Func<object, object>>(); ValueTypeTransformers = new Dictionary<Type, Func<object, object>>(); } public static void RegisterTag<T>(string name) where T : Tag, new() { Tags[name] = typeof(T); } public static Type GetTagType(string name) { Type result; Tags.TryGetValue(name, out result); return result; } /// <summary> /// Pass a module with filter methods which should be available /// to all liquid views. Good for registering the standard library /// </summary> /// <param name="filter"></param> public static void RegisterFilter(Type filter) { Strainer.GlobalFilter(filter); } /// <summary> /// Registers a simple type. DotLiquidCore will wrap the object in a <see cref="DropProxy"/> object. /// </summary> /// <param name="type">The type to register</param> /// <param name="allowedMembers">An array of property and method names that are allowed to be called on the object.</param> public static void RegisterSafeType(Type type, string[] allowedMembers) { RegisterSafeType(type, x => new DropProxy(x, allowedMembers)); } /// <summary> /// Registers a simple type. DotLiquidCore will wrap the object in a <see cref="DropProxy"/> object. /// </summary> /// <param name="type">The type to register</param> /// <param name="allowedMembers">An array of property and method names that are allowed to be called on the object.</param> public static void RegisterSafeType(Type type, string[] allowedMembers, Func<object, object> func) { RegisterSafeType(type, x => new DropProxy(x, allowedMembers, func)); } /// <summary> /// Registers a simple type using the specified transformer. /// </summary> /// <param name="type">The type to register</param> /// <param name="func">Function that converts the specified type into a Liquid Drop-compatible object (eg, implements ILiquidizable)</param> public static void RegisterSafeType(Type type, Func<object, object> func) { SafeTypeTransformers[type] = func; } /// <summary> /// Registers a simple value type transformer. Used for rendering a variable to the output stream /// </summary> /// <param name="type">The type to register</param> /// <param name="func">Function that converts the specified type into a Liquid Drop-compatible object (eg, implements ILiquidizable)</param> public static void RegisterValueTypeTransformer(Type type, Func<object, object> func) { ValueTypeTransformers[type] = func; } public static Func<object, object> GetValueTypeTransformer(Type type) { // Check for concrete types if (ValueTypeTransformers.ContainsKey(type)) return ValueTypeTransformers[type]; // Check for interfaces foreach (var interfaceType in ValueTypeTransformers.Where(x => x.Key.GetTypeInfo().IsInterface)) { if (type.GetInterfaces().Contains(interfaceType.Key)) return interfaceType.Value; } return null; } public static Func<object, object> GetSafeTypeTransformer(Type type) { // Check for concrete types if (SafeTypeTransformers.ContainsKey(type)) return SafeTypeTransformers[type]; // Check for interfaces foreach (var interfaceType in SafeTypeTransformers.Where(x => x.Key.GetTypeInfo().IsInterface)) { if (type.GetInterfaces().Contains(interfaceType.Key)) return interfaceType.Value; } return null; } /// <summary> /// Creates a new <tt>Template</tt> object from liquid source code /// </summary> /// <param name="source"></param> /// <returns></returns> public static Template Parse(string source) { Template template = new Template(); template.ParseInternal(source); return template; } private Hash _registers, _assigns, _instanceAssigns; private List<Exception> _errors; public Document Root { get; set; } public Hash Registers { get { return (_registers = _registers ?? new Hash()); } } public Hash Assigns { get { return (_assigns = _assigns ?? new Hash()); } } public Hash InstanceAssigns { get { return (_instanceAssigns = _instanceAssigns ?? new Hash()); } } public List<Exception> Errors { get { return (_errors = _errors ?? new List<Exception>()); } } /// <summary> /// Creates a new <tt>Template</tt> from an array of tokens. Use <tt>Template.parse</tt> instead /// </summary> internal Template() { } /// <summary> /// Parse source code. /// Returns self for easy chaining /// </summary> /// <param name="source"></param> /// <returns></returns> internal Template ParseInternal(string source) { source = DotLiquidCore.Tags.Literal.FromShortHand(source); source = DotLiquidCore.Tags.Comment.FromShortHand(source); Root = new Document(); Root.Initialize(null, null, Tokenize(source)); return this; } /// <summary> /// Renders the template using default parameters and returns a string containing the result. /// </summary> /// <returns></returns> public string Render() { return Render(new RenderParameters()); } /// <summary> /// Renders the template using the specified local variables and returns a string containing the result. /// </summary> /// <param name="localVariables"></param> /// <returns></returns> public string Render(Hash localVariables) { return Render(new RenderParameters { LocalVariables = localVariables }); } /// <summary> /// Renders the template using the specified parameters and returns a string containing the result. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public string Render(RenderParameters parameters) { using (TextWriter writer = new StringWriter()) { Render(writer, parameters); return writer.ToString(); } } /// <summary> /// Renders the template into the specified StreamWriter. /// </summary> /// <param name="result"></param> /// <param name="parameters"></param> public void Render(TextWriter result, RenderParameters parameters) { RenderInternal(result, parameters); } /// <summary> /// Renders the template into the specified Stream. /// </summary> /// <param name="stream"></param> /// <param name="parameters"></param> public void Render(Stream stream, RenderParameters parameters) { // Can't dispose this new StreamWriter, because it would close the // passed-in stream, which isn't up to us. StreamWriter streamWriter = new StreamWriter(stream); RenderInternal(streamWriter, parameters); streamWriter.Flush(); } /// <summary> /// Render takes a hash with local variables. /// /// if you use the same filters over and over again consider registering them globally /// with <tt>Template.register_filter</tt> /// /// Following options can be passed: /// /// * <tt>filters</tt> : array with local filters /// * <tt>registers</tt> : hash with register variables. Those can be accessed from /// filters and tags and might be useful to integrate liquid more with its host application /// </summary> private void RenderInternal(TextWriter result, RenderParameters parameters) { if (Root == null) return; Context context; Hash registers; IEnumerable<Type> filters; parameters.Evaluate(this, out context, out registers, out filters); if (registers != null) Registers.Merge(registers); if (filters != null) context.AddFilters(filters); try { // Render the nodelist. Root.Render(context, result); } finally { _errors = context.Errors; } } /// <summary> /// Uses the <tt>Liquid::TemplateParser</tt> regexp to tokenize the passed source /// </summary> /// <param name="source"></param> /// <returns></returns> internal static List<string> Tokenize(string source) { if (string.IsNullOrEmpty(source)) return new List<string>(); // Trim leading whitespace. source = Regex.Replace(source, string.Format(@"([ \t]+)?({0}|{1})-", Liquid.VariableStart, Liquid.TagStart), "$2"); // Trim trailing whitespace. source = Regex.Replace(source, string.Format(@"-({0}|{1})(\n|\r\n|[ \t]+)?", Liquid.VariableEnd, Liquid.TagEnd), "$1"); List<string> tokens = Regex.Split(source, Liquid.TemplateParser).ToList(); // Trim any whitespace elements from the end of the array. for (int i = tokens.Count - 1; i > 0; --i) if (tokens[i] == string.Empty) tokens.RemoveAt(i); // Removes the rogue empty element at the beginning of the array if (tokens[0] != null && tokens[0] == string.Empty) tokens.Shift(); return tokens; } } }
/** * @brief Same throttleing mechanism as the baseline global_round_robin scheme. However * this controller puts high apps into a cluster with batching. The number of clusters is * no longer static. Each cluster is batched with an average MPKI value. Therefore the number * of clusters depends on the number of high apps and their average MPKI value. * * TODO: can go into throttle mode with only 2 nodes, and none of them has high enough MPKI to throttle. * * Trigger metric: netutil. * High app metric: MPKI. * Batch metric: MPKI. **/ //#define DEBUG_NETUTIL //#define DEBUG #define DEBUG_CLUSTER //#define DEBUG_CLUSTER2 #define DEBUG_CLUSTER_RATE using System; using System.Collections.Generic; namespace ICSimulator { public class Controller_Uniform_Batch: Controller_Global_Batch { public static double[] ipc_diff=new double[Config.N]; //total ipc retired during every free injection slot public static double[] ipc_free=new double[Config.N]; public static double[] ipc_throttled=new double[Config.N]; public static ulong[] ins_free=new ulong[Config.N]; public static ulong[] ins_throttled=new ulong[Config.N]; public static int[] last_free_nodes=new int[Config.N]; public Controller_Uniform_Batch() { isThrottling = false; for (int i = 0; i < Config.N; i++) { ipc_diff[i]=0.0; ipc_free[i]=0.0; ipc_throttled[i]=0.0; ins_free[i]=0; ins_throttled[i]=0; last_free_nodes[i]=0; MPKI[i]=0.0; num_ins_last_epoch[i]=0; m_isThrottled[i]=false; L1misses[i]=0; lastNetUtil = 0; } cluster_pool=new UniformBatchClusterPool(Config.cluster_MPKI_threshold); } public override void doThrottling() { //Unthrottle all nodes b/c could have nodes being throttled //in last sample period, but not supposed to be throttle in //this period. for(int i=0;i<Config.N;i++) { setThrottleRate(i,false); m_nodeStates[i] = NodeState.Low; } //Throttle all the high nodes int [] high_nodes=cluster_pool.allNodes(); Console.Write("\n:: cycle {0} ::", Simulator.CurrentRound); foreach (int node in high_nodes) { setThrottleRate(node,true); m_nodeStates[node] = NodeState.HighOther; } #if DEBUG_CLUSTER2 Console.Write("\nLow nodes *NOT* throttled: "); for(int i=0;i<Config.N;i++) if(!m_isThrottled[i]) { Console.Write("{0} ",i); throw new Exception("All nodes should be in high cluster in uniform cluster controller"); } #endif //Unthrottle all the nodes in the cluster int [] nodes=cluster_pool.nodesInNextCluster(); #if DEBUG_CLUSTER2 Console.Write("\nUnthrottling cluster nodes: "); #endif if(nodes.Length>0) { //Clear the vector for last free nodes Array.Clear(last_free_nodes,0,last_free_nodes.Length); foreach (int node in nodes) { ins_free[node]=(ulong)Simulator.stats.insns_persrc[node].Count; last_free_nodes[node]=1; Console.Write("\nFree Turn: Node {0} w/ ins {1} ",node,ins_free[node]); setThrottleRate(node,false); m_nodeStates[node] = NodeState.HighGolden; Simulator.stats.throttle_time_bysrc[node].Add(); #if DEBUG_CLUSTER2 Console.Write("{0} ",node); #endif } } #if DEBUG_CLUSTER2 Console.Write("\nThrottled nodes: "); for(int i=0;i<Config.N;i++) if(m_isThrottled[i]) Console.Write("{0} ",i); Console.Write("\n*NOT* Throttled nodes: "); for(int i=0;i<Config.N;i++) if(!m_isThrottled[i]) Console.Write("{0} ",i); Console.Write("\n"); #endif } public override void doStep() { if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.interval_length) == 0) { for(int node=0;node<Config.N;node++) { /* Calculate IPC during the last free-inject and throtttled interval */ if(ins_throttled[node]==0) ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count; if(last_free_nodes[node]==1) { ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_free[node]; ipc_free[node]+=(double)ins_retired/Config.interval_length; Console.Write("\nFree calc: Node {0} w/ ins {1}->{3} retired {2}::IPC accum:{4}", node,ins_free[node],ins_retired,Simulator.stats.insns_persrc[node].Count, ipc_free[node]); } else { ulong ins_retired=(ulong)Simulator.stats.insns_persrc[node].Count-ins_throttled[node]; ipc_throttled[node]+=(double)ins_retired/Config.interval_length; } ins_throttled[node]=(ulong)Simulator.stats.insns_persrc[node].Count; } } //sampling period: Examine the network state and determine whether to throttle or not if (Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0) { setThrottling(); lastNetUtil = Simulator.stats.netutil.Total; resetStat(); } //once throttle mode is turned on. Let each cluster run for a certain time interval //to ensure fairness. Otherwise it's throttled most of the time. if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.interval_length) == 0) doThrottling(); } public override void setThrottling() { if(isThrottling) { Console.WriteLine("\n:: cycle {0} ::", Simulator.CurrentRound); int free_inj_count=Config.throttle_sampling_period/Config.interval_length/Config.N; int throttled_inj_count=(Config.throttle_sampling_period/Config.interval_length)-free_inj_count; for(int i=0;i<Config.N;i++) { ipc_free[i]/=free_inj_count; ipc_throttled[i]/=throttled_inj_count; if(ipc_free[i]==0) ipc_diff[i]=0; else ipc_diff[i]=(ipc_free[i]==0)?0:(ipc_free[i]-ipc_throttled[i])/ipc_throttled[i]; //record the % difference Simulator.stats.ipc_diff_bysrc[i].Add(ipc_diff[i]); Console.WriteLine("id:{0} ipc_free:{1} ipc_th:{2} ipc free gain:{3}%", i,ipc_free[i],ipc_throttled[i],(int)(ipc_diff[i]*100)); //Reset ipc_diff[i]=0.0; ipc_free[i]=0.0; ipc_throttled[i]=0.0; ins_free[i]=0; ins_throttled[i]=0; last_free_nodes[i]=0; } } #if DEBUG_NETUTIL Console.Write("\n:: cycle {0} ::", Simulator.CurrentRound); #endif //get the MPKI value for (int i = 0; i < Config.N; i++) { prev_MPKI[i]=MPKI[i]; if(num_ins_last_epoch[i]==0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count); else { if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]); else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0) MPKI[i]=0; else throw new Exception("MPKI error!"); } } recordStats(); if(isThrottling) { #if DEBUG_NETUTIL double netutil=((double)(Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period); Console.WriteLine("In throttle mode: avg netUtil = {0} thres at {1}", netutil,Config.netutil_throttling_threshold); #endif isThrottling=false; //un-throttle the network for(int i=0;i<Config.N;i++) setThrottleRate(i,false); cluster_pool.removeAllClusters(); Simulator.stats.total_th_rate.Add(Config.RR_throttle_rate); } if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not { //Add every node to high cluster int total_high = 0; double total_mpki=0.0; for (int i = 0; i < Config.N; i++) { total_mpki+=MPKI[i]; cluster_pool.addNewNode(i,MPKI[i]); total_high++; #if DEBUG Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]); #endif } Simulator.stats.total_sum_mpki.Add(total_mpki); #if DEBUG Console.WriteLine(")"); #endif //if no node needs to be throttled, set throttling to false isThrottling = (total_high>0)?true:false; #if DEBUG_CLUSTER cluster_pool.printClusterPool(); #endif } } } public class UniformBatchClusterPool: BatchClusterPool { public UniformBatchClusterPool(double mpki_threshold) :base(mpki_threshold) { _mpki_threshold=mpki_threshold; q=new List<Cluster>(); nodes_pool=new List<int>(); _cluster_id=0; } public void addNewNodeUniform(int id, double mpki) { nodes_pool.Add(id); q.Add(new Cluster()); Cluster cur_cluster=q[q.Count-1]; cur_cluster.addNode(id,mpki); return; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Chat { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ChatModule")] public class ChatModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected const int DEBUG_CHANNEL = 2147483647; protected bool m_enabled = true; protected int m_saydistance = 20; protected int m_shoutdistance = 100; protected int m_whisperdistance = 10; protected List<Scene> m_scenes = new List<Scene>(); protected List<string> FreezeCache = new List<string>(); protected string m_adminPrefix = ""; protected object m_syncy = new object(); protected IConfig m_config; #region ISharedRegionModule Members public virtual void Initialise(IConfigSource config) { m_config = config.Configs["Chat"]; if (m_config != null) { if (!m_config.GetBoolean("enabled", true)) { m_log.Info("[CHAT]: plugin disabled by configuration"); m_enabled = false; return; } m_whisperdistance = m_config.GetInt("whisper_distance", m_whisperdistance); m_saydistance = m_config.GetInt("say_distance", m_saydistance); m_shoutdistance = m_config.GetInt("shout_distance", m_shoutdistance); m_adminPrefix = m_config.GetString("admin_prefix", ""); } } public virtual void AddRegion(Scene scene) { if (!m_enabled) return; lock (m_syncy) { if (!m_scenes.Contains(scene)) { m_scenes.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnChatFromWorld += OnChatFromWorld; scene.EventManager.OnChatBroadcast += OnChatBroadcast; } } m_log.InfoFormat("[CHAT]: Initialized for {0} w:{1} s:{2} S:{3}", scene.RegionInfo.RegionName, m_whisperdistance, m_saydistance, m_shoutdistance); } public virtual void RegionLoaded(Scene scene) { if (!m_enabled) return; ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>(); if (featuresModule != null) featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest; } public virtual void RemoveRegion(Scene scene) { if (!m_enabled) return; lock (m_syncy) { if (m_scenes.Contains(scene)) { scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnChatFromWorld -= OnChatFromWorld; scene.EventManager.OnChatBroadcast -= OnChatBroadcast; m_scenes.Remove(scene); } } } public virtual void Close() { } public virtual void PostInitialise() { } public virtual Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "ChatModule"; } } #endregion public virtual void OnNewClient(IClientAPI client) { client.OnChatFromClient += OnChatFromClient; } protected virtual OSChatMessage FixPositionOfChatMessage(OSChatMessage c) { ScenePresence avatar; Scene scene = (Scene)c.Scene; if ((avatar = scene.GetScenePresence(c.Sender.AgentId)) != null) c.Position = avatar.AbsolutePosition; return c; } public virtual void OnChatFromClient(Object sender, OSChatMessage c) { c = FixPositionOfChatMessage(c); // redistribute to interested subscribers Scene scene = (Scene)c.Scene; scene.EventManager.TriggerOnChatFromClient(sender, c); // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; // sanity check: if (c.Sender == null) { m_log.ErrorFormat("[CHAT]: OnChatFromClient from {0} has empty Sender field!", sender); return; } if (FreezeCache.Contains(c.Sender.AgentId.ToString())) { if (c.Type != ChatTypeEnum.StartTyping || c.Type != ChatTypeEnum.StopTyping) c.Sender.SendAgentAlertMessage("You may not talk as you are frozen.", false); } else { DeliverChatToAvatars(ChatSourceType.Agent, c); } } public virtual void OnChatFromWorld(Object sender, OSChatMessage c) { // early return if not on public or debug channel if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; DeliverChatToAvatars(ChatSourceType.Object, c); } protected virtual void DeliverChatToAvatars(ChatSourceType sourceType, OSChatMessage c) { string fromName = c.From; string fromNamePrefix = ""; UUID fromID = UUID.Zero; UUID ownerID = UUID.Zero; string message = c.Message; Scene scene = c.Scene as Scene; UUID destination = c.Destination; Vector3 fromPos = c.Position; Vector3 regionPos = new Vector3(scene.RegionInfo.WorldLocX, scene.RegionInfo.WorldLocY, 0); bool checkParcelHide = false; UUID sourceParcelID = UUID.Zero; Vector3 hidePos = fromPos; if (c.Channel == DEBUG_CHANNEL) c.Type = ChatTypeEnum.DebugChannel; if(!m_scenes.Contains(scene)) { m_log.WarnFormat("[CHAT]: message from unkown scene {0} ignored", scene.RegionInfo.RegionName); return; } switch (sourceType) { case ChatSourceType.Agent: ScenePresence avatar = (scene as Scene).GetScenePresence(c.Sender.AgentId); fromPos = avatar.AbsolutePosition; fromName = avatar.Name; fromID = c.Sender.AgentId; if (avatar.IsViewerUIGod) { // let gods speak to outside or things may get confusing fromNamePrefix = m_adminPrefix; checkParcelHide = false; } else { checkParcelHide = true; } destination = UUID.Zero; // Avatars cant "SayTo" ownerID = c.Sender.AgentId; hidePos = fromPos; break; case ChatSourceType.Object: fromID = c.SenderUUID; if (c.SenderObject != null && c.SenderObject is SceneObjectPart) { ownerID = ((SceneObjectPart)c.SenderObject).OwnerID; if (((SceneObjectPart)c.SenderObject).ParentGroup.IsAttachment) { checkParcelHide = true; hidePos = ((SceneObjectPart)c.SenderObject).ParentGroup.AbsolutePosition; } } break; } // TODO: iterate over message if (message.Length >= 1000) // libomv limit message = message.Substring(0, 1000); // m_log.DebugFormat( // "[CHAT]: DCTA: fromID {0} fromName {1}, region{2}, cType {3}, sType {4}", // fromID, fromName, scene.RegionInfo.RegionName, c.Type, sourceType); HashSet<UUID> receiverIDs = new HashSet<UUID>(); if (checkParcelHide) { checkParcelHide = false; if (c.Type < ChatTypeEnum.DebugChannel && destination == UUID.Zero) { ILandObject srcland = scene.LandChannel.GetLandObject(hidePos.X, hidePos.Y); if (srcland != null && !srcland.LandData.SeeAVs) { sourceParcelID = srcland.LandData.GlobalID; checkParcelHide = true; } } } scene.ForEachScenePresence( delegate(ScenePresence presence) { if (destination != UUID.Zero && presence.UUID != destination) return; if(presence.IsChildAgent) { if(checkParcelHide) return; if (TrySendChatMessage(presence, fromPos, regionPos, fromID, ownerID, fromNamePrefix + fromName, c.Type, message, sourceType, (destination != UUID.Zero))) receiverIDs.Add(presence.UUID); return; } ILandObject Presencecheck = scene.LandChannel.GetLandObject(presence.AbsolutePosition.X, presence.AbsolutePosition.Y); if (Presencecheck != null) { if (checkParcelHide) { if (sourceParcelID != Presencecheck.LandData.GlobalID && !presence.IsViewerUIGod) return; } if (c.Sender == null || Presencecheck.IsEitherBannedOrRestricted(c.Sender.AgentId) != true) { if (TrySendChatMessage(presence, fromPos, regionPos, fromID, ownerID, fromNamePrefix + fromName, c.Type, message, sourceType, (destination != UUID.Zero))) receiverIDs.Add(presence.UUID); } } }); scene.EventManager.TriggerOnChatToClients( fromID, receiverIDs, message, c.Type, fromPos, fromName, sourceType, ChatAudibleLevel.Fully); } static protected Vector3 CenterOfRegion = new Vector3(128, 128, 30); public virtual void OnChatBroadcast(Object sender, OSChatMessage c) { if (c.Channel != 0 && c.Channel != DEBUG_CHANNEL) return; ChatTypeEnum cType = c.Type; if (c.Channel == DEBUG_CHANNEL) cType = ChatTypeEnum.DebugChannel; if (cType == ChatTypeEnum.Region) cType = ChatTypeEnum.Say; if (c.Message.Length > 1100) c.Message = c.Message.Substring(0, 1000); // broadcast chat works by redistributing every incoming chat // message to each avatar in the scene. string fromName = c.From; UUID fromID = UUID.Zero; UUID ownerID = UUID.Zero; ChatSourceType sourceType = ChatSourceType.Object; if (null != c.Sender) { ScenePresence avatar = (c.Scene as Scene).GetScenePresence(c.Sender.AgentId); fromID = c.Sender.AgentId; fromName = avatar.Name; ownerID = c.Sender.AgentId; sourceType = ChatSourceType.Agent; } else if (c.SenderUUID != UUID.Zero) { fromID = c.SenderUUID; ownerID = ((SceneObjectPart)c.SenderObject).OwnerID; } // m_log.DebugFormat("[CHAT] Broadcast: fromID {0} fromName {1}, cType {2}, sType {3}", fromID, fromName, cType, sourceType); HashSet<UUID> receiverIDs = new HashSet<UUID>(); if (c.Scene != null) { ((Scene)c.Scene).ForEachRootClient ( delegate(IClientAPI client) { // don't forward SayOwner chat from objects to // non-owner agents if ((c.Type == ChatTypeEnum.Owner) && (null != c.SenderObject) && (((SceneObjectPart)c.SenderObject).OwnerID != client.AgentId)) return; client.SendChatMessage(c.Message, (byte)cType, CenterOfRegion, fromName, fromID, fromID, (byte)sourceType, (byte)ChatAudibleLevel.Fully); receiverIDs.Add(client.AgentId); } ); (c.Scene as Scene).EventManager.TriggerOnChatToClients( fromID, receiverIDs, c.Message, cType, CenterOfRegion, fromName, sourceType, ChatAudibleLevel.Fully); } } /// <summary> /// Try to send a message to the given presence /// </summary> /// <param name="presence">The receiver</param> /// <param name="fromPos"></param> /// <param name="regionPos">/param> /// <param name="fromAgentID"></param> /// <param name='ownerID'> /// Owner of the message. For at least some messages from objects, this has to be correctly filled with the owner's UUID. /// This is the case for script error messages in viewer 3 since LLViewer change EXT-7762 /// </param> /// <param name="fromName"></param> /// <param name="type"></param> /// <param name="message"></param> /// <param name="src"></param> /// <returns>true if the message was sent to the receiver, false if it was not sent due to failing a /// precondition</returns> protected virtual bool TrySendChatMessage( ScenePresence presence, Vector3 fromPos, Vector3 regionPos, UUID fromAgentID, UUID ownerID, string fromName, ChatTypeEnum type, string message, ChatSourceType src, bool ignoreDistance) { if (presence.LifecycleState != ScenePresenceState.Running) return false; if (!ignoreDistance) { Vector3 fromRegionPos = fromPos + regionPos; Vector3 toRegionPos = presence.AbsolutePosition + new Vector3(presence.Scene.RegionInfo.WorldLocX, presence.Scene.RegionInfo.WorldLocY, 0); int dis = (int)Util.GetDistanceTo(toRegionPos, fromRegionPos); if (type == ChatTypeEnum.Whisper && dis > m_whisperdistance || type == ChatTypeEnum.Say && dis > m_saydistance || type == ChatTypeEnum.Shout && dis > m_shoutdistance) { return false; } } // TODO: should change so the message is sent through the avatar rather than direct to the ClientView presence.ControllingClient.SendChatMessage( message, (byte) type, fromPos, fromName, fromAgentID, ownerID, (byte)src, (byte)ChatAudibleLevel.Fully); return true; } Dictionary<UUID, System.Threading.Timer> Timers = new Dictionary<UUID, System.Threading.Timer>(); public virtual void ParcelFreezeUser(IClientAPI client, UUID parcelowner, uint flags, UUID target) { System.Threading.Timer Timer; if (flags == 0) { FreezeCache.Add(target.ToString()); System.Threading.TimerCallback timeCB = new System.Threading.TimerCallback(OnEndParcelFrozen); Timer = new System.Threading.Timer(timeCB, target, 30000, 0); Timers.Add(target, Timer); } else { FreezeCache.Remove(target.ToString()); Timers.TryGetValue(target, out Timer); Timers.Remove(target); Timer.Dispose(); } } protected virtual void OnEndParcelFrozen(object avatar) { UUID target = (UUID)avatar; FreezeCache.Remove(target.ToString()); System.Threading.Timer Timer; Timers.TryGetValue(target, out Timer); Timers.Remove(target); Timer.Dispose(); } #region SimulatorFeaturesRequest protected static OSDInteger m_SayRange, m_WhisperRange, m_ShoutRange; protected virtual void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features) { OSD extras = new OSDMap(); if (features.ContainsKey("OpenSimExtras")) extras = features["OpenSimExtras"]; else features["OpenSimExtras"] = extras; if (m_SayRange == null) { // Do this only once m_SayRange = new OSDInteger(m_saydistance); m_WhisperRange = new OSDInteger(m_whisperdistance); m_ShoutRange = new OSDInteger(m_shoutdistance); } ((OSDMap)extras)["say-range"] = m_SayRange; ((OSDMap)extras)["whisper-range"] = m_WhisperRange; ((OSDMap)extras)["shout-range"] = m_ShoutRange; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections; using System.Management.Automation; using System.Management.Automation.Internal; using System.Globalization; using Microsoft.PowerShell.Commands.Internal.Format; using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.Commands { /// <summary> /// Definitions for hash table keys. /// </summary> internal static class SortObjectParameterDefinitionKeys { internal const string AscendingEntryKey = "ascending"; internal const string DescendingEntryKey = "descending"; } /// <summary> /// </summary> internal class SortObjectExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { this.hashEntries.Add(new ExpressionEntryDefinition(false)); this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.AscendingEntryKey)); this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.DescendingEntryKey)); } } /// <summary> /// </summary> internal class GroupObjectExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { this.hashEntries.Add(new ExpressionEntryDefinition(true)); } } /// <summary> /// Base Cmdlet for cmdlets which deal with raw objects. /// </summary> public class ObjectCmdletBase : PSCmdlet { #region Parameters /// <summary> /// </summary> /// <value></value> [Parameter] [System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "The CultureNumber is only used if the property has been set with a hex string starting with 0x")] public string Culture { get { return _cultureInfo != null ? _cultureInfo.ToString() : null; } set { if (string.IsNullOrEmpty(value)) { _cultureInfo = null; return; } int cultureNumber; string trimmedValue = value.Trim(); if (trimmedValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { if ((trimmedValue.Length > 2) && int.TryParse(trimmedValue.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture, out cultureNumber)) { _cultureInfo = new CultureInfo(cultureNumber); return; } } else if (int.TryParse(trimmedValue, NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out cultureNumber)) { _cultureInfo = new CultureInfo(cultureNumber); return; } _cultureInfo = new CultureInfo(value); } } internal CultureInfo _cultureInfo = null; /// <summary> /// </summary> /// <value></value> [Parameter] public SwitchParameter CaseSensitive { get { return _caseSensitive; } set { _caseSensitive = value; } } private bool _caseSensitive; #endregion Parameters } /// <summary> /// Base Cmdlet for object cmdlets that deal with Grouping, Sorting and Comparison. /// </summary> public abstract class ObjectBase : ObjectCmdletBase { #region Parameters /// <summary> /// </summary> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } = AutomationNull.Value; /// <summary> /// Gets or Sets the Properties that would be used for Grouping, Sorting and Comparison. /// </summary> [Parameter(Position = 0)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] Property { get; set; } #endregion Parameters } /// <summary> /// Base Cmdlet for object cmdlets that deal with Ordering and Comparison. /// </summary> public class OrderObjectBase : ObjectBase { #region Internal Properties /// <summary> /// Specifies sorting order. /// </summary> internal SwitchParameter DescendingOrder { get { return !_ascending; } set { _ascending = !value; } } private bool _ascending = true; internal List<PSObject> InputObjects { get; } = new List<PSObject>(); /// <summary> /// CultureInfo converted from the Culture Cmdlet parameter. /// </summary> internal CultureInfo ConvertedCulture { get { return _cultureInfo; } } #endregion Internal Properties /// <summary> /// Simply accumulates the incoming objects. /// </summary> protected override void ProcessRecord() { if (InputObject != null && InputObject != AutomationNull.Value) { InputObjects.Add(InputObject); } } } internal sealed class OrderByProperty { #region Internal properties /// <summary> /// A logical matrix where each row is an input object and its property values specified by Properties. /// </summary> internal List<OrderByPropertyEntry> OrderMatrix { get; } = null; internal OrderByPropertyComparer Comparer { get; } = null; internal List<MshParameter> MshParameterList { get { return _mshParameterList; } } #endregion Internal properties #region Utils // These are made static for Measure-Object's GroupBy parameter that measure the outputs of Group-Object // However, Measure-Object differs from Group-Object and Sort-Object considerably that it should not // be built on the same base class, i.e., this class. Moreover, Measure-Object's Property parameter is // a string array and allows wildcard. // Yes, the Cmdlet is needed. It's used to get the TerminatingErrorContext, WriteError and WriteDebug. #region process PSPropertyExpression and MshParameter private static void ProcessExpressionParameter( List<PSObject> inputObjects, PSCmdlet cmdlet, object[] expr, out List<MshParameter> mshParameterList) { mshParameterList = null; TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); if (expr == null && inputObjects != null && inputObjects.Count > 0) { expr = GetDefaultKeyPropertySet(inputObjects[0]); } if (expr != null) { List<MshParameter> unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); mshParameterList = ExpandExpressions(inputObjects, unexpandedParameterList); } // NOTE: if no parameters are passed, we will look at the default keys of the first // incoming object } internal void ProcessExpressionParameter( PSCmdlet cmdlet, object[] expr) { TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); if (expr != null) { if (_unexpandedParameterList == null) { _unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); foreach (MshParameter unexpandedParameter in _unexpandedParameterList) { PSPropertyExpression mshExpression = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); if (!mshExpression.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings { _mshParameterList.Add(unexpandedParameter); } else { if (_unExpandedParametersWithWildCardPattern == null) { _unExpandedParametersWithWildCardPattern = new List<MshParameter>(); } _unExpandedParametersWithWildCardPattern.Add(unexpandedParameter); } } } } } // Expand a list of (possibly wildcarded) expressions into resolved expressions that // match property names on the incoming objects. private static List<MshParameter> ExpandExpressions(List<PSObject> inputObjects, List<MshParameter> unexpandedParameterList) { List<MshParameter> expandedParameterList = new List<MshParameter>(); if (unexpandedParameterList != null) { foreach (MshParameter unexpandedParameter in unexpandedParameterList) { PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); if (!ex.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings { expandedParameterList.Add(unexpandedParameter); } else { SortedDictionary<string, PSPropertyExpression> expandedPropertyNames = new SortedDictionary<string, PSPropertyExpression>(StringComparer.OrdinalIgnoreCase); if (inputObjects != null) { foreach (object inputObject in inputObjects) { if (inputObject == null) { continue; } foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject))) { expandedPropertyNames[resolvedName.ToString()] = resolvedName; } } } foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values) { MshParameter expandedParameter = new MshParameter(); expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; expandedParameterList.Add(expandedParameter); } } } } return expandedParameterList; } // Expand a list of (possibly wildcarded) expressions into resolved expressions that // match property names on the incoming objects. private static void ExpandExpressions(PSObject inputObject, List<MshParameter> UnexpandedParametersWithWildCardPattern, List<MshParameter> expandedParameterList) { if (UnexpandedParametersWithWildCardPattern != null) { foreach (MshParameter unexpandedParameter in UnexpandedParametersWithWildCardPattern) { PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); SortedDictionary<string, PSPropertyExpression> expandedPropertyNames = new SortedDictionary<string, PSPropertyExpression>(StringComparer.OrdinalIgnoreCase); if (inputObject == null) { continue; } foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject))) { expandedPropertyNames[resolvedName.ToString()] = resolvedName; } foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values) { MshParameter expandedParameter = new MshParameter(); expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; expandedParameterList.Add(expandedParameter); } } } } internal static string[] GetDefaultKeyPropertySet(PSObject mshObj) { PSMemberSet standardNames = mshObj.PSStandardMembers; if (standardNames == null) { return null; } PSPropertySet defaultKeys = standardNames.Members["DefaultKeyPropertySet"] as PSPropertySet; if (defaultKeys == null) { return null; } string[] props = new string[defaultKeys.ReferencedPropertyNames.Count]; defaultKeys.ReferencedPropertyNames.CopyTo(props, 0); return props; } #endregion process PSPropertyExpression and MshParameter internal static List<OrderByPropertyEntry> CreateOrderMatrix( PSCmdlet cmdlet, List<PSObject> inputObjects, List<MshParameter> mshParameterList ) { List<OrderByPropertyEntry> orderMatrixToCreate = new List<OrderByPropertyEntry>(); for (int index = 0; index < inputObjects.Count; index++) { PSObject so = inputObjects[index]; if (so == null || so == AutomationNull.Value) continue; List<ErrorRecord> evaluationErrors = new List<ErrorRecord>(); List<string> propertyNotFoundMsgs = new List<string>(); OrderByPropertyEntry result = OrderByPropertyEntryEvaluationHelper.ProcessObject(so, mshParameterList, evaluationErrors, propertyNotFoundMsgs, originalIndex: index); foreach (ErrorRecord err in evaluationErrors) { cmdlet.WriteError(err); } foreach (string debugMsg in propertyNotFoundMsgs) { cmdlet.WriteDebug(debugMsg); } orderMatrixToCreate.Add(result); } return orderMatrixToCreate; } private static bool isOrderEntryKeyDefined(object orderEntryKey) { return orderEntryKey != null && orderEntryKey != AutomationNull.Value; } private static OrderByPropertyComparer CreateComparer( List<OrderByPropertyEntry> orderMatrix, List<MshParameter> mshParameterList, bool ascending, CultureInfo cultureInfo, bool caseSensitive) { if (orderMatrix == null || orderMatrix.Count == 0) { return null; } bool?[] ascendingOverrides = null; if (mshParameterList != null && mshParameterList.Count != 0) { ascendingOverrides = new bool?[mshParameterList.Count]; for (int k = 0; k < ascendingOverrides.Length; k++) { object ascendingVal = mshParameterList[k].GetEntry( SortObjectParameterDefinitionKeys.AscendingEntryKey); object descendingVal = mshParameterList[k].GetEntry( SortObjectParameterDefinitionKeys.DescendingEntryKey); bool isAscendingDefined = isOrderEntryKeyDefined(ascendingVal); bool isDescendingDefined = isOrderEntryKeyDefined(descendingVal); if (!isAscendingDefined && !isDescendingDefined) { // if neither ascending nor descending is defined ascendingOverrides[k] = null; } else if (isAscendingDefined && isDescendingDefined && (bool)ascendingVal == (bool)descendingVal) { // if both ascending and descending defined but their values conflict // they are ignored. ascendingOverrides[k] = null; } else if (isAscendingDefined) { ascendingOverrides[k] = (bool)ascendingVal; } else { ascendingOverrides[k] = !(bool)descendingVal; } } } OrderByPropertyComparer comparer = OrderByPropertyComparer.CreateComparer(orderMatrix, ascending, ascendingOverrides, cultureInfo, caseSensitive); return comparer; } internal OrderByProperty( PSCmdlet cmdlet, List<PSObject> inputObjects, object[] expr, bool ascending, CultureInfo cultureInfo, bool caseSensitive ) { Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); ProcessExpressionParameter(inputObjects, cmdlet, expr, out _mshParameterList); OrderMatrix = CreateOrderMatrix(cmdlet, inputObjects, _mshParameterList); Comparer = CreateComparer(OrderMatrix, _mshParameterList, ascending, cultureInfo, caseSensitive); } /// <summary> /// OrderByProperty constructor. /// </summary> internal OrderByProperty() { _mshParameterList = new List<MshParameter>(); OrderMatrix = new List<OrderByPropertyEntry>(); } /// <summary> /// Utility function used to create OrderByPropertyEntry for the supplied input object. /// </summary> /// <param name="cmdlet">PSCmdlet.</param> /// <param name="inputObject">Input Object.</param> /// <param name="isCaseSensitive">Indicates if the Property value comparisons need to be case sensitive or not.</param> /// <param name="cultureInfo">Culture Info that needs to be used for comparison.</param> /// <returns>OrderByPropertyEntry for the supplied InputObject.</returns> internal OrderByPropertyEntry CreateOrderByPropertyEntry( PSCmdlet cmdlet, PSObject inputObject, bool isCaseSensitive, CultureInfo cultureInfo) { Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); if (_unExpandedParametersWithWildCardPattern != null) { ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList); } List<ErrorRecord> evaluationErrors = new List<ErrorRecord>(); List<string> propertyNotFoundMsgs = new List<string>(); OrderByPropertyEntry result = OrderByPropertyEntryEvaluationHelper.ProcessObject(inputObject, _mshParameterList, evaluationErrors, propertyNotFoundMsgs, isCaseSensitive, cultureInfo); foreach (ErrorRecord err in evaluationErrors) { cmdlet.WriteError(err); } foreach (string debugMsg in propertyNotFoundMsgs) { cmdlet.WriteDebug(debugMsg); } return result; } #endregion Utils // list of processed parameters obtained from the Expression array private List<MshParameter> _mshParameterList = null; // list of unprocessed parameters obtained from the Expression array. private List<MshParameter> _unexpandedParameterList = null; // list of unprocessed parameters with wild card patterns. private List<MshParameter> _unExpandedParametersWithWildCardPattern = null; } internal static class OrderByPropertyEntryEvaluationHelper { internal static OrderByPropertyEntry ProcessObject(PSObject inputObject, List<MshParameter> mshParameterList, List<ErrorRecord> errors, List<string> propertyNotFoundMsgs, bool isCaseSensitive = false, CultureInfo cultureInfo = null, int originalIndex = -1) { Diagnostics.Assert(errors != null, "errors cannot be null!"); Diagnostics.Assert(propertyNotFoundMsgs != null, "propertyNotFoundMsgs cannot be null!"); OrderByPropertyEntry entry = new OrderByPropertyEntry(); entry.inputObject = inputObject; entry.originalIndex = originalIndex; if (mshParameterList == null || mshParameterList.Count == 0) { // we do not have a property to evaluate, we sort on $_ entry.orderValues.Add(new ObjectCommandPropertyValue(inputObject, isCaseSensitive, cultureInfo)); entry.comparable = true; return entry; } // we need to compute the properties foreach (MshParameter p in mshParameterList) { string propertyNotFoundMsg = null; EvaluateSortingExpression(p, inputObject, entry.orderValues, errors, out propertyNotFoundMsg, ref entry.comparable); if (!string.IsNullOrEmpty(propertyNotFoundMsg)) { propertyNotFoundMsgs.Add(propertyNotFoundMsg); } } return entry; } private static void EvaluateSortingExpression( MshParameter p, PSObject inputObject, List<ObjectCommandPropertyValue> orderValues, List<ErrorRecord> errors, out string propertyNotFoundMsg, ref bool comparable) { // NOTE: we assume globbing was not allowed in input PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; // get the values, but do not expand aliases List<PSPropertyExpressionResult> expressionResults = ex.GetValues(inputObject, false, true); if (expressionResults.Count == 0) { // we did not get any result out of the expression: // we enter a null as a place holder orderValues.Add(ObjectCommandPropertyValue.NonExistingProperty); propertyNotFoundMsg = StringUtil.Format(SortObjectStrings.PropertyNotFound, ex.ToString()); return; } propertyNotFoundMsg = null; // we obtained some results, enter them into the list foreach (PSPropertyExpressionResult r in expressionResults) { if (r.Exception == null) { orderValues.Add(new ObjectCommandPropertyValue(r.Result)); } else { ErrorRecord errorRecord = new ErrorRecord( r.Exception, "ExpressionEvaluation", ErrorCategory.InvalidResult, inputObject); errors.Add(errorRecord); orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty); } comparable = true; } } } /// <summary> /// This is the row of the OrderMatrix. /// </summary> internal sealed class OrderByPropertyEntry { internal PSObject inputObject = null; internal List<ObjectCommandPropertyValue> orderValues = new List<ObjectCommandPropertyValue>(); // The originalIndex field was added to enable stable heap-sorts (Top N/Bottom N) internal int originalIndex = -1; // The comparable field enables faster identification of uncomparable data internal bool comparable = false; } internal class OrderByPropertyComparer : IComparer<OrderByPropertyEntry> { internal OrderByPropertyComparer(bool[] ascending, CultureInfo cultureInfo, bool caseSensitive) { _propertyComparers = new ObjectCommandComparer[ascending.Length]; for (int k = 0; k < ascending.Length; k++) { _propertyComparers[k] = new ObjectCommandComparer(ascending[k], cultureInfo, caseSensitive); } } public int Compare(OrderByPropertyEntry firstEntry, OrderByPropertyEntry secondEntry) { // we have to take into consideration that some vectors // might be shorter than others int order = 0; for (int k = 0; k < _propertyComparers.Length; k++) { ObjectCommandPropertyValue firstValue = (k < firstEntry.orderValues.Count) ? firstEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; ObjectCommandPropertyValue secondValue = (k < secondEntry.orderValues.Count) ? secondEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; order = _propertyComparers[k].Compare(firstValue, secondValue); if (order != 0) return order; } return order; } internal static OrderByPropertyComparer CreateComparer(List<OrderByPropertyEntry> orderMatrix, bool ascendingFlag, bool?[] ascendingOverrides, CultureInfo cultureInfo, bool caseSensitive) { if (orderMatrix.Count == 0) return null; // create a comparer able to handle a vector of N entries, // where N is the max number of entries int maxEntries = 0; foreach (OrderByPropertyEntry entry in orderMatrix) { if (entry.orderValues.Count > maxEntries) maxEntries = entry.orderValues.Count; } if (maxEntries == 0) return null; bool[] ascending = new bool[maxEntries]; for (int k = 0; k < maxEntries; k++) { if (ascendingOverrides != null && ascendingOverrides[k].HasValue) { ascending[k] = ascendingOverrides[k].Value; } else { ascending[k] = ascendingFlag; } } // NOTE: the size of the boolean array will determine the max width of the // vectors to check return new OrderByPropertyComparer(ascending, cultureInfo, caseSensitive); } private ObjectCommandComparer[] _propertyComparers = null; } internal class IndexedOrderByPropertyComparer : IComparer<OrderByPropertyEntry> { internal IndexedOrderByPropertyComparer(OrderByPropertyComparer orderByPropertyComparer) { _orderByPropertyComparer = orderByPropertyComparer; } public int Compare(OrderByPropertyEntry lhs, OrderByPropertyEntry rhs) { // Non-comparable items always fall after comparable items if (lhs.comparable != rhs.comparable) { return lhs.comparable.CompareTo(rhs.comparable) * -1; } int result = _orderByPropertyComparer.Compare(lhs, rhs); // When items are identical according to the internal comparison, compare by index // to preserve the original order if (result == 0) { return lhs.originalIndex.CompareTo(rhs.originalIndex); } // Otherwise, return the default comparison results return result; } private OrderByPropertyComparer _orderByPropertyComparer = null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IdentityModel.Tokens; using System.Reflection; using System.Security.Cryptography; using System.ServiceModel; namespace System.IdentityModel { internal static class CryptoHelper { private static RandomNumberGenerator s_random; private const string SHAString = "SHA"; private const string SHA1String = "SHA1"; private const string SHA256String = "SHA256"; private const string SystemSecurityCryptographySha1String = "System.Security.Cryptography.SHA1"; private static Dictionary<string, Func<object>> s_algorithmDelegateDictionary = new Dictionary<string, Func<object>>(); private static object s_algorithmDictionaryLock = new object(); internal static bool IsSymmetricAlgorithm(string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static byte[] UnwrapKey(byte[] wrappingKey, byte[] wrappedKey, string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static byte[] WrapKey(byte[] wrappingKey, byte[] keyToBeWrapped, string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static byte[] GenerateDerivedKey(byte[] key, string algorithm, byte[] label, byte[] nonce, int derivedKeySize, int position) { throw ExceptionHelper.PlatformNotSupported(); } internal static int GetIVSize(string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static ICryptoTransform CreateDecryptor(byte[] key, byte[] iv, string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static ICryptoTransform CreateEncryptor(byte[] key, byte[] iv, string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static KeyedHashAlgorithm CreateKeyedHashAlgorithm(byte[] key, string algorithm) { object algorithmObject = GetAlgorithmFromConfig(algorithm); if (algorithmObject != null) { KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm; if (keyedHashAlgorithm != null) { keyedHashAlgorithm.Key = key; return keyedHashAlgorithm; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.CustomCryptoAlgorithmIsNotValidKeyedHashAlgorithm, algorithm))); } switch (algorithm) { case SecurityAlgorithms.HmacSha1Signature: #pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1. return new HMACSHA1(key); #pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1. case SecurityAlgorithms.HmacSha256Signature: return new HMACSHA256(key); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm))); } } internal static SymmetricAlgorithm GetSymmetricAlgorithm(byte[] key, string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static bool IsAsymmetricAlgorithm(string algorithm) { throw ExceptionHelper.PlatformNotSupported(); } internal static bool IsSymmetricSupportedAlgorithm(string algorithm, int keySize) { bool found = false; object algorithmObject = null; try { algorithmObject = GetAlgorithmFromConfig(algorithm); } catch (InvalidOperationException) { // We swallow the exception and continue. } if (algorithmObject != null) { SymmetricAlgorithm symmetricAlgorithm = algorithmObject as SymmetricAlgorithm; KeyedHashAlgorithm keyedHashAlgorithm = algorithmObject as KeyedHashAlgorithm; if (symmetricAlgorithm != null || keyedHashAlgorithm != null) { found = true; } // The reason we do not return here even when the user has provided a custom algorithm to CryptoConfig // is because we need to check if the user has overwritten an existing standard URI. } switch (algorithm) { case SecurityAlgorithms.DsaSha1Signature: case SecurityAlgorithms.RsaSha1Signature: case SecurityAlgorithms.RsaSha256Signature: case SecurityAlgorithms.RsaOaepKeyWrap: case SecurityAlgorithms.RsaV15KeyWrap: return false; case SecurityAlgorithms.HmacSha1Signature: case SecurityAlgorithms.HmacSha256Signature: case SecurityAlgorithms.Psha1KeyDerivation: case SecurityAlgorithms.Psha1KeyDerivationDec2005: return true; case SecurityAlgorithms.Aes128Encryption: case SecurityAlgorithms.Aes128KeyWrap: return keySize >= 128 && keySize <= 256; case SecurityAlgorithms.Aes192Encryption: case SecurityAlgorithms.Aes192KeyWrap: return keySize >= 192 && keySize <= 256; case SecurityAlgorithms.Aes256Encryption: case SecurityAlgorithms.Aes256KeyWrap: return keySize == 256; case SecurityAlgorithms.TripleDesEncryption: case SecurityAlgorithms.TripleDesKeyWrap: return keySize == 128 || keySize == 192; default: if (found) { return true; } return false; // We do not expect the user to map the uri of an existing standrad algorithm with say key size 128 bit // to a custom algorithm with keySize 192 bits. If he does that, we anyways make sure that we return false. } } internal static void FillRandomBytes(byte[] buffer) { RandomNumberGenerator.GetBytes(buffer); } /// <summary> /// This generates the entropy using random number. This is usually used on the sending /// side to generate the requestor's entropy. /// </summary> /// <param name="data">The array to fill with cryptographically strong random nonzero bytes.</param> public static void GenerateRandomBytes(byte[] data) { RandomNumberGenerator.GetNonZeroBytes(data); } /// <summary> /// This method generates a random byte array used as entropy with the given size. /// </summary> /// <param name="sizeInBits"></param> /// <returns></returns> public static byte[] GenerateRandomBytes(int sizeInBits) { int sizeInBytes = sizeInBits / 8; if (sizeInBits <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(sizeInBits), SR.Format(SR.ID6033, sizeInBits))); } else if (sizeInBytes * 8 != sizeInBits) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.ID6002, sizeInBits), nameof(sizeInBits))); } byte[] data = new byte[sizeInBytes]; GenerateRandomBytes(data); return data; } internal static RandomNumberGenerator RandomNumberGenerator { get { if (s_random == null) { s_random = RandomNumberGenerator.Create(); } return s_random; } } internal static HashAlgorithm CreateHashAlgorithm(string algorithm) { object algorithmObject = GetAlgorithmFromConfig(algorithm); if (algorithmObject != null) { HashAlgorithm hashAlgorithm = algorithmObject as HashAlgorithm; if (hashAlgorithm != null) { return hashAlgorithm; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.CustomCryptoAlgorithmIsNotValidHashAlgorithm, algorithm))); } switch (algorithm) { case SHAString: case SHA1String: case SystemSecurityCryptographySha1String: case SecurityAlgorithms.Sha1Digest: #pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1. return SHA1.Create(); #pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1. case SHA256String: case SecurityAlgorithms.Sha256Digest: return SHA256.Create(); default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm))); } } private static object GetDefaultAlgorithm(string algorithm) { if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(algorithm))); } switch (algorithm) { //case SecurityAlgorithms.RsaSha1Signature: //case SecurityAlgorithms.DsaSha1Signature: // For these algorithms above, crypto config returns internal objects. // As we cannot create those internal objects, we are returning null. // If no custom algorithm is plugged-in, at least these two algorithms // will be inside the delegate dictionary. case SecurityAlgorithms.Sha1Digest: #pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1. return SHA1.Create(); #pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1. case SecurityAlgorithms.ExclusiveC14n: throw ExceptionHelper.PlatformNotSupported(); case SHA256String: case SecurityAlgorithms.Sha256Digest: return SHA256.Create(); case SecurityAlgorithms.Sha512Digest: return SHA512.Create(); case SecurityAlgorithms.Aes128Encryption: case SecurityAlgorithms.Aes192Encryption: case SecurityAlgorithms.Aes256Encryption: case SecurityAlgorithms.Aes128KeyWrap: case SecurityAlgorithms.Aes192KeyWrap: case SecurityAlgorithms.Aes256KeyWrap: return Aes.Create(); case SecurityAlgorithms.TripleDesEncryption: case SecurityAlgorithms.TripleDesKeyWrap: #pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms return TripleDES.Create(); #pragma warning restore CA5350 // Do Not Use Weak Cryptographic Algorithms case SecurityAlgorithms.HmacSha1Signature: #pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1. return new HMACSHA1(); #pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1. case SecurityAlgorithms.HmacSha256Signature: return new HMACSHA256(); case SecurityAlgorithms.ExclusiveC14nWithComments: throw ExceptionHelper.PlatformNotSupported(); case SecurityAlgorithms.Ripemd160Digest: return null; case SecurityAlgorithms.DesEncryption: #pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms return DES.Create(); #pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms default: return null; } } internal static object GetAlgorithmFromConfig(string algorithm) { if (string.IsNullOrEmpty(algorithm)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(algorithm))); } object algorithmObject = null; object defaultObject = null; Func<object> delegateFunction = null; if (!s_algorithmDelegateDictionary.TryGetValue(algorithm, out delegateFunction)) { lock (s_algorithmDictionaryLock) { if (!s_algorithmDelegateDictionary.ContainsKey(algorithm)) { try { algorithmObject = CryptoConfig.CreateFromName(algorithm); } catch (TargetInvocationException) { s_algorithmDelegateDictionary[algorithm] = null; } if (algorithmObject == null) { s_algorithmDelegateDictionary[algorithm] = null; } else { defaultObject = GetDefaultAlgorithm(algorithm); if (defaultObject != null && defaultObject.GetType() == algorithmObject.GetType()) { s_algorithmDelegateDictionary[algorithm] = null; } else { // Create a factory delegate which returns new instances of the algorithm type for later calls. Type algorithmType = algorithmObject.GetType(); Linq.Expressions.NewExpression algorithmCreationExpression = Linq.Expressions.Expression.New(algorithmType); Linq.Expressions.LambdaExpression creationFunction = Linq.Expressions.Expression.Lambda<Func<object>>(algorithmCreationExpression); delegateFunction = creationFunction.Compile() as Func<object>; if (delegateFunction != null) { s_algorithmDelegateDictionary[algorithm] = delegateFunction; } return algorithmObject; } } } } } else { if (delegateFunction != null) { return delegateFunction.Invoke(); } } // // This is a fallback in case CryptoConfig fails to return a valid // algorithm object. CrytoConfig does not understand all the uri's and // can return a null in that case, in which case it is our responsibility // to fallback and create the right algorithm if it is a uri we understand // switch (algorithm) { case SHA256String: case SecurityAlgorithms.Sha256Digest: return SHA256.Create(); case SecurityAlgorithms.Sha1Digest: #pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1. return SHA1.Create(); #pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1. case SecurityAlgorithms.HmacSha1Signature: #pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1. return new HMACSHA1(); #pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1. default: break; } return null; } internal static HashAlgorithm NewSha1HashAlgorithm() { return CreateHashAlgorithm(SecurityAlgorithms.Sha1Digest); } internal static HashAlgorithm NewSha256HashAlgorithm() { return CreateHashAlgorithm(SecurityAlgorithms.Sha256Digest); } internal static KeyedHashAlgorithm NewHmacSha1KeyedHashAlgorithm(byte[] key) { return CryptoHelper.CreateKeyedHashAlgorithm(key, SecurityAlgorithms.HmacSha1Signature); } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using MiniJSON; /* * Session M service implementation. Implements and provides access (via SessionM.GetInstance()) to the SessionM service. */ public class SessionM : MonoBehaviour { private ISessionMCallback callback; public string iosAppId; public string androidAppId; public LogLevel logLevel; //The SessionM Class is a monobehaviour Singleton. Drop the Gameobject in your scene and set it up instead of trying to instantiate it via code. //Put the SessionM object as early in your project as possible. The object will survive loads, so there's never a reason to put it in more than one place in your scenes. private static SessionM instance; public static SessionM GetInstance() { if(instance == null) { SessionM existingSessionM = GameObject.FindObjectOfType<SessionM>(); if(existingSessionM == null) { Debug.LogError("There is no SessionM GameObject set up in the scene. Please add one and set it up as per the SessionM Plug-In Documentation."); return null; } existingSessionM.SetSessionMNative(); instance = existingSessionM; } return instance; } public static ServiceRegion serviceRegion = ServiceRegion.USA; //Call this method before starting the session to set the service region. public static void SetServiceRegion(ServiceRegion region) { serviceRegion = region; } //Here, SessionM instantiates the appropiate Native interface to be used on each platform. //iOS: iSessionM_IOS //Android: iSessionM_Android //All others: iSessionM_Dummy (The Dummy simply catches all calls coming into SessionM un unsupported platforms.) //If you need to modify how SessionM is interacting with either iOS or Android natively, please look in the respective Interface Class. private ISessionM sessionMNative; public ISessionM SessionMNative { get { return sessionMNative; } } //The following methods can be called at anytime via the SessionM Singleton. //For instance, you can call GetSessionState from anywhere in Unity program by aclling SessionM.GetInstance().GetSessionState() //Returns SessionM's current SessionState //Can be: Stopped, Started Online, Started Offline //Use this method to determine if your user is in a valid region for SessionM. If SessionM is in a Stopped State, you should //suppress SessionM elements. public SessionState GetSessionState() { return sessionMNative.GetSessionState(); } //Use this method for displaying a badge or other SessionM tools. Remember, your Acheivement count can accumulate over days, so be sure to support at least //triple digit numbers. public int GetUnclaimedAchievementCount() { return sessionMNative.GetUnclaimedAchievementCount(); } //Use this method to get current user data. public UserData GetUserData() { UserData userData = null; string userDataJSON = null; userDataJSON = sessionMNative.GetUser(); if(userDataJSON == null) { return null; } userData = GetUserData(userDataJSON); return userData; } //Use this method to set user opt-out status public void SetUserOptOutStatus(bool status){ sessionMNative.SetUserOptOutStatus(status); } //Use this method to set the value of shouldAutoUpdateAchievementsList public void SetShouldAutoUpdateAchievementsList(bool shouldAutoUpdate) { sessionMNative.SetShouldAutoUpdateAchievementsList(shouldAutoUpdate); } //Use this method to manually update the user's achievementsList field. Has no effect if shouldAutoUpdateAchievementsList is set to true. public void UpdateAchievementsList() { sessionMNative.UpdateAchievementsList(); } //This method is required for displaying Native Acheivements. Fore more information, please see the Unity plugin documetnation. public AchievementData GetUnclaimedAchievementData() { IAchievementData achievementData = null; string achievementJSON = null; achievementJSON = sessionMNative.GetUnclaimedAchievementData(); if(achievementJSON == null) { return null; } achievementData = GetAchievementData(achievementJSON); return achievementData as AchievementData; } //This method is vital to using SessionM, whenever your user completes an action that contributes towards a SessionM Acheivement //report it to SessionM using this method. public void LogAction(string action) { sessionMNative.LogAction(action); } //You can use this method if multiple actions were achieved simultaneously. public void LogAction(string action, int count) { sessionMNative.LogAction(action, count); } //Use this method to display an Acheivement if there is an unclaimed Achievement ready. SessionM will automatically display an overlay //Acheivement display for you. You can see if there is an achievement ready by running the IsActivityAvailable method below. public bool PresentActivity(ActivityType type) { return sessionMNative.PresentActivity(type); } public bool IsActivityAvailable(ActivityType type) { return sessionMNative.IsActivityAvailable(type); } //Use this to display the SessionM Portal. You can use this after users have clicked on a Native Acheivement, or when they click on a SessionM //button in your app. public bool ShowPortal() { return PresentActivity(ActivityType.Portal); } //The following methods are generally used for debugging and won't be utilized by most SessionM Developers. public string GetSDKVersion() { return sessionMNative.GetSDKVersion(); } public string[] GetRewards() { return UnpackJSONArray(sessionMNative.GetRewards()); } public LogLevel GetLogLevel() { return sessionMNative.GetLogLevel(); } public void SetLogLevel(LogLevel level) { //Note Log Level only works on iOS. For Android, use logcat. //LogLevel can also be set on the SessionM Object. sessionMNative.SetLogLevel(level); } public bool IsActivityPresented() { return sessionMNative.IsActivityPresented(); } public void SetMetaData(string data, string key) { sessionMNative.SetMetaData(data, key); } public void NotifyPresented() { sessionMNative.NotifyPresented(); } public void NotifyDismissed() { sessionMNative.NotifyDismissed(); } public void NotifyClaimed() { sessionMNative.NotifyClaimed(); } public void DismissActivity() { sessionMNative.DismissActivity(); } public void SetCallback(ISessionMCallback callback) { sessionMNative.SetCallback(callback); } public ISessionMCallback GetCallback() { return sessionMNative.GetCallback(); } // Unity Lifecycle private void Awake() { SetSessionMNative(); GameObject.DontDestroyOnLoad(this.gameObject); instance = this; SetLogLevel (logLevel); } private void SetSessionMNative() { if(sessionMNative != null) return; //Assign the appropiate Native Class to handle method calls here. #if UNITY_EDITOR sessionMNative = new ISessionM_Dummy(); #elif UNITY_IOS sessionMNative = new ISessionM_iOS(this); #elif UNITY_ANDROID sessionMNative = new ISessionM_Android(this); #else sessionMNative = new ISessionM_Dummy(); #endif } //This is a useful method you can call whenever you need to parse a JSON string into a the IAchievementData custom class. public static IAchievementData GetAchievementData(string jsonString) { Dictionary<string, object> achievementDict = Json.Deserialize(jsonString) as Dictionary<string,object>; long mpointValue = (Int64)achievementDict["mpointValue"]; long timesEarned = (Int64)achievementDict["timesEarned"]; long unclaimedCount = (Int64)achievementDict["unclaimedCount"]; long distance = (Int64)achievementDict["distance"]; bool isCustom = (bool)achievementDict["isCustom"]; string identifier = (string)achievementDict["identifier"]; string importID = (string)achievementDict["importID"]; string instructions = (string)achievementDict["instructions"]; string achievementIconURL = (string)achievementDict["achievementIconURL"]; string action = (string)achievementDict["action"]; string name = (string)achievementDict["name"]; string message = (string)achievementDict["message"]; string limitText = (string)achievementDict["limitText"]; DateTime lastEarnedDate = new DateTime((Int64)achievementDict["lastEarnedDate"], DateTimeKind.Utc); IAchievementData achievementData = new AchievementData(identifier, importID, instructions, achievementIconURL, action, name, message, limitText, (int)mpointValue, isCustom, lastEarnedDate, (int)timesEarned, (int)unclaimedCount, (int)distance); return achievementData; } //This is a useful method you can call whenever you need to parse a JSON string into a the UserData custom class. public static UserData GetUserData(string jsonString) { Dictionary<string, object> userDict = Json.Deserialize(jsonString) as Dictionary<string, object>; bool isOptedOut = (bool)userDict["isOptedOut"]; bool isRegistered = (bool)userDict["isRegistered"]; bool isLoggedIn = (bool)userDict["isLoggedIn"]; long userPointBalance = (Int64)userDict["getPointBalance"]; long unclaimedAchievementCount = (Int64)userDict["getUnclaimedAchievementCount"]; long unclaimedAchievementValue = (Int64)userDict["getUnclaimedAchievementValue"]; string achievementsJSON = (string)userDict["getAchievementsJSON"]; string[] achievementsJSONArray = UnpackJSONArray(achievementsJSON); AchievementData[] achievementsArray = new AchievementData[achievementsJSONArray.Length]; for(int i = 0; i < achievementsJSONArray.Length; i++) { string achievement = achievementsJSONArray[i]; if(achievement == "") { break; } achievementsArray[i] = GetAchievementData(achievement) as AchievementData; } List<AchievementData> achievements = new List<AchievementData>(achievementsArray); string achievementsListJSON = (string)userDict["getAchievementsListJSON"]; string[] achievementsListJSONArray = UnpackJSONArray(achievementsListJSON); AchievementData[] achievementsListArray = new AchievementData[achievementsListJSONArray.Length]; for(int i = 0; i < achievementsListJSONArray.Length; i++) { string achievement = achievementsListJSONArray[i]; if(achievement == "") { break; } achievementsListArray[i] = GetAchievementData(achievement) as AchievementData; } List<AchievementData> achievementsList = new List<AchievementData>(achievementsListArray); UserData userData = new UserData(isOptedOut, isRegistered, isLoggedIn, (int)userPointBalance, (int)unclaimedAchievementCount, (int)unclaimedAchievementValue, achievements, achievementsList); return userData; } private static string[] UnpackJSONArray(string json) { string[] separatorArray = new string[] {"__"}; string[] JSONArray = json.Split(separatorArray, StringSplitOptions.None); return JSONArray; } }
namespace Microsoft.Protocols.TestSuites.MS_ASAIRS { using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using DataStructures = Microsoft.Protocols.TestSuites.Common.DataStructures; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// This scenario is designed to test the Attachments element and its sub elements in the AirSyncBase namespace, which is used by the Sync command, Search command and ItemOperations command to identify the data sent by and returned to client. /// </summary> [TestClass] public class S03_Attachment : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanUp() { TestClassBase.Cleanup(); } #endregion #region MSASAIRS_S03_TC01_FileReference_ZeroLengthString /// <summary> /// This case is designed to test if the client includes a zero-length string for the value of the FileReference (Fetch) element in an ItemOperations command request, the server responds with a protocol status error of 15. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S03_TC01_FileReference_ZeroLengthString() { #region Send a mail with normal attachment. string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.NormalAttachment, subject, body); #endregion #region Send an ItemOperations request with the value of FileReference element as a zero-length string. DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, null); // Send an ItemOperations request with the value of FileReference element as a zero-length string. ItemOperationsRequest request = TestSuiteHelper.CreateItemOperationsRequest(this.User2Information.InboxCollectionId, syncItem.ServerId, string.Empty, null, null); DataStructures.ItemOperationsStore itemOperationsStore = this.ASAIRSAdapter.ItemOperations(request, DeliveryMethodForFetch.Inline); Site.Assert.AreEqual<int>( 1, itemOperationsStore.Items.Count, "There should be 1 item in ItemOperations response."); #endregion #region Verify requirements // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R214"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R214 Site.CaptureRequirementIfAreEqual<string>( "15", itemOperationsStore.Items[0].Status, 214, @"[In FileReference (Fetch)] If the client includes a zero-length string for the value of this element [the FileReference (Fetch) element] in an ItemOperations command request, the server responds with a protocol status error of 15."); #endregion } #endregion #region MSASAIRS_S03_TC02_NormalAttachment /// <summary> /// This case is designed to test the method value 1 which specifies the attachment is a normal attachment. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S03_TC02_NormalAttachment() { #region Send a mail with normal attachment string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.NormalAttachment, subject, body); #endregion #region Verify requirements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, null); this.VerifyMethodElementValue(syncItem.Email, 1); DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, null, null); this.VerifyMethodElementValue(itemOperationsItem.Email, 1); if (Common.IsRequirementEnabled(53, this.Site)) { DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, null, null, null); this.VerifyMethodElementValue(searchItem.Email, 1); } // According to above steps, requirement MS-ASAIRS_R225 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R225"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R225 Site.CaptureRequirement( 225, @"[In Method (Attachment)] [The value] 1 [of the Method element] meaning ""Normal attachment"" specifies that the attachment is a normal attachment."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R160"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R160 Site.CaptureRequirementIfIsNotNull( ((Response.AttachmentsAttachment)syncItem.Email.Attachments.Items[0]).ContentId, 160, @"[In ContentId (Attachment)] The ContentId element is an optional child element of the Attachment element (section 2.2.2.7) that contains the unique object ID for an attachment."); this.Site.CaptureRequirementIfIsNotNull( ((Response.AttachmentsAttachment)syncItem.Email.Attachments.Items[0]).ContentId, 1343, @"[In ContentId (Attachment)] [The ContentId element is an optional child element of the Attachment element (section 2.2.2.7) that contains the unique identifier of the attachment, and] is used to reference the attachment within the item to which the attachment belongs."); #endregion } #endregion #region MSASAIRS_S03_TC03_EmbeddedMessageAttachment /// <summary> /// This case is designed to test the method value 5 which indicates that the attachment is an e-mail message, and that the attachment file has an .eml extension. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S03_TC03_EmbeddedMessageAttachment() { #region Send a mail with an e-mail messsage attachment string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.EmbeddedAttachment, subject, body); #endregion #region Verify requirements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, null); this.VerifyMethodElementValue(syncItem.Email, 5); DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, null, null); this.VerifyMethodElementValue(itemOperationsItem.Email, 5); if (Common.IsRequirementEnabled(53, this.Site)) { DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, null); this.VerifyMethodElementValue(searchItem.Email, 5); } // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R2299"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R2299 Site.CaptureRequirementIfIsTrue( ((Response.AttachmentsAttachment)syncItem.Email.Attachments.Items[0]).DisplayName.EndsWith(".eml", System.StringComparison.CurrentCultureIgnoreCase), 2299, @"[In Method (Attachment)] [The value] 5 [of the Method element] meaning ""Embedded message"" indicates that the attachment is an e-mail message, and that the attachment file has an .eml extension."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R100298"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R100298 Site.CaptureRequirementIfIsFalse( ((Response.AttachmentsAttachment)syncItem.Email.Attachments.Items[0]).IsInlineSpecified, 100298, @"[In IsInline (Attachment)] If the value[IsInline] is FALSE, then the attachment is not embedded in the message."); #endregion } #endregion #region MSASAIRS_S03_TC04_OLEAttachment /// <summary> /// This case is designed to test the method value 6 which indicates that the attachment is an embedded Object Linking and Embedding (OLE) object. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S03_TC04_OLEAttachment() { #region Send a mail with an embedded OLE object string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.AttachOLE, subject, body); #endregion #region Verify requirements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, null); this.VerifyMethodElementValue(syncItem.Email, 6); DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, null, null); this.VerifyMethodElementValue(itemOperationsItem.Email, 6); if (Common.IsRequirementEnabled(53, this.Site)) { DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, null); this.VerifyMethodElementValue(searchItem.Email, 6); } // According to above steps, requirement MS-ASAIRS_R230 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R230"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R230 Site.CaptureRequirement( 230, @"[In Method (Attachment)] [The value] 6 [of the Method element] meaning ""Attach OLE"" indicates that the attachment is an embedded Object Linking and Embedding (OLE) object, such as an inline image."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R100299"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R100299 Site.CaptureRequirementIfIsTrue( ((Response.AttachmentsAttachment)syncItem.Email.Attachments.Items[0]).IsInline, 100299, @"[In IsInline (Attachment)] If the value[IsInline] is TRUE, then the attachment is embedded in the message."); #endregion } #endregion #region private methods /// <summary> /// This method is used to verify whether the Method element is the expected value. /// </summary> /// <param name="email">The email item got from server.</param> /// <param name="methodValue">The expected value of Method element .</param> private void VerifyMethodElementValue(DataStructures.Email email, byte methodValue) { Site.Assert.IsNotNull( email.Attachments, "The Attachments element in response should not be null."); Site.Assert.IsNotNull( email.Attachments.Items, "The Attachment element in response should not be null."); Site.Assert.AreEqual<int>( 1, email.Attachments.Items.Length, "There should be only one Attachment element in response."); Site.Assert.IsNotNull( email.Attachments.Items[0], "The Attachment element in response should not be null."); Site.Assert.AreEqual<byte>( methodValue, ((Response.AttachmentsAttachment)email.Attachments.Items[0]).Method, "The value of Method element in response should be equal to the expected value."); } #endregion } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; namespace Cassandra { internal class M3PToken : IToken { public static readonly TokenFactory Factory = new M3PTokenFactory(); private readonly long _value; internal M3PToken(long value) { _value = value; } public int CompareTo(object obj) { var other = obj as M3PToken; long otherValue = other._value; return _value < otherValue ? -1 : (_value == otherValue) ? 0 : 1; } public override bool Equals(object obj) { if (this == obj) return true; if (obj == null || GetType() != obj.GetType()) return false; return _value == ((M3PToken) obj)._value; } public override int GetHashCode() { return (int) (_value ^ ((long) ((ulong) _value >> 32))); } public override string ToString() { return _value.ToString(); } internal class M3PTokenFactory : TokenFactory { public override IToken Parse(string tokenStr) { return new M3PToken(long.Parse(tokenStr)); } public override IToken Hash(byte[] partitionKey) { var v = Murmur(partitionKey); return new M3PToken(v == long.MinValue ? long.MaxValue : v); } /// <summary> /// Murmur hash it /// </summary> /// <returns></returns> private static long Murmur(byte[] bytes) { // This is an adapted version of the MurmurHash.hash3_x64_128 from Cassandra used // for M3P. Compared to that methods, there's a few inlining of arguments and we // only return the first 64-bits of the result since that's all M3P uses. //Convert to sbyte as in Java byte are signed sbyte[] data = (sbyte[])(Array)bytes; int offset = 0; int length = data.Length; int nblocks = length >> 4; // Process as 128-bit blocks. long h1 = 0; long h2 = 0; //Instead of using ulong for constants, use long values representing the same bits //Negated, same bits as ulong: 0x87c37b91114253d5L const long c1 = -0x783C846EEEBDAC2BL; const long c2 = 0x4cf5ad432745937fL; //---------- // body for (int i = 0; i < nblocks; i++) { long k1 = GetBlock(data, offset, i * 2 + 0); long k2 = GetBlock(data, offset, i * 2 + 1); k1 *= c1; k1 = Rotl64(k1, 31); k1 *= c2; h1 ^= k1; h1 = Rotl64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; k2 *= c2; k2 = Rotl64(k2, 33); k2 *= c1; h2 ^= k2; h2 = Rotl64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; } //---------- // tail // Advance offset to the unprocessed tail of the data. offset += nblocks * 16; { //context long k1 = 0; long k2 = 0; switch (length & 15) { case 15: k2 ^= ((long)data[offset + 14]) << 48; goto case 14; case 14: k2 ^= ((long)data[offset + 13]) << 40; goto case 13; case 13: k2 ^= ((long)data[offset + 12]) << 32; goto case 12; case 12: k2 ^= ((long)data[offset + 11]) << 24; goto case 11; case 11: k2 ^= ((long)data[offset + 10]) << 16; goto case 10; case 10: k2 ^= ((long)data[offset + 9 ]) << 8; goto case 9; case 9: k2 ^= ((long)data[offset + 8 ]) << 0; k2 *= c2; k2 = Rotl64(k2, 33); k2 *= c1; h2 ^= k2; goto case 8; case 8: k1 ^= ((long)data[offset + 7]) << 56; goto case 7; case 7: k1 ^= ((long)data[offset + 6]) << 48; goto case 6; case 6: k1 ^= ((long)data[offset + 5]) << 40; goto case 5; case 5: k1 ^= ((long)data[offset + 4]) << 32; goto case 4; case 4: k1 ^= ((long)data[offset + 3]) << 24; goto case 3; case 3: k1 ^= ((long)data[offset + 2]) << 16; goto case 2; case 2: k1 ^= ((long)data[offset + 1]) << 8; goto case 1; case 1: k1 ^= ((long)data[offset]); k1 *= c1; k1 = Rotl64(k1, 31); k1 *= c2; h1 ^= k1; break; } //---------- // finalization h1 ^= length; h2 ^= length; h1 += h2; h2 += h1; h1 = Fmix(h1); h2 = Fmix(h2); h1 += h2; return h1; } } private static long GetBlock(sbyte[] key, int offset, int index) { int i8 = index << 3; int blockOffset = offset + i8; return ((long)key[blockOffset + 0] & 0xff) + (((long)key[blockOffset + 1] & 0xff) << 8) + (((long)key[blockOffset + 2] & 0xff) << 16) + (((long)key[blockOffset + 3] & 0xff) << 24) + (((long)key[blockOffset + 4] & 0xff) << 32) + (((long)key[blockOffset + 5] & 0xff) << 40) + (((long)key[blockOffset + 6] & 0xff) << 48) + (((long)key[blockOffset + 7] & 0xff) << 56); } private static long Rotl64(long v, int n) { return ((v << n) | ((long)((ulong)v >> (64 - n)))); } private static long Fmix(long k) { k ^= (long)((ulong)k >> 33); //Negated, same bits as ulong 0xff51afd7ed558ccdL k *= -0xAE502812AA7333; k ^= (long)((ulong)k >> 33); //Negated, same bits as ulong 0xc4ceb9fe1a85ec53L k *= -0x3B314601E57A13AD; k ^= (long)((ulong)k >> 33); return k; } } } }
// Win32.cs // By Joe Esposito using System; using System.Drawing; using System.Runtime.InteropServices; namespace WindowFinder { /// <summary> /// Win32 API. /// </summary> internal static class Win32 { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct POINTAPI { public int x; public int y; } // Type definitions for Windows' basic types. public const int ANYSIZE_ARRAY = unchecked((int)(1)); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct RECT { public int left; public int top; public int right; public int bottom; } /// <summary> /// Gets the text of the specified window. /// </summary> internal static string GetWindowText(IntPtr hWnd) { int cch; IntPtr lpString; string sResult; // !!!!! System.Text.Encoding if(IsWindow(hWnd) == 0) return ""; if(IsWindowUnicode(hWnd) != 0) { // Allocate new Unicode string lpString = Marshal.AllocHGlobal((cch = (GetWindowTextLengthW(hWnd) + 1)) * 2); // Get window Unicode text GetWindowTextW(hWnd, lpString, cch); // Get managed string from Unicode string sResult = Marshal.PtrToStringUni(lpString, cch); // Free allocated Unicode string Marshal.FreeHGlobal(lpString); lpString = IntPtr.Zero; // Return managed string return sResult; } else { // Allocate new ANSI string lpString = Marshal.AllocHGlobal((cch = (GetWindowTextLengthA(hWnd) + 1))); // Get window ANSI text GetWindowTextA(hWnd, lpString, cch); // Get managed string from ANSI string sResult = Marshal.PtrToStringAnsi(lpString, cch); // Free allocated ANSI string Marshal.FreeHGlobal(lpString); lpString = IntPtr.Zero; // Return managed string return sResult; } } /// <summary> /// Gets the class name of the specified window. /// </summary> internal static string GetClassName(IntPtr hWnd) { const int windowClassNameLength = 255; int cch; IntPtr lpString; string sResult; // !!!!! System.Text.Encoding if(IsWindow(hWnd) == 0) return ""; if(IsWindowUnicode(hWnd) != 0) { // Allocate new Unicode string lpString = Marshal.AllocHGlobal((cch = (windowClassNameLength + 1)) * 2); // Get window class Unicode text GetClassNameW(hWnd, lpString, cch); // Get managed string from Unicode string sResult = Marshal.PtrToStringUni(lpString, cch); // Free allocated Unicode string Marshal.FreeHGlobal(lpString); lpString = IntPtr.Zero; // Return managed string return sResult; } else { // Allocate new ANSI string lpString = Marshal.AllocHGlobal((cch = (GetWindowTextLengthA(hWnd) + 1))); // Get window class ANSI text GetClassNameA(hWnd, lpString, cch); // Get managed string from ANSI string sResult = Marshal.PtrToStringAnsi(lpString, cch); // Free allocated ANSI string Marshal.FreeHGlobal(lpString); lpString = IntPtr.Zero; // Return managed string return sResult; } } /// <summary> /// Retrieves the window from the client point. /// </summary> internal static IntPtr WindowFromPoint(IntPtr hClientWnd, int xPoint, int yPoint) { POINTAPI pt; pt.x = xPoint; pt.y = yPoint; ClientToScreen(hClientWnd, ref pt); return (IntPtr)WindowFromPoint(pt.x, pt.y); } /// <summary> /// Highlights the specified window. /// </summary> internal static bool HighlightWindow(IntPtr hWnd) { IntPtr hDC; // The DC of the window. RECT rt = new RECT(); // Rectangle area of the window. // Get the window DC of the window. if((hDC = (IntPtr)GetWindowDC(hWnd)) == IntPtr.Zero) return false; // Get the screen coordinates of the rectangle of the window. GetWindowRect(hWnd, ref rt); rt.right -= rt.left; rt.left = 0; rt.bottom -= rt.top; rt.top = 0; // Draw a border in the DC covering the entire window area of the window. IntPtr hRgn = (IntPtr)CreateRectRgnIndirect(ref rt); GetWindowRgn(hWnd, hRgn); SetROP2(hDC, R2_NOT); FrameRgn(hDC, hRgn, (IntPtr)GetStockObject(WHITE_BRUSH), 3, 3); DeleteObject(hRgn); // Finally release the DC. ReleaseDC(hWnd, hDC); return true; } /// <summary> /// Determines whether the two windows are related. /// </summary> internal static bool IsRelativeWindow(IntPtr hWnd, IntPtr hRelativeWindow, bool bProcessAncestor) { int dwProcess = new int(), dwProcessOwner = new int(); int dwThread = new int(), dwThreadOwner = new int(); ; // Failsafe if(hWnd == IntPtr.Zero) return false; if(hRelativeWindow == IntPtr.Zero) return false; if(hWnd == hRelativeWindow) return true; // Get processes and threads dwThread = GetWindowThreadProcessId(hWnd, ref dwProcess); dwThreadOwner = GetWindowThreadProcessId(hRelativeWindow, ref dwProcessOwner); // Get relative info if(bProcessAncestor) return (dwProcess == dwProcessOwner); return (dwThread == dwThreadOwner); } [DllImport("user32", EntryPoint = "IsWindow", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] internal static extern int IsWindow(IntPtr hWnd); [DllImport("user32", EntryPoint = "IsWindowUnicode", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] internal static extern int IsWindowUnicode(IntPtr hWnd); [DllImport("user32", EntryPoint = "SetCapture", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] internal static extern int SetCapture(IntPtr hWnd); [DllImport("user32", EntryPoint = "ClientToScreen", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int ClientToScreen(IntPtr hWnd, ref POINTAPI lpPoint); [DllImport("user32", EntryPoint = "MapWindowPoints", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int MapWindowPoints(IntPtr hwndFrom, IntPtr hwndTo, ref RECT lprt, int cPoints); [DllImport("user32", EntryPoint = "MapWindowPoints", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int MapWindowPoints(IntPtr hwndFrom, IntPtr hwndTo, ref POINTAPI lppt, int cPoints); [DllImport("user32", EntryPoint = "ChildWindowFromPoint", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int ChildWindowFromPoint(IntPtr hWnd, int xPoint, int yPoint); [DllImport("user32", EntryPoint = "GetParent", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport("user32", EntryPoint = "GetWindowTextLengthA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowTextLengthA(IntPtr hWnd); [DllImport("user32", EntryPoint = "GetWindowTextLengthW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowTextLengthW(IntPtr hWnd); [DllImport("user32", EntryPoint = "GetWindowTextA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowTextA(IntPtr hWnd, IntPtr lpString, int cch); [DllImport("user32", EntryPoint = "GetWindowTextW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowTextW(IntPtr hWnd, IntPtr lpString, int cch); [DllImport("user32", EntryPoint = "GetClassNameA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetClassNameA(IntPtr hWnd, IntPtr lpClassName, int nMaxCount); [DllImport("user32", EntryPoint = "GetClassNameW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetClassNameW(IntPtr hWnd, IntPtr lpClassName, int nMaxCount); [DllImport("user32", EntryPoint = "GetWindowDC", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowDC(IntPtr hWnd); [DllImport("user32", EntryPoint = "GetWindowRect", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowRect(IntPtr hWnd, ref RECT lpRect); [DllImport("gdi32", EntryPoint = "CreateRectRgnIndirect", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int CreateRectRgnIndirect(ref RECT lpRect); [DllImport("user32", EntryPoint = "WindowFromPoint", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int WindowFromPoint(int xPoint, int yPoint); [DllImport("user32", EntryPoint = "GetWindowRgn", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn); [DllImport("gdi32", EntryPoint = "SetROP2", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int SetROP2(IntPtr hdc, int nDrawMode); [DllImport("gdi32", EntryPoint = "FrameRgn", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int FrameRgn(IntPtr hdc, IntPtr hRgn, IntPtr hBrush, int nWidth, int nHeight); [DllImport("gdi32", EntryPoint = "GetStockObject", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetStockObject(int nIndex); [DllImport("user32", EntryPoint = "GetWindowThreadProcessId", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int GetWindowThreadProcessId(IntPtr hWnd, ref int lpdwProcessId); [DllImport("gdi32", EntryPoint = "DeleteObject", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int DeleteObject(IntPtr hObject); [DllImport("user32", EntryPoint = "ReleaseDC", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = false, CallingConvention = CallingConvention.Winapi)] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hdc); // Binary raster ops public const int R2_NOT = unchecked((int)(6));// Dn // Stock Logical Objects public const int WHITE_BRUSH = unchecked((int)(0)); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Extensions; using osu.Framework.Graphics.Textures; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Beatmaps.Formats; using osu.Game.Database; using osu.Game.IO.Archives; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.Notifications; using osu.Game.Rulesets; namespace osu.Game.Beatmaps { /// <summary> /// Handles the storage and retrieval of Beatmaps/WorkingBeatmaps. /// </summary> public partial class BeatmapManager : ArchiveModelManager<BeatmapSetInfo, BeatmapSetFileInfo> { /// <summary> /// Fired when a single difficulty has been hidden. /// </summary> public event Action<BeatmapInfo> BeatmapHidden; /// <summary> /// Fired when a single difficulty has been restored. /// </summary> public event Action<BeatmapInfo> BeatmapRestored; /// <summary> /// Fired when a beatmap download begins. /// </summary> public event Action<DownloadBeatmapSetRequest> BeatmapDownloadBegan; /// <summary> /// Fired when a beatmap download is interrupted, due to user cancellation or other failures. /// </summary> public event Action<DownloadBeatmapSetRequest> BeatmapDownloadFailed; /// <summary> /// A default representation of a WorkingBeatmap to use when no beatmap is available. /// </summary> public readonly WorkingBeatmap DefaultBeatmap; public override string[] HandledExtensions => new[] { ".osz" }; protected override string[] HashableFileTypes => new[] { ".osu" }; protected override string ImportFromStablePath => "Songs"; private readonly RulesetStore rulesets; private readonly BeatmapStore beatmaps; private readonly IAPIProvider api; private readonly AudioManager audioManager; private readonly GameHost host; private readonly List<DownloadBeatmapSetRequest> currentDownloads = new List<DownloadBeatmapSetRequest>(); public BeatmapManager(Storage storage, IDatabaseContextFactory contextFactory, RulesetStore rulesets, IAPIProvider api, AudioManager audioManager, GameHost host = null, WorkingBeatmap defaultBeatmap = null) : base(storage, contextFactory, new BeatmapStore(contextFactory), host) { this.rulesets = rulesets; this.api = api; this.audioManager = audioManager; this.host = host; DefaultBeatmap = defaultBeatmap; beatmaps = (BeatmapStore)ModelStore; beatmaps.BeatmapHidden += b => BeatmapHidden?.Invoke(b); beatmaps.BeatmapRestored += b => BeatmapRestored?.Invoke(b); } protected override void Populate(BeatmapSetInfo beatmapSet, ArchiveReader archive) { if (archive != null) beatmapSet.Beatmaps = createBeatmapDifficulties(archive); foreach (BeatmapInfo b in beatmapSet.Beatmaps) { // remove metadata from difficulties where it matches the set if (beatmapSet.Metadata.Equals(b.Metadata)) b.Metadata = null; b.BeatmapSet = beatmapSet; } validateOnlineIds(beatmapSet); foreach (BeatmapInfo b in beatmapSet.Beatmaps) fetchAndPopulateOnlineValues(b); } protected override void PreImport(BeatmapSetInfo beatmapSet) { if (beatmapSet.Beatmaps.Any(b => b.BaseDifficulty == null)) throw new InvalidOperationException($"Cannot import {nameof(BeatmapInfo)} with null {nameof(BeatmapInfo.BaseDifficulty)}."); // check if a set already exists with the same online id, delete if it does. if (beatmapSet.OnlineBeatmapSetID != null) { var existingOnlineId = beatmaps.ConsumableItems.FirstOrDefault(b => b.OnlineBeatmapSetID == beatmapSet.OnlineBeatmapSetID); if (existingOnlineId != null) { Delete(existingOnlineId); beatmaps.PurgeDeletable(s => s.ID == existingOnlineId.ID); Logger.Log($"Found existing beatmap set with same OnlineBeatmapSetID ({beatmapSet.OnlineBeatmapSetID}). It has been purged.", LoggingTarget.Database); } } } private void validateOnlineIds(BeatmapSetInfo beatmapSet) { var beatmapIds = beatmapSet.Beatmaps.Where(b => b.OnlineBeatmapID.HasValue).Select(b => b.OnlineBeatmapID).ToList(); // ensure all IDs are unique if (beatmapIds.GroupBy(b => b).Any(g => g.Count() > 1)) { resetIds(); return; } // find any existing beatmaps in the database that have matching online ids var existingBeatmaps = QueryBeatmaps(b => beatmapIds.Contains(b.OnlineBeatmapID)).ToList(); if (existingBeatmaps.Count > 0) { // reset the import ids (to force a re-fetch) *unless* they match the candidate CheckForExisting set. // we can ignore the case where the new ids are contained by the CheckForExisting set as it will either be used (import skipped) or deleted. var existing = CheckForExisting(beatmapSet); if (existing == null || existingBeatmaps.Any(b => !existing.Beatmaps.Contains(b))) resetIds(); } void resetIds() => beatmapSet.Beatmaps.ForEach(b => b.OnlineBeatmapID = null); } /// <summary> /// Downloads a beatmap. /// This will post notifications tracking progress. /// </summary> /// <param name="beatmapSetInfo">The <see cref="BeatmapSetInfo"/> to be downloaded.</param> /// <param name="noVideo">Whether the beatmap should be downloaded without video. Defaults to false.</param> /// <returns>Downloading can happen</returns> public bool Download(BeatmapSetInfo beatmapSetInfo, bool noVideo = false) { var existing = GetExistingDownload(beatmapSetInfo); if (existing != null || api == null) return false; var downloadNotification = new DownloadNotification { Text = $"Downloading {beatmapSetInfo}", }; var request = new DownloadBeatmapSetRequest(beatmapSetInfo, noVideo); request.DownloadProgressed += progress => { downloadNotification.State = ProgressNotificationState.Active; downloadNotification.Progress = progress; }; request.Success += filename => { Task.Factory.StartNew(() => { // This gets scheduled back to the update thread, but we want the import to run in the background. Import(downloadNotification, filename); currentDownloads.Remove(request); }, TaskCreationOptions.LongRunning); }; request.Failure += error => { BeatmapDownloadFailed?.Invoke(request); if (error is OperationCanceledException) return; downloadNotification.State = ProgressNotificationState.Cancelled; Logger.Error(error, "Beatmap download failed!"); currentDownloads.Remove(request); }; downloadNotification.CancelRequested += () => { request.Cancel(); currentDownloads.Remove(request); downloadNotification.State = ProgressNotificationState.Cancelled; return true; }; currentDownloads.Add(request); PostNotification?.Invoke(downloadNotification); // don't run in the main api queue as this is a long-running task. Task.Factory.StartNew(() => { try { request.Perform(api); } catch (Exception e) { // no need to handle here as exceptions will filter down to request.Failure above. } }, TaskCreationOptions.LongRunning); BeatmapDownloadBegan?.Invoke(request); return true; } /// <summary> /// Get an existing download request if it exists. /// </summary> /// <param name="beatmap">The <see cref="BeatmapSetInfo"/> whose download request is wanted.</param> /// <returns>The <see cref="DownloadBeatmapSetRequest"/> object if it exists, or null.</returns> public DownloadBeatmapSetRequest GetExistingDownload(BeatmapSetInfo beatmap) => currentDownloads.Find(d => d.BeatmapSet.OnlineBeatmapSetID == beatmap.OnlineBeatmapSetID); /// <summary> /// Delete a beatmap difficulty. /// </summary> /// <param name="beatmap">The beatmap difficulty to hide.</param> public void Hide(BeatmapInfo beatmap) => beatmaps.Hide(beatmap); /// <summary> /// Restore a beatmap difficulty. /// </summary> /// <param name="beatmap">The beatmap difficulty to restore.</param> public void Restore(BeatmapInfo beatmap) => beatmaps.Restore(beatmap); /// <summary> /// Retrieve a <see cref="WorkingBeatmap"/> instance for the provided <see cref="BeatmapInfo"/> /// </summary> /// <param name="beatmapInfo">The beatmap to lookup.</param> /// <param name="previous">The currently loaded <see cref="WorkingBeatmap"/>. Allows for optimisation where elements are shared with the new beatmap. May be returned if beatmapInfo requested matches</param> /// <returns>A <see cref="WorkingBeatmap"/> instance correlating to the provided <see cref="BeatmapInfo"/>.</returns> public WorkingBeatmap GetWorkingBeatmap(BeatmapInfo beatmapInfo, WorkingBeatmap previous = null) { if (beatmapInfo?.ID > 0 && previous != null && previous.BeatmapInfo?.ID == beatmapInfo.ID) return previous; if (beatmapInfo?.BeatmapSet == null || beatmapInfo == DefaultBeatmap?.BeatmapInfo) return DefaultBeatmap; if (beatmapInfo.Metadata == null) beatmapInfo.Metadata = beatmapInfo.BeatmapSet.Metadata; WorkingBeatmap working = new BeatmapManagerWorkingBeatmap(Files.Store, new LargeTextureStore(host?.CreateTextureLoaderStore(Files.Store)), beatmapInfo, audioManager); previous?.TransferTo(working); return working; } /// <summary> /// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>The first result for the provided query, or null if no results were found.</returns> public BeatmapSetInfo QueryBeatmapSet(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().FirstOrDefault(query); protected override bool CanUndelete(BeatmapSetInfo existing, BeatmapSetInfo import) { if (!base.CanUndelete(existing, import)) return false; var existingIds = existing.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i); var importIds = import.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i); // force re-import if we are not in a sane state. return existing.OnlineBeatmapSetID == import.OnlineBeatmapSetID && existingIds.SequenceEqual(importIds); } /// <summary> /// Returns a list of all usable <see cref="BeatmapSetInfo"/>s. /// </summary> /// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns> public List<BeatmapSetInfo> GetAllUsableBeatmapSets() => GetAllUsableBeatmapSetsEnumerable().ToList(); /// <summary> /// Returns a list of all usable <see cref="BeatmapSetInfo"/>s. /// </summary> /// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns> public IQueryable<BeatmapSetInfo> GetAllUsableBeatmapSetsEnumerable() => beatmaps.ConsumableItems.Where(s => !s.DeletePending && !s.Protected); /// <summary> /// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>Results from the provided query.</returns> public IEnumerable<BeatmapSetInfo> QueryBeatmapSets(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().Where(query); /// <summary> /// Perform a lookup query on available <see cref="BeatmapInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>The first result for the provided query, or null if no results were found.</returns> public BeatmapInfo QueryBeatmap(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().FirstOrDefault(query); /// <summary> /// Perform a lookup query on available <see cref="BeatmapInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>Results from the provided query.</returns> public IQueryable<BeatmapInfo> QueryBeatmaps(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().Where(query); protected override BeatmapSetInfo CreateModel(ArchiveReader reader) { // let's make sure there are actually .osu files to import. string mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu")); if (string.IsNullOrEmpty(mapName)) { Logger.Log($"No beatmap files found in the beatmap archive ({reader.Name}).", LoggingTarget.Database); return null; } Beatmap beatmap; using (var stream = new StreamReader(reader.GetStream(mapName))) beatmap = Decoder.GetDecoder<Beatmap>(stream).Decode(stream); return new BeatmapSetInfo { OnlineBeatmapSetID = beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID, Beatmaps = new List<BeatmapInfo>(), Metadata = beatmap.Metadata, }; } /// <summary> /// Create all required <see cref="BeatmapInfo"/>s for the provided archive. /// </summary> private List<BeatmapInfo> createBeatmapDifficulties(ArchiveReader reader) { var beatmapInfos = new List<BeatmapInfo>(); foreach (var name in reader.Filenames.Where(f => f.EndsWith(".osu"))) { using (var raw = reader.GetStream(name)) using (var ms = new MemoryStream()) //we need a memory stream so we can seek and shit using (var sr = new StreamReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = Decoder.GetDecoder<Beatmap>(sr); IBeatmap beatmap = decoder.Decode(sr); beatmap.BeatmapInfo.Path = name; beatmap.BeatmapInfo.Hash = ms.ComputeSHA2Hash(); beatmap.BeatmapInfo.MD5Hash = ms.ComputeMD5Hash(); var ruleset = rulesets.GetRuleset(beatmap.BeatmapInfo.RulesetID); beatmap.BeatmapInfo.Ruleset = ruleset; // TODO: this should be done in a better place once we actually need to dynamically update it. beatmap.BeatmapInfo.StarDifficulty = ruleset?.CreateInstance().CreateDifficultyCalculator(new DummyConversionBeatmap(beatmap)).Calculate().StarRating ?? 0; beatmapInfos.Add(beatmap.BeatmapInfo); } } return beatmapInfos; } /// <summary> /// Query the API to populate missing values like OnlineBeatmapID / OnlineBeatmapSetID or (Rank-)Status. /// </summary> /// <param name="beatmap">The beatmap to populate.</param> /// <param name="otherBeatmaps">The other beatmaps contained within this set.</param> /// <param name="force">Whether to re-query if the provided beatmap already has populated values.</param> /// <returns>True if population was successful.</returns> private bool fetchAndPopulateOnlineValues(BeatmapInfo beatmap, bool force = false) { if (api?.State != APIState.Online) return false; if (!force && beatmap.OnlineBeatmapID != null && beatmap.BeatmapSet.OnlineBeatmapSetID != null && beatmap.Status != BeatmapSetOnlineStatus.None && beatmap.BeatmapSet.Status != BeatmapSetOnlineStatus.None) return true; Logger.Log("Attempting online lookup for the missing values...", LoggingTarget.Database); try { var req = new GetBeatmapRequest(beatmap); req.Perform(api); var res = req.Result; Logger.Log($"Successfully mapped to {res.OnlineBeatmapSetID} / {res.OnlineBeatmapID}.", LoggingTarget.Database); beatmap.Status = res.Status; beatmap.BeatmapSet.Status = res.BeatmapSet.Status; beatmap.BeatmapSet.OnlineBeatmapSetID = res.OnlineBeatmapSetID; beatmap.OnlineBeatmapID = res.OnlineBeatmapID; return true; } catch (Exception e) { Logger.Log($"Failed ({e})", LoggingTarget.Database); return false; } } /// <summary> /// A dummy WorkingBeatmap for the purpose of retrieving a beatmap for star difficulty calculation. /// </summary> private class DummyConversionBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; public DummyConversionBeatmap(IBeatmap beatmap) : base(beatmap.BeatmapInfo) { this.beatmap = beatmap; } protected override IBeatmap GetBeatmap() => beatmap; protected override Texture GetBackground() => null; protected override Track GetTrack() => null; } private class DownloadNotification : ProgressNotification { public override bool IsImportant => false; protected override Notification CreateCompletionNotification() => new SilencedProgressCompletionNotification { Activated = CompletionClickAction, Text = CompletionText }; private class SilencedProgressCompletionNotification : ProgressCompletionNotification { public override bool IsImportant => false; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/cancellation_policy.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking { /// <summary>Holder for reflection information generated from booking/cancellation_policy.proto</summary> public static partial class CancellationPolicyReflection { #region Descriptor /// <summary>File descriptor for booking/cancellation_policy.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CancellationPolicyReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiFib29raW5nL2NhbmNlbGxhdGlvbl9wb2xpY3kucHJvdG8SE2hvbG1zLnR5", "cGVzLmJvb2tpbmcaNmJvb2tpbmcvaW5kaWNhdG9ycy9jYW5jZWxsYXRpb25f", "cG9saWN5X2luZGljYXRvci5wcm90bxonYm9va2luZy9jYW5jZWxsYXRpb25f", "ZmVlX2NhdGVnb3J5LnByb3RvGiFwcmltaXRpdmUvZml4ZWRfcG9pbnRfcmF0", "aW8ucHJvdG8aH3ByaW1pdGl2ZS9tb25ldGFyeV9hbW91bnQucHJvdG8ihwMK", "EkNhbmNlbGxhdGlvblBvbGljeRJOCgllbnRpdHlfaWQYASABKAsyOy5ob2xt", "cy50eXBlcy5ib29raW5nLmluZGljYXRvcnMuQ2FuY2VsbGF0aW9uUG9saWN5", "SW5kaWNhdG9yEhMKC2Rlc2NyaXB0aW9uGAIgASgJEhcKD25vX3BlbmFsdHlf", "ZGF5cxgDIAEoBRJCCgxmZWVfY2F0ZWdvcnkYBCABKA4yLC5ob2xtcy50eXBl", "cy5ib29raW5nLkNhbmNlbGxhdGlvbkZlZUNhdGVnb3J5EkYKF2NhbmNlbGxh", "dGlvbl9mZWVfYW1vdW50GAUgASgLMiUuaG9sbXMudHlwZXMucHJpbWl0aXZl", "Lk1vbmV0YXJ5QW1vdW50EkUKFWNhbmNlbGxhdGlvbl9mZWVfcmF0ZRgGIAEo", "CzImLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5GaXhlZFBvaW50UmF0aW8SIAoY", "Y2FuY2VsbGF0aW9uX3BvbGljeV90ZXh0GAcgASgJQh9aB2Jvb2tpbmeqAhNI", "T0xNUy5UeXBlcy5Cb29raW5nYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.CancellationFeeCategoryReflection.Descriptor, global::HOLMS.Types.Primitive.FixedPointRatioReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.CancellationPolicy), global::HOLMS.Types.Booking.CancellationPolicy.Parser, new[]{ "EntityId", "Description", "NoPenaltyDays", "FeeCategory", "CancellationFeeAmount", "CancellationFeeRate", "CancellationPolicyText" }, null, null, null) })); } #endregion } #region Messages public sealed partial class CancellationPolicy : pb::IMessage<CancellationPolicy> { private static readonly pb::MessageParser<CancellationPolicy> _parser = new pb::MessageParser<CancellationPolicy>(() => new CancellationPolicy()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CancellationPolicy> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.CancellationPolicyReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CancellationPolicy() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CancellationPolicy(CancellationPolicy other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; description_ = other.description_; noPenaltyDays_ = other.noPenaltyDays_; feeCategory_ = other.feeCategory_; CancellationFeeAmount = other.cancellationFeeAmount_ != null ? other.CancellationFeeAmount.Clone() : null; CancellationFeeRate = other.cancellationFeeRate_ != null ? other.CancellationFeeRate.Clone() : null; cancellationPolicyText_ = other.cancellationPolicyText_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CancellationPolicy Clone() { return new CancellationPolicy(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 2; private string description_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "no_penalty_days" field.</summary> public const int NoPenaltyDaysFieldNumber = 3; private int noPenaltyDays_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NoPenaltyDays { get { return noPenaltyDays_; } set { noPenaltyDays_ = value; } } /// <summary>Field number for the "fee_category" field.</summary> public const int FeeCategoryFieldNumber = 4; private global::HOLMS.Types.Booking.CancellationFeeCategory feeCategory_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.CancellationFeeCategory FeeCategory { get { return feeCategory_; } set { feeCategory_ = value; } } /// <summary>Field number for the "cancellation_fee_amount" field.</summary> public const int CancellationFeeAmountFieldNumber = 5; private global::HOLMS.Types.Primitive.MonetaryAmount cancellationFeeAmount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount CancellationFeeAmount { get { return cancellationFeeAmount_; } set { cancellationFeeAmount_ = value; } } /// <summary>Field number for the "cancellation_fee_rate" field.</summary> public const int CancellationFeeRateFieldNumber = 6; private global::HOLMS.Types.Primitive.FixedPointRatio cancellationFeeRate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.FixedPointRatio CancellationFeeRate { get { return cancellationFeeRate_; } set { cancellationFeeRate_ = value; } } /// <summary>Field number for the "cancellation_policy_text" field.</summary> public const int CancellationPolicyTextFieldNumber = 7; private string cancellationPolicyText_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CancellationPolicyText { get { return cancellationPolicyText_; } set { cancellationPolicyText_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CancellationPolicy); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CancellationPolicy other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (Description != other.Description) return false; if (NoPenaltyDays != other.NoPenaltyDays) return false; if (FeeCategory != other.FeeCategory) return false; if (!object.Equals(CancellationFeeAmount, other.CancellationFeeAmount)) return false; if (!object.Equals(CancellationFeeRate, other.CancellationFeeRate)) return false; if (CancellationPolicyText != other.CancellationPolicyText) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (NoPenaltyDays != 0) hash ^= NoPenaltyDays.GetHashCode(); if (FeeCategory != 0) hash ^= FeeCategory.GetHashCode(); if (cancellationFeeAmount_ != null) hash ^= CancellationFeeAmount.GetHashCode(); if (cancellationFeeRate_ != null) hash ^= CancellationFeeRate.GetHashCode(); if (CancellationPolicyText.Length != 0) hash ^= CancellationPolicyText.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (Description.Length != 0) { output.WriteRawTag(18); output.WriteString(Description); } if (NoPenaltyDays != 0) { output.WriteRawTag(24); output.WriteInt32(NoPenaltyDays); } if (FeeCategory != 0) { output.WriteRawTag(32); output.WriteEnum((int) FeeCategory); } if (cancellationFeeAmount_ != null) { output.WriteRawTag(42); output.WriteMessage(CancellationFeeAmount); } if (cancellationFeeRate_ != null) { output.WriteRawTag(50); output.WriteMessage(CancellationFeeRate); } if (CancellationPolicyText.Length != 0) { output.WriteRawTag(58); output.WriteString(CancellationPolicyText); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (NoPenaltyDays != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NoPenaltyDays); } if (FeeCategory != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) FeeCategory); } if (cancellationFeeAmount_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CancellationFeeAmount); } if (cancellationFeeRate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CancellationFeeRate); } if (CancellationPolicyText.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CancellationPolicyText); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CancellationPolicy other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.Description.Length != 0) { Description = other.Description; } if (other.NoPenaltyDays != 0) { NoPenaltyDays = other.NoPenaltyDays; } if (other.FeeCategory != 0) { FeeCategory = other.FeeCategory; } if (other.cancellationFeeAmount_ != null) { if (cancellationFeeAmount_ == null) { cancellationFeeAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } CancellationFeeAmount.MergeFrom(other.CancellationFeeAmount); } if (other.cancellationFeeRate_ != null) { if (cancellationFeeRate_ == null) { cancellationFeeRate_ = new global::HOLMS.Types.Primitive.FixedPointRatio(); } CancellationFeeRate.MergeFrom(other.CancellationFeeRate); } if (other.CancellationPolicyText.Length != 0) { CancellationPolicyText = other.CancellationPolicyText; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } input.ReadMessage(entityId_); break; } case 18: { Description = input.ReadString(); break; } case 24: { NoPenaltyDays = input.ReadInt32(); break; } case 32: { feeCategory_ = (global::HOLMS.Types.Booking.CancellationFeeCategory) input.ReadEnum(); break; } case 42: { if (cancellationFeeAmount_ == null) { cancellationFeeAmount_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(cancellationFeeAmount_); break; } case 50: { if (cancellationFeeRate_ == null) { cancellationFeeRate_ = new global::HOLMS.Types.Primitive.FixedPointRatio(); } input.ReadMessage(cancellationFeeRate_); break; } case 58: { CancellationPolicyText = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: A1015Response.txt #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace DolphinServer.ProtoEntity { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class A1015Response { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_A1015Response__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1015Response, global::DolphinServer.ProtoEntity.A1015Response.Builder> internal__static_A1015Response__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static A1015Response() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFBMTAxNVJlc3BvbnNlLnR4dCJSCg1BMTAxNVJlc3BvbnNlEhEKCUVycm9y", "SW5mbxgBIAEoCRIRCglFcnJvckNvZGUYAiABKAUSCwoDVWlkGAMgASgJEg4K", "Bkh1VHlwZRgEIAEoBUIcqgIZRG9scGhpblNlcnZlci5Qcm90b0VudGl0eQ==")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_A1015Response__Descriptor = Descriptor.MessageTypes[0]; internal__static_A1015Response__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A1015Response, global::DolphinServer.ProtoEntity.A1015Response.Builder>(internal__static_A1015Response__Descriptor, new string[] { "ErrorInfo", "ErrorCode", "Uid", "HuType", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class A1015Response : pb::GeneratedMessage<A1015Response, A1015Response.Builder> { private A1015Response() { } private static readonly A1015Response defaultInstance = new A1015Response().MakeReadOnly(); private static readonly string[] _a1015ResponseFieldNames = new string[] { "ErrorCode", "ErrorInfo", "HuType", "Uid" }; private static readonly uint[] _a1015ResponseFieldTags = new uint[] { 16, 10, 32, 26 }; public static A1015Response DefaultInstance { get { return defaultInstance; } } public override A1015Response DefaultInstanceForType { get { return DefaultInstance; } } protected override A1015Response ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::DolphinServer.ProtoEntity.Proto.A1015Response.internal__static_A1015Response__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<A1015Response, A1015Response.Builder> InternalFieldAccessors { get { return global::DolphinServer.ProtoEntity.Proto.A1015Response.internal__static_A1015Response__FieldAccessorTable; } } public const int ErrorInfoFieldNumber = 1; private bool hasErrorInfo; private string errorInfo_ = ""; public bool HasErrorInfo { get { return hasErrorInfo; } } public string ErrorInfo { get { return errorInfo_; } } public const int ErrorCodeFieldNumber = 2; private bool hasErrorCode; private int errorCode_; public bool HasErrorCode { get { return hasErrorCode; } } public int ErrorCode { get { return errorCode_; } } public const int UidFieldNumber = 3; private bool hasUid; private string uid_ = ""; public bool HasUid { get { return hasUid; } } public string Uid { get { return uid_; } } public const int HuTypeFieldNumber = 4; private bool hasHuType; private int huType_; public bool HasHuType { get { return hasHuType; } } public int HuType { get { return huType_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _a1015ResponseFieldNames; if (hasErrorInfo) { output.WriteString(1, field_names[1], ErrorInfo); } if (hasErrorCode) { output.WriteInt32(2, field_names[0], ErrorCode); } if (hasUid) { output.WriteString(3, field_names[3], Uid); } if (hasHuType) { output.WriteInt32(4, field_names[2], HuType); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasErrorInfo) { size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo); } if (hasErrorCode) { size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode); } if (hasUid) { size += pb::CodedOutputStream.ComputeStringSize(3, Uid); } if (hasHuType) { size += pb::CodedOutputStream.ComputeInt32Size(4, HuType); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static A1015Response ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1015Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1015Response ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static A1015Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static A1015Response ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1015Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static A1015Response ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static A1015Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static A1015Response ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static A1015Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private A1015Response MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(A1015Response prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<A1015Response, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(A1015Response cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private A1015Response result; private A1015Response PrepareBuilder() { if (resultIsReadOnly) { A1015Response original = result; result = new A1015Response(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override A1015Response MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::DolphinServer.ProtoEntity.A1015Response.Descriptor; } } public override A1015Response DefaultInstanceForType { get { return global::DolphinServer.ProtoEntity.A1015Response.DefaultInstance; } } public override A1015Response BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is A1015Response) { return MergeFrom((A1015Response) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(A1015Response other) { if (other == global::DolphinServer.ProtoEntity.A1015Response.DefaultInstance) return this; PrepareBuilder(); if (other.HasErrorInfo) { ErrorInfo = other.ErrorInfo; } if (other.HasErrorCode) { ErrorCode = other.ErrorCode; } if (other.HasUid) { Uid = other.Uid; } if (other.HasHuType) { HuType = other.HuType; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_a1015ResponseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _a1015ResponseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasErrorInfo = input.ReadString(ref result.errorInfo_); break; } case 16: { result.hasErrorCode = input.ReadInt32(ref result.errorCode_); break; } case 26: { result.hasUid = input.ReadString(ref result.uid_); break; } case 32: { result.hasHuType = input.ReadInt32(ref result.huType_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasErrorInfo { get { return result.hasErrorInfo; } } public string ErrorInfo { get { return result.ErrorInfo; } set { SetErrorInfo(value); } } public Builder SetErrorInfo(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasErrorInfo = true; result.errorInfo_ = value; return this; } public Builder ClearErrorInfo() { PrepareBuilder(); result.hasErrorInfo = false; result.errorInfo_ = ""; return this; } public bool HasErrorCode { get { return result.hasErrorCode; } } public int ErrorCode { get { return result.ErrorCode; } set { SetErrorCode(value); } } public Builder SetErrorCode(int value) { PrepareBuilder(); result.hasErrorCode = true; result.errorCode_ = value; return this; } public Builder ClearErrorCode() { PrepareBuilder(); result.hasErrorCode = false; result.errorCode_ = 0; return this; } public bool HasUid { get { return result.hasUid; } } public string Uid { get { return result.Uid; } set { SetUid(value); } } public Builder SetUid(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasUid = true; result.uid_ = value; return this; } public Builder ClearUid() { PrepareBuilder(); result.hasUid = false; result.uid_ = ""; return this; } public bool HasHuType { get { return result.hasHuType; } } public int HuType { get { return result.HuType; } set { SetHuType(value); } } public Builder SetHuType(int value) { PrepareBuilder(); result.hasHuType = true; result.huType_ = value; return this; } public Builder ClearHuType() { PrepareBuilder(); result.hasHuType = false; result.huType_ = 0; return this; } } static A1015Response() { object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A1015Response.Descriptor, null); } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; namespace System.Globalization { // Gregorian Calendars use Era Info [Serializable] internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) internal String eraName; // The era name internal String abbrevEraName; // Abbreviated Era Name internal String englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, String eraName, String abbrevEraName, String englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear { get { return (m_maxYear); } } internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; internal int m_maxYear = 9999; internal int m_minYear; internal Calendar m_Cal; internal EraInfo[] m_EraInfo; internal int[] m_eras = null; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear; ; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } return (m_EraInfo[i].yearOffset + year); } } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } internal bool IsValidYear(int year, int era) { if (year < 0) { return false; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { return false; } return true; } } return false; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day) * TicksPerDay); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } return (InternalGloablizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (m_EraInfo[i].era); } } throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return ((int[])m_eras.Clone()); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public int GetMonthsInYear(int year, int era) { year = GetGregorianYear(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(SR.Argument_NoEra); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset // which will end up with zero as calendar year. // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989 if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(SR.Argument_NoEra); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month, era))); } Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public int GetLeapMonth(int year, int era) { year = GetGregorianYear(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public bool IsLeapMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( nameof(month), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return (new DateTime(ticks)); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek)); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); if (year < 100) { int y = year % 100; return ((twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y); } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Refractored.Xam.TTS.Abstractions; using Java.Util; using Android.Speech.Tts; using Android.App; using Android.OS; namespace Refractored.Xam.TTS { /// <summary> /// Text to speech implementation Android /// </summary> public class TextToSpeech : Java.Lang.Object, ITextToSpeech, Android.Speech.Tts.TextToSpeech.IOnInitListener, IDisposable { Android.Speech.Tts.TextToSpeech textToSpeech; string text; CrossLocale? language; float pitch, speakRate; bool queue; bool initialized; /// <summary> /// Default constructor /// </summary> public TextToSpeech() { } /// <summary> /// Initialize TTS /// </summary> public void Init() { Console.WriteLine("Current version: " + (int)global::Android.OS.Build.VERSION.SdkInt); Android.Util.Log.Info("CrossTTS", "Current version: " + (int)global::Android.OS.Build.VERSION.SdkInt); textToSpeech = new Android.Speech.Tts.TextToSpeech(Application.Context, this); } #region IOnInitListener implementation /// <summary> /// OnInit of TTS /// </summary> /// <param name="status"></param> public void OnInit(OperationResult status) { if (status.Equals(OperationResult.Success)) { initialized = true; Speak(); } } #endregion /// <summary> /// Speak back text /// </summary> /// <param name="text">Text to speak</param> /// <param name="queue">If you want to chain together speak command or cancel current</param> /// <param name="crossLocale">Locale of voice</param> /// <param name="pitch">Pitch of voice</param> /// <param name="speakRate">Speak Rate of voice (All) (0.0 - 2.0f)</param> /// <param name="volume">Volume of voice (iOS/WP) (0.0-1.0)</param> public void Speak(string text, bool queue = false, CrossLocale? crossLocale = null, float? pitch = null, float? speakRate = null, float? volume = null) { this.text = text; this.language = crossLocale; this.pitch = pitch == null ? 1.0f : pitch.Value; this.speakRate = speakRate == null ? 1.0f : speakRate.Value; this.queue = queue; if (textToSpeech == null || !initialized) { Init(); } else { Speak(); } } private void SetDefaultLanguage() { SetDefaultLanguageNonLollipop(); /*int version = (int)global::Android.OS.Build.VERSION.SdkInt; bool isLollipop = version >= 21; if (isLollipop) { //in a different method as it can crash on older target/compile for some reason SetDefaultLanguageLollipop(); } else { SetDefaultLanguageNonLollipop(); }*/ } private void SetDefaultLanguageNonLollipop() { //disable warning because we are checking ahead of time. #pragma warning disable 0618 if (textToSpeech.DefaultLanguage == null && textToSpeech.Language != null) textToSpeech.SetLanguage(textToSpeech.Language); else if (textToSpeech.DefaultLanguage != null) textToSpeech.SetLanguage(textToSpeech.DefaultLanguage); #pragma warning restore 0618 } /// <summary> /// In a different method as it can crash on older target/compile for some reason /// </summary> private void SetDefaultLanguageLollipop() { /*if (textToSpeech.DefaultVoice != null) { textToSpeech.SetVoice(textToSpeech.DefaultVoice); if (textToSpeech.DefaultVoice.Locale != null) textToSpeech.SetLanguage(textToSpeech.DefaultVoice.Locale); } else SetDefaultLanguageNonLollipop();*/ } private void Speak() { if (string.IsNullOrWhiteSpace(text)) return; if (!queue && textToSpeech.IsSpeaking) textToSpeech.Stop(); if (language.HasValue && !string.IsNullOrWhiteSpace(language.Value.Language)) { Locale locale = null; if (!string.IsNullOrWhiteSpace(language.Value.Country)) locale = new Locale(language.Value.Language, language.Value.Country); else locale = new Locale(language.Value.Language); var result = textToSpeech.IsLanguageAvailable(locale); if (result == LanguageAvailableResult.CountryAvailable) { textToSpeech.SetLanguage(locale); } else { Console.WriteLine("Locale: " + locale + " was not valid, setting to default."); SetDefaultLanguage(); } } else { SetDefaultLanguage(); } textToSpeech.SetPitch(pitch); textToSpeech.SetSpeechRate(speakRate); textToSpeech.Speak(text, queue ? QueueMode.Add : QueueMode.Flush, null); } /// <summary> /// Get all installed and valide lanaguages /// </summary> /// <returns>List of CrossLocales</returns> public IEnumerable<CrossLocale> GetInstalledLanguages() { if (textToSpeech != null && initialized) { int version = (int)global::Android.OS.Build.VERSION.SdkInt; bool isLollipop = version >= 21; if (isLollipop) { try { //in a different method as it can crash on older target/compile for some reason return GetInstalledLanguagesLollipop(); } catch(Exception ex) { Console.WriteLine("Something went horribly wrong, defaulting to old implementation to get languages: " + ex); } } var languages = new List<CrossLocale>(); var allLocales = Locale.GetAvailableLocales(); foreach(var locale in allLocales) { try { var result = textToSpeech.IsLanguageAvailable(locale); if (result == LanguageAvailableResult.CountryAvailable) { languages.Add(new CrossLocale { Country = locale.Country, Language = locale.Language, DisplayName = locale.DisplayName}); } } catch(Exception ex) { Console.WriteLine("Error checking language; " + locale + " " + ex); } } return languages.GroupBy(c => c.ToString()) .Select(g => g.First()); } else { return Locale.GetAvailableLocales() .Where(a => !string.IsNullOrWhiteSpace(a.Language) && !string.IsNullOrWhiteSpace(a.Country)) .Select(a => new CrossLocale { Country = a.Country, Language = a.Language, DisplayName = a.DisplayName }) .GroupBy(c => c.ToString()) .Select(g => g.First()); } } /// <summary> /// In a different method as it can crash on older target/compile for some reason /// </summary> /// <returns></returns> private IEnumerable<CrossLocale> GetInstalledLanguagesLollipop() { return textToSpeech.AvailableLanguages .Select(a => new CrossLocale { Country = a.Country, Language = a.Language, DisplayName = a.DisplayName }); } void IDisposable.Dispose() { if(textToSpeech != null) { textToSpeech.Stop(); textToSpeech.Dispose(); textToSpeech = null; } } } }
using UnityEngine; using System; using System.IO; using System.Collections.Generic; /* File browser for selecting files or folders at runtime. */ public enum FileBrowserType { File, Directory } public class FileBrowser { // Called when the user clicks cancel or select public delegate void FinishedCallback(string path); // Defaults to working directory public string CurrentDirectory { get { return m_currentDirectory; } set { SetNewDirectory(value); SwitchDirectoryNow(); } } protected string m_currentDirectory; // Optional pattern for filtering selectable files/folders. See: // http://msdn.microsoft.com/en-us/library/wz42302f(v=VS.90).aspx // and // http://msdn.microsoft.com/en-us/library/6ff71z1w(v=VS.90).aspx public string SelectionPattern { get { return m_filePattern; } set { m_filePattern = value; ReadDirectoryContents(); } } protected string m_filePattern; // Optional image for directories public Texture2D DirectoryImage { get { return m_directoryImage; } set { m_directoryImage = value; BuildContent(); } } protected Texture2D m_directoryImage; // Optional image for files public Texture2D FileImage { get { return m_fileImage; } set { m_fileImage = value; BuildContent(); } } protected Texture2D m_fileImage; // Browser type. Defaults to File, but can be set to Folder public FileBrowserType BrowserType { get { return m_browserType; } set { m_browserType = value; ReadDirectoryContents(); } } protected FileBrowserType m_browserType; protected string m_newDirectory; protected string[] m_currentDirectoryParts; protected string[] m_files; protected GUIContent[] m_filesWithImages; protected int m_selectedFile; protected string[] m_nonMatchingFiles; protected GUIContent[] m_nonMatchingFilesWithImages; protected int m_selectedNonMatchingDirectory; protected string[] m_directories; protected GUIContent[] m_directoriesWithImages; protected int m_selectedDirectory; protected string[] m_nonMatchingDirectories; protected GUIContent[] m_nonMatchingDirectoriesWithImages; protected bool m_currentDirectoryMatches; protected GUIStyle CentredText { get { if (m_centredText == null) { m_centredText = new GUIStyle(GUI.skin.label); m_centredText.alignment = TextAnchor.MiddleLeft; m_centredText.fixedHeight = GUI.skin.button.fixedHeight; } return m_centredText; } } protected GUIStyle m_centredText; protected string m_name; protected Rect m_screenRect; protected Vector2 m_scrollPosition; protected FinishedCallback m_callback; // Browsers need at least a rect, name and callback public FileBrowser(Rect screenRect, string name, FinishedCallback callback) { m_name = name; m_screenRect = screenRect; m_browserType = FileBrowserType.File; m_callback = callback; //SetNewDirectory(Directory.GetCurrentDirectory()); SetNewDirectory("LegacyMissions/"); SwitchDirectoryNow(); } protected void SetNewDirectory(string directory) { m_newDirectory = directory; } protected void SwitchDirectoryNow() { if (m_newDirectory == null || m_currentDirectory == m_newDirectory) { return; } m_currentDirectory = m_newDirectory; m_scrollPosition = Vector2.zero; m_selectedDirectory = m_selectedNonMatchingDirectory = m_selectedFile = -1; ReadDirectoryContents(); } protected void ReadDirectoryContents() { if (m_currentDirectory == "/") { m_currentDirectoryParts = new string[] {""}; m_currentDirectoryMatches = false; } else { m_currentDirectoryParts = m_currentDirectory.Split(Path.DirectorySeparatorChar); if (SelectionPattern != null) { string[] generation = Directory.GetDirectories( Path.GetDirectoryName(m_currentDirectory), SelectionPattern ); m_currentDirectoryMatches = Array.IndexOf(generation, m_currentDirectory) >= 0; } else { m_currentDirectoryMatches = false; } } if (BrowserType == FileBrowserType.File || SelectionPattern == null) { m_directories = Directory.GetDirectories(m_currentDirectory); m_nonMatchingDirectories = new string[0]; } else { m_directories = Directory.GetDirectories(m_currentDirectory, SelectionPattern); var nonMatchingDirectories = new List<string>(); foreach (string directoryPath in Directory.GetDirectories(m_currentDirectory)) { if (Array.IndexOf(m_directories, directoryPath) < 0) { nonMatchingDirectories.Add(directoryPath); } } m_nonMatchingDirectories = nonMatchingDirectories.ToArray(); for (int i = 0; i < m_nonMatchingDirectories.Length; ++i) { int lastSeparator = m_nonMatchingDirectories[i].LastIndexOf(Path.DirectorySeparatorChar); m_nonMatchingDirectories[i] = m_nonMatchingDirectories[i].Substring(lastSeparator + 1); } Array.Sort(m_nonMatchingDirectories); } for (int i = 0; i < m_directories.Length; ++i) { m_directories[i] = m_directories[i].Substring(m_directories[i].LastIndexOf(Path.DirectorySeparatorChar) + 1); } if (BrowserType == FileBrowserType.Directory || SelectionPattern == null) { m_files = Directory.GetFiles(m_currentDirectory); m_nonMatchingFiles = new string[0]; } else { m_files = Directory.GetFiles(m_currentDirectory, SelectionPattern); var nonMatchingFiles = new List<string>(); foreach (string filePath in Directory.GetFiles(m_currentDirectory)) { if (Array.IndexOf(m_files, filePath) < 0) { nonMatchingFiles.Add(filePath); } } m_nonMatchingFiles = nonMatchingFiles.ToArray(); for (int i = 0; i < m_nonMatchingFiles.Length; ++i) { m_nonMatchingFiles[i] = Path.GetFileName(m_nonMatchingFiles[i]); } Array.Sort(m_nonMatchingFiles); } for (int i = 0; i < m_files.Length; ++i) { m_files[i] = Path.GetFileName(m_files[i]); } Array.Sort(m_files); BuildContent(); m_newDirectory = null; } protected void BuildContent() { m_directoriesWithImages = new GUIContent[m_directories.Length]; for (int i = 0; i < m_directoriesWithImages.Length; ++i) { m_directoriesWithImages[i] = new GUIContent(m_directories[i], DirectoryImage); } m_nonMatchingDirectoriesWithImages = new GUIContent[m_nonMatchingDirectories.Length]; for (int i = 0; i < m_nonMatchingDirectoriesWithImages.Length; ++i) { m_nonMatchingDirectoriesWithImages[i] = new GUIContent(m_nonMatchingDirectories[i], DirectoryImage); } m_filesWithImages = new GUIContent[m_files.Length]; for (int i = 0; i < m_filesWithImages.Length; ++i) { m_filesWithImages[i] = new GUIContent(m_files[i], FileImage); } m_nonMatchingFilesWithImages = new GUIContent[m_nonMatchingFiles.Length]; for (int i = 0; i < m_nonMatchingFilesWithImages.Length; ++i) { m_nonMatchingFilesWithImages[i] = new GUIContent(m_nonMatchingFiles[i], FileImage); } } public void OnGUI() { GUILayout.BeginArea( m_screenRect, m_name, GUI.skin.window ); GUILayout.BeginHorizontal(); for (int parentIndex = 0; parentIndex < m_currentDirectoryParts.Length; ++parentIndex) { if (parentIndex == m_currentDirectoryParts.Length - 1) { GUILayout.Label(m_currentDirectoryParts[parentIndex], CentredText); } else if (GUILayout.Button(m_currentDirectoryParts[parentIndex])) { string parentDirectoryName = m_currentDirectory; for (int i = m_currentDirectoryParts.Length - 1; i > parentIndex; --i) { parentDirectoryName = Path.GetDirectoryName(parentDirectoryName); } SetNewDirectory(parentDirectoryName); } } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); m_scrollPosition = GUILayout.BeginScrollView( m_scrollPosition, false, true, GUI.skin.horizontalScrollbar, GUI.skin.verticalScrollbar, GUI.skin.box ); m_selectedDirectory = GUILayoutx.SelectionList( m_selectedDirectory, m_directoriesWithImages, DirectoryDoubleClickCallback ); if (m_selectedDirectory > -1) { m_selectedFile = m_selectedNonMatchingDirectory = -1; } m_selectedNonMatchingDirectory = GUILayoutx.SelectionList( m_selectedNonMatchingDirectory, m_nonMatchingDirectoriesWithImages, NonMatchingDirectoryDoubleClickCallback ); if (m_selectedNonMatchingDirectory > -1) { m_selectedDirectory = m_selectedFile = -1; } GUI.enabled = BrowserType == FileBrowserType.File; m_selectedFile = GUILayoutx.SelectionList( m_selectedFile, m_filesWithImages, FileDoubleClickCallback ); GUI.enabled = true; if (m_selectedFile > -1) { m_selectedDirectory = m_selectedNonMatchingDirectory = -1; } GUI.enabled = false; GUILayoutx.SelectionList( -1, m_nonMatchingFilesWithImages ); GUI.enabled = true; GUILayout.EndScrollView(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Cancel", GUILayout.Width(50))) { m_callback(null); } if (BrowserType == FileBrowserType.File) { GUI.enabled = m_selectedFile > -1; } else { if (SelectionPattern == null) { GUI.enabled = m_selectedDirectory > -1; } else { GUI.enabled = m_selectedDirectory > -1 || ( m_currentDirectoryMatches && m_selectedNonMatchingDirectory == -1 && m_selectedFile == -1 ); } } if (GUILayout.Button("Select", GUILayout.Width(50))) { if (BrowserType == FileBrowserType.File) { m_callback(Path.Combine(m_currentDirectory, m_files[m_selectedFile])); } else { if (m_selectedDirectory > -1) { m_callback(Path.Combine(m_currentDirectory, m_directories[m_selectedDirectory])); } else { m_callback(m_currentDirectory); } } } GUI.enabled = true; GUILayout.EndHorizontal(); GUILayout.EndArea(); if (Event.current.type == EventType.Repaint) { SwitchDirectoryNow(); } } protected void FileDoubleClickCallback(int i) { if (BrowserType == FileBrowserType.File) { m_callback(Path.Combine(m_currentDirectory, m_files[i])); } } protected void DirectoryDoubleClickCallback(int i) { SetNewDirectory(Path.Combine(m_currentDirectory, m_directories[i])); } protected void NonMatchingDirectoryDoubleClickCallback(int i) { SetNewDirectory(Path.Combine(m_currentDirectory, m_nonMatchingDirectories[i])); } }
// 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.Runtime.InteropServices; using System.Collections; using System.Diagnostics; using System.Text; namespace System.DirectoryServices.ActiveDirectory { [Flags] public enum ActiveDirectorySiteOptions { None = 0, AutoTopologyDisabled = 1, TopologyCleanupDisabled = 2, AutoMinimumHopDisabled = 4, StaleServerDetectDisabled = 8, AutoInterSiteTopologyDisabled = 16, GroupMembershipCachingEnabled = 32, ForceKccWindows2003Behavior = 64, UseWindows2000IstgElection = 128, RandomBridgeHeaderServerSelectionDisabled = 256, UseHashingForReplicationSchedule = 512, RedundantServerTopologyEnabled = 1024 } public class ActiveDirectorySite : IDisposable { internal readonly DirectoryContext context = null; private readonly string _name = null; internal readonly DirectoryEntry cachedEntry = null; private DirectoryEntry _ntdsEntry = null; private readonly ActiveDirectorySubnetCollection _subnets = null; private DirectoryServer _topologyGenerator = null; private readonly ReadOnlySiteCollection _adjacentSites = new ReadOnlySiteCollection(); private bool _disposed = false; private readonly DomainCollection _domains = new DomainCollection(null); private readonly ReadOnlyDirectoryServerCollection _servers = new ReadOnlyDirectoryServerCollection(); private readonly ReadOnlySiteLinkCollection _links = new ReadOnlySiteLinkCollection(); private ActiveDirectorySiteOptions _siteOptions = ActiveDirectorySiteOptions.None; private ReadOnlyDirectoryServerCollection _bridgeheadServers = new ReadOnlyDirectoryServerCollection(); private readonly DirectoryServerCollection _SMTPBridgeheadServers = null; private readonly DirectoryServerCollection _RPCBridgeheadServers = null; private byte[] _replicationSchedule = null; internal bool existing = false; private bool _subnetRetrieved = false; private bool _isADAMServer = false; private readonly bool _checkADAM = false; private bool _topologyTouched = false; private bool _adjacentSitesRetrieved = false; private readonly string _siteDN = null; private bool _domainsRetrieved = false; private bool _serversRetrieved = false; private bool _belongLinksRetrieved = false; private bool _bridgeheadServerRetrieved = false; private bool _SMTPBridgeRetrieved = false; private bool _RPCBridgeRetrieved = false; private const int ERROR_NO_SITENAME = 1919; public static ActiveDirectorySite FindByName(DirectoryContext context, string siteName) { // find an existing site ValidateArgument(context, siteName); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; string sitedn; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); sitedn = "CN=Sites," + (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); de = DirectoryEntryManager.GetDirectoryEntry(context, sitedn); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=site)(objectCategory=site)(name=" + Utils.GetEscapedFilterValue(siteName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such site object throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySite), siteName); } // it is an existing site object ActiveDirectorySite site = new ActiveDirectorySite(context, siteName, true); return site; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySite), siteName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { de.Dispose(); } } public ActiveDirectorySite(DirectoryContext context, string siteName) { ValidateArgument(context, siteName); // work with copy of the context context = new DirectoryContext(context); this.context = context; _name = siteName; // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de = null; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); _siteDN = "CN=Sites," + config; // bind to the site container de = DirectoryEntryManager.GetDirectoryEntry(context, _siteDN); string rdn = "cn=" + _name; rdn = Utils.GetEscapedPath(rdn); cachedEntry = de.Children.Add(rdn, "site"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } finally { if (de != null) de.Dispose(); } _subnets = new ActiveDirectorySubnetCollection(context, "CN=" + siteName + "," + _siteDN); string transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN; _RPCBridgeheadServers = new DirectoryServerCollection(context, "CN=" + siteName + "," + _siteDN, transportDN); transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN; _SMTPBridgeheadServers = new DirectoryServerCollection(context, "CN=" + siteName + "," + _siteDN, transportDN); } internal ActiveDirectorySite(DirectoryContext context, string siteName, bool existing) { Debug.Assert(existing == true); this.context = context; _name = siteName; this.existing = existing; DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); _siteDN = "CN=Sites," + (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); cachedEntry = DirectoryEntryManager.GetDirectoryEntry(context, "CN=" + siteName + "," + _siteDN); _subnets = new ActiveDirectorySubnetCollection(context, "CN=" + siteName + "," + _siteDN); string transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN; _RPCBridgeheadServers = new DirectoryServerCollection(context, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), transportDN); transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN; _SMTPBridgeheadServers = new DirectoryServerCollection(context, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), transportDN); } public static ActiveDirectorySite GetComputerSite() { // make sure that this is the platform that we support new DirectoryContext(DirectoryContextType.Forest); IntPtr ptr = (IntPtr)0; int result = UnsafeNativeMethods.DsGetSiteName(null, ref ptr); if (result != 0) { // computer is not in a site if (result == ERROR_NO_SITENAME) throw new ActiveDirectoryObjectNotFoundException(SR.NoCurrentSite, typeof(ActiveDirectorySite), null); else throw ExceptionHelper.GetExceptionFromErrorCode(result); } else { try { string siteName = Marshal.PtrToStringUni(ptr); Debug.Assert(siteName != null); // find the forest this machine belongs to string forestName = Locator.GetDomainControllerInfo(null, null, null, (long)PrivateLocatorFlags.DirectoryServicesRequired).DnsForestName; DirectoryContext currentContext = Utils.GetNewDirectoryContext(forestName, DirectoryContextType.Forest, null); // existing site ActiveDirectorySite site = ActiveDirectorySite.FindByName(currentContext, siteName); return site; } finally { if (ptr != (IntPtr)0) Marshal.FreeHGlobal(ptr); } } } public string Name { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _name; } } public DomainCollection Domains { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_domainsRetrieved) { // clear it first to be safe in case GetDomains fail in the middle and leave partial results there _domains.Clear(); GetDomains(); _domainsRetrieved = true; } } return _domains; } } public ActiveDirectorySubnetCollection Subnets { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { // if asked the first time, we need to properly construct the subnets collection if (!_subnetRetrieved) { _subnets.initialized = false; _subnets.Clear(); GetSubnets(); _subnetRetrieved = true; } } _subnets.initialized = true; return _subnets; } } public ReadOnlyDirectoryServerCollection Servers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_serversRetrieved) { _servers.Clear(); GetServers(); _serversRetrieved = true; } } return _servers; } } public ReadOnlySiteCollection AdjacentSites { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_adjacentSitesRetrieved) { _adjacentSites.Clear(); GetAdjacentSites(); _adjacentSitesRetrieved = true; } } return _adjacentSites; } } public ReadOnlySiteLinkCollection SiteLinks { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_belongLinksRetrieved) { _links.Clear(); GetLinks(); _belongLinksRetrieved = true; } } return _links; } } public DirectoryServer InterSiteTopologyGenerator { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { // have not load topology generator information from the directory and user has not set it yet if (_topologyGenerator == null && !_topologyTouched) { bool ISTGExist; try { ISTGExist = NTDSSiteEntry.Properties.Contains("interSiteTopologyGenerator"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (ISTGExist) { string serverDN = (string)PropertyManager.GetPropertyValue(context, NTDSSiteEntry, PropertyManager.InterSiteTopologyGenerator); string hostname = null; DirectoryEntry tmp = DirectoryEntryManager.GetDirectoryEntry(context, serverDN); try { hostname = (string)PropertyManager.GetPropertyValue(context, tmp.Parent, PropertyManager.DnsHostName); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // indicates a demoted server return null; } } if (IsADAM) { int port = (int)PropertyManager.GetPropertyValue(context, tmp, PropertyManager.MsDSPortLDAP); string fullHostName = hostname; if (port != 389) { fullHostName = hostname + ":" + port; } _topologyGenerator = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName); } else { _topologyGenerator = new DomainController(Utils.GetNewDirectoryContext(hostname, DirectoryContextType.DirectoryServer, context), hostname); } } } } return _topologyGenerator; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (value == null) throw new ArgumentNullException(nameof(value)); if (existing) { // for existing site, nTDSSiteSettings needs to exist DirectoryEntry tmp = NTDSSiteEntry; } _topologyTouched = true; _topologyGenerator = value; } } public ActiveDirectorySiteOptions Options { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { try { if (NTDSSiteEntry.Properties.Contains("options")) { return (ActiveDirectorySiteOptions)NTDSSiteEntry.Properties["options"][0]; } else return ActiveDirectorySiteOptions.None; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else return _siteOptions; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { try { NTDSSiteEntry.Properties["options"].Value = value; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else _siteOptions = value; } } public string Location { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { if (cachedEntry.Properties.Contains("location")) { return (string)cachedEntry.Properties["location"][0]; } else return null; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { if (value == null) { if (cachedEntry.Properties.Contains("location")) cachedEntry.Properties["location"].Clear(); } else { cachedEntry.Properties["location"].Value = value; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public ReadOnlyDirectoryServerCollection BridgeheadServers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!_bridgeheadServerRetrieved) { _bridgeheadServers = GetBridgeheadServers(); _bridgeheadServerRetrieved = true; } return _bridgeheadServers; } } public DirectoryServerCollection PreferredSmtpBridgeheadServers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_SMTPBridgeRetrieved) { _SMTPBridgeheadServers.initialized = false; _SMTPBridgeheadServers.Clear(); GetPreferredBridgeheadServers(ActiveDirectoryTransportType.Smtp); _SMTPBridgeRetrieved = true; } } _SMTPBridgeheadServers.initialized = true; return _SMTPBridgeheadServers; } } public DirectoryServerCollection PreferredRpcBridgeheadServers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_RPCBridgeRetrieved) { _RPCBridgeheadServers.initialized = false; _RPCBridgeheadServers.Clear(); GetPreferredBridgeheadServers(ActiveDirectoryTransportType.Rpc); _RPCBridgeRetrieved = true; } } _RPCBridgeheadServers.initialized = true; return _RPCBridgeheadServers; } } public ActiveDirectorySchedule IntraSiteReplicationSchedule { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); ActiveDirectorySchedule schedule = null; if (existing) { // if exists in the cache, return it, otherwise null is returned try { if (NTDSSiteEntry.Properties.Contains("schedule")) { byte[] tmpSchedule = (byte[])NTDSSiteEntry.Properties["schedule"][0]; Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188); schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(tmpSchedule); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { if (_replicationSchedule != null) { // newly created site, get the schedule if already has been set by the user schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(_replicationSchedule); } } return schedule; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { try { if (value == null) { // clear it out if existing before if (NTDSSiteEntry.Properties.Contains("schedule")) NTDSSiteEntry.Properties["schedule"].Clear(); } else // replace with the new value NTDSSiteEntry.Properties["schedule"].Value = value.GetUnmanagedSchedule(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { // clear out the schedule if (value == null) _replicationSchedule = null; else { // replace with the new value _replicationSchedule = value.GetUnmanagedSchedule(); } } } } private bool IsADAM { get { if (!_checkADAM) { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); PropertyValueCollection values = null; try { values = de.Properties["supportedCapabilities"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (values.Contains(SupportedCapability.ADAMOid)) _isADAMServer = true; } return _isADAMServer; } } private DirectoryEntry NTDSSiteEntry { get { if (_ntdsEntry == null) { DirectoryEntry tmp = DirectoryEntryManager.GetDirectoryEntry(context, "CN=NTDS Site Settings," + (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)); try { tmp.RefreshCache(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { string message = SR.Format(SR.NTDSSiteSetting, _name); throw new ActiveDirectoryOperationException(message, e, 0x2030); } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } _ntdsEntry = tmp; } return _ntdsEntry; } } public void Save() { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { // commit changes cachedEntry.CommitChanges(); foreach (DictionaryEntry e in _subnets.changeList) { try { ((DirectoryEntry)e.Value).CommitChanges(); } catch (COMException exception) { // there is a bug in ADSI that when targeting ADAM, permissive modify control is not used. if (exception.ErrorCode != unchecked((int)0x8007200A)) throw ExceptionHelper.GetExceptionFromCOMException(exception); } } // reset status variables _subnets.changeList.Clear(); _subnetRetrieved = false; // need to throw better exception for ADAM since its SMTP transport is not available foreach (DictionaryEntry e in _SMTPBridgeheadServers.changeList) { try { ((DirectoryEntry)e.Value).CommitChanges(); } catch (COMException exception) { // SMTP transport is not supported on ADAM if (IsADAM && (exception.ErrorCode == unchecked((int)0x8007202F))) throw new NotSupportedException(SR.NotSupportTransportSMTP); // there is a bug in ADSI that when targeting ADAM, permissive modify control is not used. if (exception.ErrorCode != unchecked((int)0x8007200A)) throw ExceptionHelper.GetExceptionFromCOMException(exception); } } _SMTPBridgeheadServers.changeList.Clear(); _SMTPBridgeRetrieved = false; foreach (DictionaryEntry e in _RPCBridgeheadServers.changeList) { try { ((DirectoryEntry)e.Value).CommitChanges(); } catch (COMException exception) { // there is a bug in ADSI that when targeting ADAM, permissive modify control is not used. if (exception.ErrorCode != unchecked((int)0x8007200A)) throw ExceptionHelper.GetExceptionFromCOMException(exception); } } _RPCBridgeheadServers.changeList.Clear(); _RPCBridgeRetrieved = false; if (existing) { // topology generator is changed if (_topologyTouched) { try { DirectoryServer server = InterSiteTopologyGenerator; string ntdsaName = (server is DomainController) ? ((DomainController)server).NtdsaObjectName : ((AdamInstance)server).NtdsaObjectName; NTDSSiteEntry.Properties["interSiteTopologyGenerator"].Value = ntdsaName; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } NTDSSiteEntry.CommitChanges(); _topologyTouched = false; } else { try { // create nTDSSiteSettings object DirectoryEntry tmpEntry = cachedEntry.Children.Add("CN=NTDS Site Settings", "nTDSSiteSettings"); //set properties on the Site NTDS settings object DirectoryServer replica = InterSiteTopologyGenerator; if (replica != null) { string ntdsaName = (replica is DomainController) ? ((DomainController)replica).NtdsaObjectName : ((AdamInstance)replica).NtdsaObjectName; tmpEntry.Properties["interSiteTopologyGenerator"].Value = ntdsaName; } tmpEntry.Properties["options"].Value = _siteOptions; if (_replicationSchedule != null) { tmpEntry.Properties["schedule"].Value = _replicationSchedule; } tmpEntry.CommitChanges(); // cached the entry _ntdsEntry = tmpEntry; // create servers contain object tmpEntry = cachedEntry.Children.Add("CN=Servers", "serversContainer"); tmpEntry.CommitChanges(); if (!IsADAM) { // create the licensingSiteSettings object tmpEntry = cachedEntry.Children.Add("CN=Licensing Site Settings", "licensingSiteSettings"); tmpEntry.CommitChanges(); } } finally { // entry is created on the backend store successfully existing = true; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } public void Delete() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existing) { throw new InvalidOperationException(SR.CannotDelete); } else { try { cachedEntry.DeleteTree(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public override string ToString() { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _name; } private ReadOnlyDirectoryServerCollection GetBridgeheadServers() { NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname)new NativeComInterfaces.Pathname(); // need to turn off the escaping for name pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX; ReadOnlyDirectoryServerCollection collection = new ReadOnlyDirectoryServerCollection(); if (existing) { Hashtable bridgeHeadTable = new Hashtable(); Hashtable nonBridgHeadTable = new Hashtable(); Hashtable hostNameTable = new Hashtable(); const string ocValue = "CN=Server"; // get destination bridgehead servers // first go to the servers container under the current site and then do a search to get the all server objects. string serverContainer = "CN=Servers," + (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName); DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverContainer); try { // go through connection objects and find out its fromServer property. ADSearcher adSearcher = new ADSearcher(de, "(|(objectCategory=server)(objectCategory=NTDSConnection))", new string[] { "fromServer", "distinguishedName", "dNSHostName", "objectCategory" }, SearchScope.Subtree, true, /* need paged search */ true /* need cached result as we need to go back to the first record */); SearchResultCollection conResults = null; try { conResults = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { // find out whether fromServer indicates replicating from a server in another site. foreach (SearchResult r in conResults) { string objectCategoryValue = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.ObjectCategory); if (Utils.Compare(objectCategoryValue, 0, ocValue.Length, ocValue, 0, ocValue.Length) == 0) { hostNameTable.Add((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DnsHostName)); } } foreach (SearchResult r in conResults) { string objectCategoryValue = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.ObjectCategory); if (Utils.Compare(objectCategoryValue, 0, ocValue.Length, ocValue, 0, ocValue.Length) != 0) { string fromServer = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.FromServer); // escaping manipulation string fromSite = Utils.GetPartialDN(fromServer, 3); pathCracker.Set(fromSite, NativeComInterfaces.ADS_SETTYPE_DN); fromSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(fromSite != null && Utils.Compare(fromSite, 0, 3, "CN=", 0, 3) == 0); fromSite = fromSite.Substring(3); string serverObjectName = Utils.GetPartialDN((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), 2); // don't know whether it is a bridgehead server yet. if (!bridgeHeadTable.Contains(serverObjectName)) { string hostName = (string)hostNameTable[serverObjectName]; // add if not yet done if (!nonBridgHeadTable.Contains(serverObjectName)) nonBridgHeadTable.Add(serverObjectName, hostName); // check whether from different site if (Utils.Compare((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.Cn), fromSite) != 0) { // the server is a bridgehead server bridgeHeadTable.Add(serverObjectName, hostName); nonBridgHeadTable.Remove(serverObjectName); } } } } } finally { conResults.Dispose(); } } finally { de.Dispose(); } // get source bridgehead server if (nonBridgHeadTable.Count != 0) { // go to sites container to get all the connecdtion object that replicates from servers in the current sites that have // not been determined whether it is a bridgehead server or not. DirectoryEntry serverEntry = DirectoryEntryManager.GetDirectoryEntry(context, _siteDN); // constructing the filter StringBuilder str = new StringBuilder(100); if (nonBridgHeadTable.Count > 1) str.Append("(|"); foreach (DictionaryEntry val in nonBridgHeadTable) { str.Append("(fromServer="); str.Append("CN=NTDS Settings,"); str.Append(Utils.GetEscapedFilterValue((string)val.Key)); str.Append(")"); } if (nonBridgHeadTable.Count > 1) str.Append(")"); ADSearcher adSearcher = new ADSearcher(serverEntry, "(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)" + str.ToString() + ")", new string[] { "fromServer", "distinguishedName" }, SearchScope.Subtree); SearchResultCollection conResults = null; try { conResults = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { foreach (SearchResult r in conResults) { string fromServer = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.FromServer); string serverObject = fromServer.Substring(17); if (nonBridgHeadTable.Contains(serverObject)) { string otherSite = Utils.GetPartialDN((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), 4); // escaping manipulation pathCracker.Set(otherSite, NativeComInterfaces.ADS_SETTYPE_DN); otherSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(otherSite != null && Utils.Compare(otherSite, 0, 3, "CN=", 0, 3) == 0); otherSite = otherSite.Substring(3); // check whether from different sites if (Utils.Compare(otherSite, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.Cn)) != 0) { string val = (string)nonBridgHeadTable[serverObject]; nonBridgHeadTable.Remove(serverObject); bridgeHeadTable.Add(serverObject, val); } } } } finally { conResults.Dispose(); serverEntry.Dispose(); } } DirectoryEntry ADAMEntry = null; foreach (DictionaryEntry e in bridgeHeadTable) { DirectoryServer replica = null; string host = (string)e.Value; // construct directoryreplica if (IsADAM) { ADAMEntry = DirectoryEntryManager.GetDirectoryEntry(context, "CN=NTDS Settings," + e.Key); int port = (int)PropertyManager.GetPropertyValue(context, ADAMEntry, PropertyManager.MsDSPortLDAP); string fullhost = host; if (port != 389) { fullhost = host + ":" + port; } replica = new AdamInstance(Utils.GetNewDirectoryContext(fullhost, DirectoryContextType.DirectoryServer, context), fullhost); } else { replica = new DomainController(Utils.GetNewDirectoryContext(host, DirectoryContextType.DirectoryServer, context), host); } collection.Add(replica); } } return collection; } public DirectoryEntry GetDirectoryEntry() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existing) { throw new InvalidOperationException(SR.CannotGetObject); } else { return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedEntry.Path); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // free other state (managed objects) if (cachedEntry != null) cachedEntry.Dispose(); if (_ntdsEntry != null) _ntdsEntry.Dispose(); } // free your own state (unmanaged objects) _disposed = true; } private static void ValidateArgument(DirectoryContext context, string siteName) { // basic validation first if (context == null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name if (context.Name != null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } if (siteName == null) throw new ArgumentNullException(nameof(siteName)); if (siteName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } private void GetSubnets() { // performs a search to find out the subnets that belong to this site DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string subnetContainer = "CN=Subnets,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, subnetContainer); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=subnet)(objectCategory=subnet)(siteObject=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))", new string[] { "cn", "location" }, SearchScope.OneLevel ); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { string subnetName = null; foreach (SearchResult result in results) { subnetName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn); ActiveDirectorySubnet subnet = new ActiveDirectorySubnet(context, subnetName, null, true); // set the cached entry subnet.cachedEntry = result.GetDirectoryEntry(); // set the site info subnet.Site = this; _subnets.Add(subnet); } } finally { results.Dispose(); de.Dispose(); } } private void GetAdjacentSites() { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)de.Properties["configurationNamingContext"][0]; string transportContainer = "CN=Inter-Site Transports,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))", new string[] { "cn", "distinguishedName" }, SearchScope.Subtree); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { ActiveDirectorySiteLink link = null; foreach (SearchResult result in results) { string dn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DistinguishedName); string linkName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn); string transportName = (string)Utils.GetDNComponents(dn)[1].Value; ActiveDirectoryTransportType transportType; if (string.Equals(transportName, "IP", StringComparison.OrdinalIgnoreCase)) transportType = ActiveDirectoryTransportType.Rpc; else if (string.Equals(transportName, "SMTP", StringComparison.OrdinalIgnoreCase)) transportType = ActiveDirectoryTransportType.Smtp; else { // should not happen string message = SR.Format(SR.UnknownTransport, transportName); throw new ActiveDirectoryOperationException(message); } try { link = new ActiveDirectorySiteLink(context, linkName, transportType, true, result.GetDirectoryEntry()); foreach (ActiveDirectorySite tmpSite in link.Sites) { // don't add itself if (Utils.Compare(tmpSite.Name, Name) == 0) continue; if (!_adjacentSites.Contains(tmpSite)) _adjacentSites.Add(tmpSite); } } finally { link.Dispose(); } } } finally { results.Dispose(); de.Dispose(); } } private void GetLinks() { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string transportContainer = "CN=Inter-Site Transports,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))", new string[] { "cn", "distinguishedName" }, SearchScope.Subtree); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { foreach (SearchResult result in results) { // construct the sitelinks at the same time DirectoryEntry connectionEntry = result.GetDirectoryEntry(); string cn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn); string transport = Utils.GetDNComponents((string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DistinguishedName))[1].Value; ActiveDirectorySiteLink link = null; if (string.Equals(transport, "IP", StringComparison.OrdinalIgnoreCase)) link = new ActiveDirectorySiteLink(context, cn, ActiveDirectoryTransportType.Rpc, true, connectionEntry); else if (string.Equals(transport, "SMTP", StringComparison.OrdinalIgnoreCase)) link = new ActiveDirectorySiteLink(context, cn, ActiveDirectoryTransportType.Smtp, true, connectionEntry); else { // should not happen string message = SR.Format(SR.UnknownTransport, transport); throw new ActiveDirectoryOperationException(message); } _links.Add(link); } } finally { results.Dispose(); de.Dispose(); } } private void GetDomains() { // for ADAM, there is no concept of domain, we just return empty collection which is good enough if (!IsADAM) { string serverName = cachedEntry.Options.GetCurrentServerName(); DomainController dc = DomainController.GetDomainController(Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context)); IntPtr handle = dc.Handle; Debug.Assert(handle != (IntPtr)0); IntPtr info = (IntPtr)0; // call DsReplicaSyncAllW IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } UnsafeNativeMethods.DsListDomainsInSiteW dsListDomainsInSiteW = (UnsafeNativeMethods.DsListDomainsInSiteW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsListDomainsInSiteW)); int result = dsListDomainsInSiteW(handle, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), ref info); if (result != 0) throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName); try { DS_NAME_RESULT names = new DS_NAME_RESULT(); Marshal.PtrToStructure(info, names); int count = names.cItems; IntPtr val = names.rItems; if (count > 0) { Debug.Assert(val != (IntPtr)0); int status = Marshal.ReadInt32(val); IntPtr tmpPtr = (IntPtr)0; for (int i = 0; i < count; i++) { tmpPtr = IntPtr.Add(val, Marshal.SizeOf(typeof(DS_NAME_RESULT_ITEM)) * i); DS_NAME_RESULT_ITEM nameResult = new DS_NAME_RESULT_ITEM(); Marshal.PtrToStructure(tmpPtr, nameResult); if (nameResult.status == DS_NAME_ERROR.DS_NAME_NO_ERROR || nameResult.status == DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY) { string domainName = Marshal.PtrToStringUni(nameResult.pName); if (domainName != null && domainName.Length > 0) { string d = Utils.GetDnsNameFromDN(domainName); Domain domain = new Domain(Utils.GetNewDirectoryContext(d, DirectoryContextType.Domain, context), d); _domains.Add(domain); } } } } } finally { // call DsFreeNameResultW functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } UnsafeNativeMethods.DsFreeNameResultW dsFreeNameResultW = (UnsafeNativeMethods.DsFreeNameResultW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsFreeNameResultW)); dsFreeNameResultW(info); } } } private void GetServers() { ADSearcher adSearcher = new ADSearcher(cachedEntry, "(&(objectClass=server)(objectCategory=server))", new string[] { "dNSHostName" }, SearchScope.Subtree); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { foreach (SearchResult result in results) { string hostName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DnsHostName); DirectoryEntry de = result.GetDirectoryEntry(); DirectoryEntry child = null; DirectoryServer replica = null; // make sure that the server is not demoted try { child = de.Children.Find("CN=NTDS Settings", "nTDSDSA"); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { continue; } else throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (IsADAM) { int port = (int)PropertyManager.GetPropertyValue(context, child, PropertyManager.MsDSPortLDAP); string fullHostName = hostName; if (port != 389) { fullHostName = hostName + ":" + port; } replica = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName); } else replica = new DomainController(Utils.GetNewDirectoryContext(hostName, DirectoryContextType.DirectoryServer, context), hostName); _servers.Add(replica); } } finally { results.Dispose(); } } private void GetPreferredBridgeheadServers(ActiveDirectoryTransportType transport) { string serverContainerDN = "CN=Servers," + PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName); string transportDN = null; if (transport == ActiveDirectoryTransportType.Smtp) transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN; else transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN; DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverContainerDN); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=server)(objectCategory=Server)(bridgeheadTransportList=" + Utils.GetEscapedFilterValue(transportDN) + "))", new string[] { "dNSHostName", "distinguishedName" }, SearchScope.OneLevel); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { DirectoryEntry ADAMEntry = null; foreach (SearchResult result in results) { string hostName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DnsHostName); DirectoryEntry resultEntry = result.GetDirectoryEntry(); DirectoryServer replica = null; try { ADAMEntry = resultEntry.Children.Find("CN=NTDS Settings", "nTDSDSA"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (IsADAM) { int port = (int)PropertyManager.GetPropertyValue(context, ADAMEntry, PropertyManager.MsDSPortLDAP); string fullHostName = hostName; if (port != 389) { fullHostName = hostName + ":" + port; } replica = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName); } else replica = new DomainController(Utils.GetNewDirectoryContext(hostName, DirectoryContextType.DirectoryServer, context), hostName); if (transport == ActiveDirectoryTransportType.Smtp) _SMTPBridgeheadServers.Add(replica); else _RPCBridgeheadServers.Add(replica); } } finally { de.Dispose(); results.Dispose(); } } } }
//----------------------------------------------------------------------- // <copyright file="CloudAnchorUIController.cs" company="Google"> // // Copyright 2018 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 GoogleARCore.Examples.CloudAnchor { using System.Collections.Generic; using GoogleARCore; using GoogleARCore.CrossPlatform; using GoogleARCore.Examples.Common; using UnityEngine; using UnityEngine.UI; /// <summary> /// Controller managing UI for the Cloud Anchor Example. /// </summary> public class CloudAnchorUIController : MonoBehaviour { /// <summary> /// A gameobject parenting UI for displaying feedback and errors. /// </summary> public Text SnackbarText; /// <summary> /// A text element displaying the current Room. /// </summary> public Text RoomText; /// <summary> /// A text element displaying the device's IP Address. /// </summary> public Text IPAddressText; /// <summary> /// The host anchor mode button. /// </summary> public Button HostAnchorModeButton; /// <summary> /// The resolve anchor mode button. /// </summary> public Button ResolveAnchorModeButton; /// <summary> /// The root for the input interface. /// </summary> public GameObject InputRoot; /// <summary> /// The input field for the room. /// </summary> public InputField RoomInputField; /// <summary> /// The input field for the ip address. /// </summary> public InputField IpAddressInputField; /// <summary> /// The field for toggling loopback (local) anchor resoltion. /// </summary> public Toggle ResolveOnDeviceToggle; /// <summary> /// The Unity Start() method. /// </summary> public void Start() { IPAddressText.text = "My IP Address: " + Network.player.ipAddress; } /// <summary> /// Shows UI for application "Ready Mode". /// </summary> public void ShowReadyMode() { HostAnchorModeButton.GetComponentInChildren<Text>().text = "Host"; HostAnchorModeButton.interactable = true; ResolveAnchorModeButton.GetComponentInChildren<Text>().text = "Resolve"; ResolveAnchorModeButton.interactable = true; SnackbarText.text = "Please select Host or Resolve to continue"; InputRoot.SetActive(false); } /// <summary> /// Shows UI for the beginning phase of application "Hosting Mode". /// </summary> /// <param name="snackbarText">Optional text to put in the snackbar.</param> public void ShowHostingModeBegin(string snackbarText = null) { HostAnchorModeButton.GetComponentInChildren<Text>().text = "Cancel"; HostAnchorModeButton.interactable = true; ResolveAnchorModeButton.GetComponentInChildren<Text>().text = "Resolve"; ResolveAnchorModeButton.interactable = false; if (string.IsNullOrEmpty(snackbarText)) { SnackbarText.text = "The room code is now available. Please place an anchor to host, press Cancel to Exit."; } else { SnackbarText.text = snackbarText; } InputRoot.SetActive(false); } /// <summary> /// Shows UI for the attempting to host phase of application "Hosting Mode". /// </summary> public void ShowHostingModeAttemptingHost() { HostAnchorModeButton.GetComponentInChildren<Text>().text = "Cancel"; HostAnchorModeButton.interactable = false; ResolveAnchorModeButton.GetComponentInChildren<Text>().text = "Resolve"; ResolveAnchorModeButton.interactable = false; SnackbarText.text = "Attempting to host anchor..."; InputRoot.SetActive(false); } /// <summary> /// Shows UI for the beginning phase of application "Resolving Mode". /// </summary> /// <param name="snackbarText">Optional text to put in the snackbar.</param> public void ShowResolvingModeBegin(string snackbarText = null) { HostAnchorModeButton.GetComponentInChildren<Text>().text = "Host"; HostAnchorModeButton.interactable = false; ResolveAnchorModeButton.GetComponentInChildren<Text>().text = "Cancel"; ResolveAnchorModeButton.interactable = true; if (string.IsNullOrEmpty(snackbarText)) { SnackbarText.text = "Input Room and IP address to resolve anchor."; } else { SnackbarText.text = snackbarText; } InputRoot.SetActive(true); } /// <summary> /// Shows UI for the attempting to resolve phase of application "Resolving Mode". /// </summary> public void ShowResolvingModeAttemptingResolve() { HostAnchorModeButton.GetComponentInChildren<Text>().text = "Host"; HostAnchorModeButton.interactable = false; ResolveAnchorModeButton.GetComponentInChildren<Text>().text = "Cancel"; ResolveAnchorModeButton.interactable = false; SnackbarText.text = "Attempting to resolve anchor."; InputRoot.SetActive(false); } /// <summary> /// Shows UI for the successful resolve phase of application "Resolving Mode". /// </summary> public void ShowResolvingModeSuccess() { HostAnchorModeButton.GetComponentInChildren<Text>().text = "Host"; HostAnchorModeButton.interactable = false; ResolveAnchorModeButton.GetComponentInChildren<Text>().text = "Cancel"; ResolveAnchorModeButton.interactable = true; SnackbarText.text = "The anchor was successfully resolved."; InputRoot.SetActive(false); } /// <summary> /// Sets the room number in the UI. /// </summary> /// <param name="roomNumber">The room number to set.</param> public void SetRoomTextValue(int roomNumber) { RoomText.text = "Room: " + roomNumber; } /// <summary> /// Gets the value of the resolve on device checkbox. /// </summary> /// <returns>The value of the resolve on device checkbox.</returns> public bool GetResolveOnDeviceValue() { return ResolveOnDeviceToggle.isOn; } /// <summary> /// Gets the value of the room number input field. /// </summary> /// <returns>The value of the room number input field.</returns> public int GetRoomInputValue() { int roomNumber; if (int.TryParse(RoomInputField.text, out roomNumber)) { return roomNumber; } return 0; } /// <summary> /// Gets the value of the ip address input field. /// </summary> /// <returns>The value of the ip address input field.</returns> public string GetIpAddressInputValue() { return IpAddressInputField.text; } /// <summary> /// Handles a change to the "Resolve on Device" checkbox. /// </summary> /// <param name="isResolveOnDevice">If set to <c>true</c> resolve on device.</param> public void OnResolveOnDeviceValueChanged(bool isResolveOnDevice) { IpAddressInputField.interactable = !isResolveOnDevice; } } }
/* * EnumBuilder.cs - Implementation of the * "System.Reflection.Emit.EnumBuilder" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Reflection.Emit { #if CONFIG_REFLECTION_EMIT using System; using System.Reflection; using System.Globalization; using System.Runtime.CompilerServices; public sealed class EnumBuilder : Type { // Internal state. internal TypeBuilder builder; private Type underlyingType; private FieldBuilder underlyingField; // Constructor. internal EnumBuilder(ModuleBuilder module, String name, String nspace, TypeAttributes visibility, Type underlyingType) { // Only allowed to specify the visibility. if((visibility & ~TypeAttributes.VisibilityMask) != 0) { throw new ArgumentException(_("Emit_InvalidTypeAttrs")); } // Create a type builder behind the scenes. builder = new TypeBuilder (module, name, nspace, visibility | TypeAttributes.Sealed, typeof(System.Enum), null, PackingSize.Unspecified, 0, null); // Define the "value__" field for the enumeration. this.underlyingType = underlyingType; this.underlyingField = builder.DefineField ("value__", underlyingType, FieldAttributes.Private | FieldAttributes.SpecialName); } // Create the final type for this enumeration. public Type CreateType() { return builder.CreateType(); } // Define a literal within this enumeration. public FieldBuilder DefineLiteral(String literalName, Object literalValue) { FieldBuilder field; field = builder.DefineField (literalName, builder, // Note: use correct enum type. FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal); field.SetConstant(literalValue); return field; } // Invoke a specific type member. public override Object InvokeMember (String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { return builder.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } // Implementation of "GetConstructor" provided by subclasses. protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callingConventions, Type[] types, ParameterModifier[] modifiers) { return builder.GetConstructor (bindingAttr, binder, callingConventions, types, modifiers); } // Get all constructors for this type. public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return builder.GetConstructors(bindingAttr); } // Get the custom attributes that are associated with this member. public override Object[] GetCustomAttributes(bool inherit) { return builder.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type type, bool inherit) { return builder.GetCustomAttributes(type, inherit); } // Determine if custom attributes are defined for this member. public override bool IsDefined(Type type, bool inherit) { return builder.IsDefined(type, inherit); } // Get the element type. public override Type GetElementType() { return builder.GetElementType(); } // Get an event from this type. public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { return builder.GetEvent(name, bindingAttr); } // Get the list of all events within this type. public override EventInfo[] GetEvents() { return builder.GetEvents(); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return builder.GetEvents(bindingAttr); } // Get a field from this type. public override FieldInfo GetField(String name, BindingFlags bindingAttr) { return builder.GetField(name, bindingAttr); } // Get the list of all fields within this type. public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return builder.GetFields(bindingAttr); } // Get an interface from within this type. public override Type GetInterface(String name, bool ignoreCase) { return builder.GetInterface(name, ignoreCase); } // Get an interface mapping for this type. public override InterfaceMapping GetInterfaceMap(Type interfaceType) { return builder.GetInterfaceMap(interfaceType); } // Get the list of all interfaces that are implemented by this type. public override Type[] GetInterfaces() { return builder.GetInterfaces(); } // Get a list of members that have a specific name. public override MemberInfo[] GetMember (String name, MemberTypes type, BindingFlags bindingAttr) { return builder.GetMember(name, type, bindingAttr); } // Get a list of all members in this type. public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return builder.GetMembers(bindingAttr); } // Implementation of "GetMethod". protected override MethodInfo GetMethodImpl (String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return builder.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } // Get a list of all methods in this type. public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return builder.GetMethods(bindingAttr); } // Get a nested type that is contained within this type. public override Type GetNestedType(String name, BindingFlags bindingAttr) { return builder.GetNestedType(name, bindingAttr); } // Get a list of all nested types in this type. public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return builder.GetNestedTypes(bindingAttr); } // Get a list of all properites in this type. public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return builder.GetProperties(bindingAttr); } // Get a specific property from within this type. protected override PropertyInfo GetPropertyImpl (String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { return builder.GetProperty(name, bindingAttr, binder, returnType, types, modifiers); } // Get the attribute flags for this type. protected override TypeAttributes GetAttributeFlagsImpl() { return builder.attr; } // Determine if this type has an element type. protected override bool HasElementTypeImpl() { throw new NotSupportedException(_("NotSupp_Builder")); } // Determine if this type is an array. protected override bool IsArrayImpl() { return false; } // Determine if this type is a "by reference" type. protected override bool IsByRefImpl() { return false; } // Determine if this type imports a COM type. protected override bool IsCOMObjectImpl() { return false; } // Determine if this is a pointer type. protected override bool IsPointerImpl() { return false; } // Determine if this is a primitive type. protected override bool IsPrimitiveImpl() { return false; } // Determine if this is a value type. protected override bool IsValueTypeImpl() { return true; } // Set a custom attribute on this enum builder. public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { builder.SetCustomAttribute(customBuilder); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { builder.SetCustomAttribute(con, binaryAttribute); } // Get the assembly associated with this type. public override Assembly Assembly { get { return builder.Assembly; } } // Get the full assembly-qualified name of this type. public override String AssemblyQualifiedName { get { return builder.AssemblyQualifiedName; } } // Get the declaring type. public override Type DeclaringType { get { return builder.DeclaringType; } } // Get the full name of this type. public override String FullName { get { return builder.FullName; } } // Get the base type of this type. public override Type BaseType { get { return builder.BaseType; } } // Get the GUID of this type. public override Guid GUID { get { return builder.GUID; } } // Get the module associated with this type. public override Module Module { get { return builder.Module; } } // Get the name of this type. public override String Name { get { return builder.Name; } } // Get the namespace of this type. public override String Namespace { get { return builder.Namespace; } } // Get the reflected type. public override Type ReflectedType { get { return builder.ReflectedType; } } // Get the type handle for this enumerated type. public override RuntimeTypeHandle TypeHandle { get { return builder.TypeHandle; } } // Get the token for this enumerated type. public TypeToken TypeToken { get { return builder.TypeToken; } } // Get the underlying field. public FieldBuilder UnderlyingField { get { return underlyingField; } } // Get the underlying type for this enumeration. public override Type UnderlyingSystemType { get { return underlyingType; } } }; // class EnumBuilder #endif // CONFIG_REFLECTION_EMIT }; // namespace System.Reflection.Emit
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class TernaryNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableBoolTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; bool?[] array2 = new bool?[] { null, true, false }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableBool(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableByteTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; byte?[] array2 = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableByte(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableCharTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; char?[] array2 = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableChar(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableDecimalTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; decimal?[] array2 = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableDecimal(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableDoubleTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; double?[] array2 = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableDouble(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableEnumTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; E?[] array2 = new E?[] { null, (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableEnum(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableEnumLongTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; El?[] array2 = new El?[] { null, (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableEnumLong(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableFloatTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; float?[] array2 = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableFloat(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableIntTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; int?[] array2 = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableInt(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableLongTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; long?[] array2 = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableLong(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableStructTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; S?[] array2 = new S?[] { null, default(S), new S() }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableStruct(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableSByteTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; sbyte?[] array2 = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableSByte(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableStructWithStringTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Sc?[] array2 = new Sc?[] { null, default(Sc), new Sc(), new Sc(null) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableStructWithString(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableStructWithStringAndFieldTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Scs?[] array2 = new Scs?[] { null, default(Scs), new Scs(), new Scs(null, new S()) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableStructWithStringAndField(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableShortTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; short?[] array2 = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableShort(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableStructWithTwoValuesTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Sp?[] array2 = new Sp?[] { null, default(Sp), new Sp(), new Sp(5, 5.0) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableStructWithTwoValues(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableStructWithValueTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; Ss?[] array2 = new Ss?[] { null, default(Ss), new Ss(), new Ss(new S()) }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableStructWithValue(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableUIntTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; uint?[] array2 = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableUInt(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableULongTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; ulong?[] array2 = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableULong(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableUShortTest(bool useInterpreter) { bool[] array1 = new bool[] { false, true }; ushort?[] array2 = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableUShort(array1[i], array2[j], array2[k], useInterpreter); } } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableGenericWithStructRestrictionWithEnumTest(bool useInterpreter) { CheckTernaryNullableGenericWithStructRestrictionHelper<E>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableGenericWithStructRestrictionWithStructTest(bool useInterpreter) { CheckTernaryNullableGenericWithStructRestrictionHelper<S>(useInterpreter); } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckTernaryNullableGenericWithStructRestrictionWithStructWithStringAndFieldTest(bool useInterpreter) { CheckTernaryNullableGenericWithStructRestrictionHelper<Scs>(useInterpreter); } #endregion #region Generic helpers private static void CheckTernaryNullableGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct { bool[] array1 = new bool[] { false, true }; Ts?[] array2 = new Ts?[] { default(Ts), new Ts() }; for (int i = 0; i < array1.Length; i++) { for (int j = 0; j < array2.Length; j++) { for (int k = 0; k < array2.Length; k++) { VerifyNullableGenericWithStructRestriction<Ts>(array1[i], array2[j], array2[k], useInterpreter); } } } } #endregion #region Test verifiers private static void VerifyNullableBool(bool condition, bool? a, bool? b, bool useInterpreter) { Expression<Func<bool?>> e = Expression.Lambda<Func<bool?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?))), Enumerable.Empty<ParameterExpression>()); Func<bool?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableByte(bool condition, byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?))), Enumerable.Empty<ParameterExpression>()); Func<byte?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableChar(bool condition, char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?))), Enumerable.Empty<ParameterExpression>()); Func<char?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableDecimal(bool condition, decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableDouble(bool condition, double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableEnum(bool condition, E? a, E? b, bool useInterpreter) { Expression<Func<E?>> e = Expression.Lambda<Func<E?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(E?)), Expression.Constant(b, typeof(E?))), Enumerable.Empty<ParameterExpression>()); Func<E?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableEnumLong(bool condition, El? a, El? b, bool useInterpreter) { Expression<Func<El?>> e = Expression.Lambda<Func<El?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(El?)), Expression.Constant(b, typeof(El?))), Enumerable.Empty<ParameterExpression>()); Func<El?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableFloat(bool condition, float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableInt(bool condition, int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableLong(bool condition, long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableStruct(bool condition, S? a, S? b, bool useInterpreter) { Expression<Func<S?>> e = Expression.Lambda<Func<S?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(S?)), Expression.Constant(b, typeof(S?))), Enumerable.Empty<ParameterExpression>()); Func<S?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableSByte(bool condition, sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?))), Enumerable.Empty<ParameterExpression>()); Func<sbyte?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableStructWithString(bool condition, Sc? a, Sc? b, bool useInterpreter) { Expression<Func<Sc?>> e = Expression.Lambda<Func<Sc?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Sc?)), Expression.Constant(b, typeof(Sc?))), Enumerable.Empty<ParameterExpression>()); Func<Sc?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableStructWithStringAndField(bool condition, Scs? a, Scs? b, bool useInterpreter) { Expression<Func<Scs?>> e = Expression.Lambda<Func<Scs?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Scs?)), Expression.Constant(b, typeof(Scs?))), Enumerable.Empty<ParameterExpression>()); Func<Scs?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableShort(bool condition, short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableStructWithTwoValues(bool condition, Sp? a, Sp? b, bool useInterpreter) { Expression<Func<Sp?>> e = Expression.Lambda<Func<Sp?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Sp?)), Expression.Constant(b, typeof(Sp?))), Enumerable.Empty<ParameterExpression>()); Func<Sp?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableStructWithValue(bool condition, Ss? a, Ss? b, bool useInterpreter) { Expression<Func<Ss?>> e = Expression.Lambda<Func<Ss?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Ss?)), Expression.Constant(b, typeof(Ss?))), Enumerable.Empty<ParameterExpression>()); Func<Ss?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableUInt(bool condition, uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableULong(bool condition, ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableUShort(bool condition, ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } private static void VerifyNullableGenericWithStructRestriction<Ts>(bool condition, Ts? a, Ts? b, bool useInterpreter) where Ts : struct { Expression<Func<Ts?>> e = Expression.Lambda<Func<Ts?>>( Expression.Condition( Expression.Constant(condition, typeof(bool)), Expression.Constant(a, typeof(Ts?)), Expression.Constant(b, typeof(Ts?))), Enumerable.Empty<ParameterExpression>()); Func<Ts?> f = e.Compile(useInterpreter); Assert.Equal(condition ? a : b, f()); } #endregion } }
/* **************************************************************************** * * 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 * vspython@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. * * ***************************************************************************/ using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Resources; using System.Threading; using CommonSR = Microsoft.VisualStudioTools.Project.SR; namespace Microsoft.PythonTools.Project { internal class SR : CommonSR { public const string PythonToolsForVisualStudio = "PythonToolsForVisualStudio"; public const string NoCompletionsCompletion = "NoCompletionsCompletion"; public const string WarningUnknownType = "WarningUnknownType"; public const string WarningAnalysisNotCurrent = "WarningAnalysisNotCurrent"; public const string AnalyzingProject = "AnalyzingProject"; public const string SearchPaths = "SearchPaths"; public const string SearchPathContainerProperties = "SearchPathProperties"; public const string SearchPathProperties = "SearchPathProperties"; public const string SelectFolderForSearchPath = "SelectFolderForSearchPath"; public const string Environments = "Environments"; public const string EnvironmentRemoveConfirmation = "EnvironmentRemoveConfirmation"; public const string EnvironmentDeleteConfirmation = "EnvironmentDeleteConfirmation"; public const string EnvironmentDeleteError = "EnvironmentDeleteError"; public const string GlobalDefaultSuffix = "GlobalDefaultSuffix"; public const string PackageFullName = "PackageFullName"; public const string PackageFullNameDescription = "PackageFullNameDescription"; public const string EnvironmentIdDisplayName = "EnvironmentIdDisplayName"; public const string EnvironmentIdDescription = "EnvironmentIdDescription"; public const string EnvironmentVersionDisplayName = "EnvironmentVersionDisplayName"; public const string EnvironmentVersionDescription = "EnvironmentVersionDescription"; public const string BaseInterpreterDisplayName = "BaseInterpreterDisplayName"; public const string BaseInterpreterDescription = "BaseInterpreterDescription"; public const string InstallPip = "InstallPip"; public const string InstallEasyInstall = "InstallEasyInstall"; public const string UninstallPackage = "UninstallPackage"; public const string UninstallPackages = "UninstallPackages"; public const string PackageInstalling = "PackageInstalling"; public const string PackageInstallingSeeOutputWindow = "PackageInstallingSeeOutputWindow"; public const string PackageInstallSucceeded = "PackageInstallSucceeded"; public const string PackageInstallFailed = "PackageInstallFailed"; public const string PackageInstallFailedExitCode = "PackageInstallFailedExitCode"; public const string PackageUninstalling = "PackageUninstalling"; public const string PackageUninstallingSeeOutputWindow = "PackageUninstallingSeeOutputWindow"; public const string PackageUninstallSucceeded = "PackageUninstallSucceeded"; public const string PackageUninstallFailed = "PackageUninstallFailed"; public const string PackageUninstallFailedExitCode = "PackageUninstallFailedExitCode"; public const string PipInstalling = "PipInstalling"; public const string PipInstallSucceeded = "PipInstallSucceeded"; public const string PipInstallFailedExitCode = "PipInstallFailedExitCode"; public const string VirtualEnvCreating = "VirtualEnvCreating"; public const string VirtualEnvCreationSucceeded = "VirtualEnvCreationSucceeded"; public const string VirtualEnvCreationFailed = "VirtualEnvCreationFailed"; public const string VirtualEnvCreationFailedExitCode = "VirtualEnvCreationFailedExitCode"; public const string VirtualEnvAddFailed = "VirtualEnvAddFailed"; public const string ErrorRunningCustomCommand = "ErrorRunningCustomCommand"; public const string ErrorBuildingCustomCommand = "ErrorBuildingCustomCommand"; public const string ErrorCommandAlreadyRunning = "ErrorCommandAlreadyRunning"; public const string FailedToReadResource = "FailedToReadResource"; public const string CustomCommandReplTitle = "CustomCommandReplTitle"; public const string CustomCommandPrerequisitesContent = "CustomCommandPrerequisitesContent"; public const string CustomCommandPrerequisitesInstruction = "CustomCommandPrerequisitesInstruction"; public const string CustomCommandPrerequisitesInstallMissing = "CustomCommandPrerequisitesInstallMissing"; public const string CustomCommandPrerequisitesInstallMissingSubtext = "CustomCommandPrerequisitesInstallMissingSubtext"; public const string CustomCommandPrerequisitesRunAnyway = "CustomCommandPrerequisitesRunAnyway"; public const string CustomCommandPrerequisitesDoNotRun = "CustomCommandPrerequisitesDoNotRun"; public const string PythonMenuLabel = "PythonMenuLabel"; public const string NoInterpretersAvailable = "NoInterpretersAvailable"; public const string NoStartupFileAvailable = "NoStartupFileAvailable"; public const string MissingEnvironment = "MissingEnvironment"; public const string ErrorImportWizardUnauthorizedAccess = "ErrorImportWizardUnauthorizedAccess"; public const string ErrorImportWizardException = "ErrorImportWizardException"; public const string StatusImportWizardError = "StatusImportWizardError"; public const string StatusImportWizardStarting = "StatusImportWizardStarting"; public const string ImportWizardProjectExists = "ImportWizardProjectExists"; public const string ImportWizardDefaultProjectCustomization = "ImportWizardDefaultProjectCustomization"; public const string ImportWizardBottleProjectCustomization = "ImportWizardBottleProjectCustomization"; public const string ImportWizardDjangoProjectCustomization = "ImportWizardDjangoProjectCustomization"; public const string ImportWizardFlaskProjectCustomization = "ImportWizardFlaskProjectCustomization"; public const string ImportWizardGenericWebProjectCustomization = "ImportWizardGenericWebProjectCustomization"; public const string ImportWizardUwpProjectCustomization = "ImportWizardUwpProjectCustomization"; public const string ReplInitializationMessage = "ReplInitializationMessage"; public const string ReplEvaluatorInterpreterNotFound = "ReplEvaluatorInterpreterNotFound"; public const string ReplEvaluatorInterpreterNotConfigured = "ReplEvaluatorInterpreterNotConfigured"; public const string ErrorOpeningInteractiveWindow = "ErrorOpeningInteractiveWindow"; public const string ErrorStartingInteractiveProcess = "ErrorStartingInteractiveProcess"; public const string DefaultLauncherName = "DefaultLauncherName"; public const string DefaultLauncherDescription = "DefaultLauncherDescription"; public const string PythonWebLauncherName = "PythonWebLauncherName"; public const string PythonWebLauncherDescription = "PythonWebLauncherDescription"; public const string PythonWebPropertyPageTitle = "PythonWebPropertyPageTitle"; public const string StaticPatternHelp = "StaticPatternHelp"; public const string StaticRewriteHelp = "StaticRewriteHelp"; public const string StaticPatternError = "StaticPatternError"; public const string WsgiHandlerHelp = "WsgiHandlerHelp"; public const string DebugLaunchWorkingDirectoryMissing = "DebugLaunchWorkingDirectoryMissing"; public const string DebugLaunchInterpreterMissing = "DebugLaunchInterpreterMissing"; public const string DebugLaunchInterpreterMissing_Path = "DebugLaunchInterpreterMissing_Path"; public const string DebugLaunchEnvironmentMissing = "DebugLaunchEnvironmentMissing"; public const string UnresolvedModuleTooltip = "UnresolvedModuleTooltip"; public const string UnresolvedModuleTooltipRefreshing = "UnresolvedModuleTooltipRefreshing"; public const string FillCommentSelectionError = "FillCommentSelectionError"; public const string UpgradedToolsVersion = "UpgradedToolsVersion"; public const string UpgradedUserToolsVersion = "UpgradedUserToolsVersion"; public const string UpgradedBottleImports = "UpgradedBottleImports"; public const string UpgradedFlaskImports = "UpgradedFlaskImports"; public const string UpgradedRemoveCommonProps = "UpgradedRemoveCommonProps"; public const string UpgradedRemoveCommonTargets = "UpgradedRemoveCommonTargets"; public const string ProjectRequiresVWDExpress = "ProjectRequiresVWDExpress"; public const string AddWebRoleSupportFiles = "AddWebRoleSupportFiles"; public const string FunctionClassificationType = "FunctionClassificationType"; public const string ParameterClassificationType = "ParameterClassificationType"; public const string ClassClassificationType = "ClassClassificationType"; public const string ModuleClassificationType = "ModuleClassificationType"; public const string OperatorClassificationType = "OperatorClassificationType"; public const string GroupingClassificationType = "GroupingClassificationType"; public const string CommaClassificationType = "CommaClassificationType"; public const string DotClassificationType = "DotClassificationType"; public const string BuiltinClassificationType = "BuiltinClassificationType"; public const string RequirementsTxtExists = "RequirementsTxtExists"; public const string RequirementsTxtExistsQuestion = "RequirementsTxtExistsQuestion"; public const string RequirementsTxtContentCollapsed = "RequirementsTxtContentCollapsed"; public const string RequirementsTxtContentExpanded = "RequirementsTxtContentExpanded"; public const string RequirementsTxtReplace = "RequirementsTxtReplace"; public const string RequirementsTxtRefresh = "RequirementsTxtRefresh"; public const string RequirementsTxtUpdate = "RequirementsTxtUpdate"; public const string RequirementsTxtReplaceHelp = "RequirementsTxtReplaceHelp"; public const string RequirementsTxtRefreshHelp = "RequirementsTxtRefreshHelp"; public const string RequirementsTxtUpdateHelp = "RequirementsTxtUpdateHelp"; public const string RequirementsTxtInstalling = "RequirementsTxtInstalling"; public const string RequirementsTxtFailedToRead = "RequirementsTxtFailedToRead"; public const string RequirementsTxtFailedToWrite = "RequirementsTxtFailedToWrite"; public const string RequirementsTxtFailedToAddToProject = "RequirementsTxtFailedToAddToProject"; public const string ShouldInstallRequirementsTxtHeader = "ShouldInstallRequirementsTxtHeader"; public const string ShouldInstallRequirementsTxtContent = "ShouldInstallRequirementsTxtContent"; public const string ShouldInstallRequirementsTxtExpandedControl = "ShouldInstallRequirementsTxtExpandedControl"; public const string ShouldInstallRequirementsTxtCollapsedControl = "ShouldInstallRequirementsTxtCollapsedControl"; public const string ShouldInstallRequirementsTxtInstallInto = "ShouldInstallRequirementsTxtInstallInto"; public const string FailedToSaveDiagnosticInfo = "FailedToSaveDiagnosticInfo"; public const string FailedToCollectFilesForPublish = "FailedToCollectFilesForPublish"; public const string FailedToCollectFilesForPublishMessage = "FailedToCollectFilesForPublishMessage"; public const string InsertSnippet = "InsertSnippet"; public const string SurroundWith = "SurroundWith"; public const string ErrorLoadingEnvironmentViewExtensions = "ErrorLoadingEnvironmentViewExtensions"; public const string ErrorLoadingEnvironmentViewExtension = "ErrorLoadingEnvironmentViewExtension"; private static readonly Lazy<ResourceManager> _manager = new Lazy<ResourceManager>( () => new System.Resources.ResourceManager("Microsoft.PythonTools.Resources", typeof(SR).Assembly), LazyThreadSafetyMode.ExecutionAndPublication ); private static ResourceManager Manager { get { return _manager.Value; } } internal static new string GetString(string value, params object[] args) { return GetStringInternal(Manager, value, args) ?? CommonSR.GetString(value, args); } internal static string ProductName { get { return GetString(PythonToolsForVisualStudio); } } } }
using System; using System.Collections; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509.Extension; namespace Org.BouncyCastle.Tests { [TestFixture] public class Pkcs10CertRequestTest : SimpleTest { private static readonly byte[] gost3410EC_A = Base64.Decode( "MIIBOzCB6wIBADB/MQ0wCwYDVQQDEwR0ZXN0MRUwEwYDVQQKEwxEZW1vcyBDbyBMdGQxHjAcBgNV" +"BAsTFUNyeXB0b2dyYXBoeSBkaXZpc2lvbjEPMA0GA1UEBxMGTW9zY293MQswCQYDVQQGEwJydTEZ" +"MBcGCSqGSIb3DQEJARYKc2RiQGRvbC5ydTBjMBwGBiqFAwICEzASBgcqhQMCAiMBBgcqhQMCAh4B" +"A0MABEBYx0P2D7YuuZo5HgdIAUKAXcLBDZ+4LYFgbKjrfStVfH59lc40BQ2FZ7M703hLpXK8GiBQ" +"GEYpKaAuQZnMIpByoAAwCAYGKoUDAgIDA0EAgXMcTrhdOY2Er2tHOSAgnMezqrYxocZTWhxmW5Rl" +"JY6lbXH5rndCn4swFzXU+YhgAsJv1wQBaoZEWRl5WV4/nA=="); private static readonly byte[] gost3410EC_B = Base64.Decode( "MIIBPTCB7QIBADCBgDENMAsGA1UEAxMEdGVzdDEWMBQGA1UEChMNRGVtb3MgQ28gTHRkLjEeMBwG" +"A1UECxMVQ3J5cHRvZ3JhcGh5IGRpdmlzaW9uMQ8wDQYDVQQHEwZNb3Njb3cxCzAJBgNVBAYTAnJ1" +"MRkwFwYJKoZIhvcNAQkBFgpzZGJAZG9sLnJ1MGMwHAYGKoUDAgITMBIGByqFAwICIwIGByqFAwIC" +"HgEDQwAEQI5SLoWT7dZVilbV9j5B/fyIDuDs6x4pjqNC2TtFYbpRHrk/Wc5g/mcHvD80tsm5o1C7" +"7cizNzkvAVUM4VT4Dz6gADAIBgYqhQMCAgMDQQAoT5TwJ8o+bSrxckymyo3diwG7ZbSytX4sRiKy" +"wXPWRS9LlBvPO2NqwpS2HUnxSU8rzfL9fJcybATf7Yt1OEVq"); private static readonly byte[] gost3410EC_C = Base64.Decode( "MIIBRDCB9AIBADCBhzEVMBMGA1UEAxMMdGVzdCByZXF1ZXN0MRUwEwYDVQQKEwxEZW1vcyBDbyBM" +"dGQxHjAcBgNVBAsTFUNyeXB0b2dyYXBoeSBkaXZpc2lvbjEPMA0GA1UEBxMGTW9zY293MQswCQYD" +"VQQGEwJydTEZMBcGCSqGSIb3DQEJARYKc2RiQGRvbC5ydTBjMBwGBiqFAwICEzASBgcqhQMCAiMD" +"BgcqhQMCAh4BA0MABEBcmGh7OmR4iqqj+ycYo1S1fS7r5PhisSQU2Ezuz8wmmmR2zeTZkdMYCOBa" +"UTMNms0msW3wuYDho7nTDNscHTB5oAAwCAYGKoUDAgIDA0EAVoOMbfyo1Un4Ss7WQrUjHJoiaYW8" +"Ime5LeGGU2iW3ieAv6es/FdMrwTKkqn5dhd3aL/itFg5oQbhyfXw5yw/QQ=="); private static readonly byte[] gost3410EC_ExA = Base64.Decode( "MIIBOzCB6wIBADB/MQ0wCwYDVQQDEwR0ZXN0MRUwEwYDVQQKEwxEZW1vcyBDbyBMdGQxHjAcBgNV" + "BAsTFUNyeXB0b2dyYXBoeSBkaXZpc2lvbjEPMA0GA1UEBxMGTW9zY293MQswCQYDVQQGEwJydTEZ" + "MBcGCSqGSIb3DQEJARYKc2RiQGRvbC5ydTBjMBwGBiqFAwICEzASBgcqhQMCAiQABgcqhQMCAh4B" + "A0MABEDkqNT/3f8NHj6EUiWnK4JbVZBh31bEpkwq9z3jf0u8ZndG56Vt+K1ZB6EpFxLT7hSIos0w" + "weZ2YuTZ4w43OgodoAAwCAYGKoUDAgIDA0EASk/IUXWxoi6NtcUGVF23VRV1L3undB4sRZLp4Vho" + "gQ7m3CMbZFfJ2cPu6QyarseXGYHmazoirH5lGjEo535c1g=="); private static readonly byte[] gost3410EC_ExB = Base64.Decode( "MIIBPTCB7QIBADCBgDENMAsGA1UEAxMEdGVzdDEWMBQGA1UEChMNRGVtb3MgQ28gTHRkLjEeMBwG" + "A1UECxMVQ3J5cHRvZ3JhcGh5IGRpdmlzaW9uMQ8wDQYDVQQHEwZNb3Njb3cxCzAJBgNVBAYTAnJ1" + "MRkwFwYJKoZIhvcNAQkBFgpzZGJAZG9sLnJ1MGMwHAYGKoUDAgITMBIGByqFAwICJAEGByqFAwIC" + "HgEDQwAEQMBWYUKPy/1Kxad9ChAmgoSWSYOQxRnXo7KEGLU5RNSXA4qMUvArWzvhav+EYUfTbWLh" + "09nELDyHt2XQcvgQHnSgADAIBgYqhQMCAgMDQQAdaNhgH/ElHp64mbMaEo1tPCg9Q22McxpH8rCz" + "E0QBpF4H5mSSQVGI5OAXHToetnNuh7gHHSynyCupYDEHTbkZ"); public override string Name { get { return "PKCS10CertRequest"; } } private void generationTest( int keySize, string keyName, string sigName) { IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator(keyName); // kpg.initialize(keySize); kpg.Init(new KeyGenerationParameters(new SecureRandom(), keySize)); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); IDictionary attrs = new Hashtable(); attrs.Add(X509Name.C, "AU"); attrs.Add(X509Name.O, "The Legion of the Bouncy Castle"); attrs.Add(X509Name.L, "Melbourne"); attrs.Add(X509Name.ST, "Victoria"); attrs.Add(X509Name.EmailAddress, "feedback-crypto@bouncycastle.org"); IList order = new ArrayList(); order.Add(X509Name.C); order.Add(X509Name.O); order.Add(X509Name.L); order.Add(X509Name.ST); order.Add(X509Name.EmailAddress); X509Name subject = new X509Name(order, attrs); Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest( sigName, subject, kp.Public, null, kp.Private); byte[] bytes = req1.GetEncoded(); Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes); if (!req2.Verify()) { Fail(sigName + ": Failed Verify check."); } if (!req2.GetPublicKey().Equals(req1.GetPublicKey())) { Fail(keyName + ": Failed public key check."); } } /* * we generate a self signed certificate for the sake of testing - SHA224withECDSA */ private void createECRequest( string algorithm, DerObjectIdentifier algOid) { FpCurve curve = new FpCurve( new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p) new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b ECDomainParameters spec = new ECDomainParameters( curve, // curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d spec); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( // curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q spec); // // // // set up the keys // // // AsymmetricKeyParameter privKey; // AsymmetricKeyParameter pubKey; // // KeyFactory fact = KeyFactory.getInstance("ECDSA"); // // privKey = fact.generatePrivate(privKeySpec); // pubKey = fact.generatePublic(pubKeySpec); Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC encoded."); } // // try with point compression turned off // // ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); FpPoint q = (FpPoint) pubKey.Q; pubKey = new ECPublicKeyParameters( pubKey.AlgorithmName, new FpPoint(q.Curve, q.X, q.Y, false), pubKey.Parameters); req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC uncompressed encoded."); } if (!req.SignatureAlgorithm.ObjectID.Equals(algOid)) { Fail("ECDSA oid incorrect."); } if (req.SignatureAlgorithm.Parameters != null) { Fail("ECDSA parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] b = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(b, 0, b.Length); if (!sig.VerifySignature(req.Signature.GetBytes())) { Fail("signature not mapped correctly."); } } private void createECGostRequest() { string algorithm = "GOST3411withECGOST3410"; IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); ecGostKpg.Init( new ECKeyGenerationParameters( CryptoProObjectIdentifiers.GostR3410x2001CryptoProA, new SecureRandom())); // // set up the keys // AsymmetricCipherKeyPair pair = ecGostKpg.GenerateKeyPair(); AsymmetricKeyParameter privKey = pair.Private; AsymmetricKeyParameter pubKey = pair.Public; Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed Verify check EC."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed Verify check EC encoded."); } if (!req.SignatureAlgorithm.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001)) { Fail("ECGOST oid incorrect."); } if (req.SignatureAlgorithm.Parameters != null) { Fail("ECGOST parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] b = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(b, 0, b.Length); if (!sig.VerifySignature(req.Signature.GetBytes())) { Fail("signature not mapped correctly."); } } private void createPssTest( string algorithm) { // RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( RsaKeyParameters pubKey = new RsaKeyParameters(false, new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); // RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16), new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); // KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); // // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); Pkcs10CertificationRequest req = new Pkcs10CertificationRequest( algorithm, new X509Name("CN=XXX"), pubKey, null, privKey); if (!req.Verify()) { Fail("Failed verify check PSS."); } req = new Pkcs10CertificationRequest(req.GetEncoded()); if (!req.Verify()) { Fail("Failed verify check PSS encoded."); } if (!req.SignatureAlgorithm.ObjectID.Equals(PkcsObjectIdentifiers.IdRsassaPss)) { Fail("PSS oid incorrect."); } if (req.SignatureAlgorithm.Parameters == null) { Fail("PSS parameters incorrect."); } ISigner sig = SignerUtilities.GetSigner(algorithm); sig.Init(false, pubKey); byte[] encoded = req.GetCertificationRequestInfo().GetEncoded(); sig.BlockUpdate(encoded, 0, encoded.Length); if (!sig.VerifySignature(req.Signature.GetBytes())) { Fail("signature not mapped correctly."); } } // previous code found to cause a NullPointerException private void nullPointerTest() { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); AsymmetricCipherKeyPair pair = keyGen.GenerateKeyPair(); IList oids = new ArrayList(); IList values = new ArrayList(); oids.Add(X509Extensions.BasicConstraints); values.Add(new X509Extension(true, new DerOctetString(new BasicConstraints(true)))); oids.Add(X509Extensions.KeyUsage); values.Add(new X509Extension(true, new DerOctetString( new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign)))); SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pair.Public); X509Extension ski = new X509Extension(false, new DerOctetString(subjectKeyIdentifier)); oids.Add(X509Extensions.SubjectKeyIdentifier); values.Add(ski); AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(oids, values))); Pkcs10CertificationRequest p1 = new Pkcs10CertificationRequest( "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private); Pkcs10CertificationRequest p2 = new Pkcs10CertificationRequest( "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private); if (!p1.Equals(p2)) { Fail("cert request comparison failed"); } } public override void PerformTest() { generationTest(512, "RSA", "SHA1withRSA"); generationTest(512, "GOST3410", "GOST3411withGOST3410"); // if (Security.getProvider("SunRsaSign") != null) // { // generationTest(512, "RSA", "SHA1withRSA", "SunRsaSign"); // } // elliptic curve GOST A parameter set Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(gost3410EC_A); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_A."); } // elliptic curve GOST B parameter set req = new Pkcs10CertificationRequest(gost3410EC_B); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_B."); } // elliptic curve GOST C parameter set req = new Pkcs10CertificationRequest(gost3410EC_C); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_C."); } // elliptic curve GOST ExA parameter set req = new Pkcs10CertificationRequest(gost3410EC_ExA); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_ExA."); } // elliptic curve GOST ExB parameter set req = new Pkcs10CertificationRequest(gost3410EC_ExB); if (!req.Verify()) { Fail("Failed Verify check gost3410EC_ExA."); } // elliptic curve openSSL IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); AsymmetricCipherKeyPair kp = g.GenerateKeyPair(); req = new Pkcs10CertificationRequest( "ECDSAWITHSHA1", new X509Name("CN=XXX"), kp.Public, null, kp.Private); if (!req.Verify()) { Fail("Failed Verify check EC."); } createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ECDsaWithSha1); createECRequest("SHA224withECDSA", X9ObjectIdentifiers.ECDsaWithSha224); createECRequest("SHA256withECDSA", X9ObjectIdentifiers.ECDsaWithSha256); createECRequest("SHA384withECDSA", X9ObjectIdentifiers.ECDsaWithSha384); createECRequest("SHA512withECDSA", X9ObjectIdentifiers.ECDsaWithSha512); createECGostRequest(); // TODO The setting of parameters for MGF algorithms is not implemented // createPssTest("SHA1withRSAandMGF1"); // createPssTest("SHA224withRSAandMGF1"); // createPssTest("SHA256withRSAandMGF1"); // createPssTest("SHA384withRSAandMGF1"); nullPointerTest(); } public static void Main( string[] args) { RunTest(new Pkcs10CertRequestTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Microsoft.PackageManagement.Providers.Internal.Bootstrap { using System; using System.Collections.Generic; using System.Linq; using PackageManagement.Internal.Packaging; using PackageManagement.Internal.Utility.Extensions; internal class Feed : Swid { [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Feed(BootstrapRequest request, Swidtag swidtag) : base(request, swidtag) { } internal Feed(BootstrapRequest request, IEnumerable<Link> mirrors) : base(request, mirrors) { } internal Feed(BootstrapRequest request, IEnumerable<Uri> mirrors) : base(request, mirrors) { } /// <summary> /// Follows the feed to find all the *declared latest* versions of packages /// </summary> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query() { if (!IsValid) { return Enumerable.Empty<Package>(); } // first get all the packages that are marked as the latest version. var packages = Packages.Select(packageGroup => new Package(_request, packageGroup.Where(link => link.Attributes[Iso19770_2.Discovery.Latest].IsTrue()))); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query()); // We do not follow to other feeds to find more, because declared latest packages should be in this feed (or a supplemental). return packages.Concat(morePackages); } /// <summary> /// Follows the feed to find all versions of package matching 'name' /// </summary> /// <param name="name">the name or partial name of a package to find</param> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query(string name) { if (!IsValid || string.IsNullOrEmpty(name)) { return Enumerable.Empty<Package>(); } // first get all the packages that are in this feed with a matched name var packages = PackagesFilteredByName(name).Select(packageGroup => new Package(_request, packageGroup)).Where(package => package.IsValid && package.Name.EqualsIgnoreCase(name)); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query(name)); // let's search child feeds that declare that the name of the package in the feed matches the given name var packagesByName = Feeds.Where(feedGroup => feedGroup.Any(link => name.EqualsIgnoreCase(link.Attributes[Iso19770_2.Discovery.Name]))).SelectMany(feed => new Feed(_request, feed).Query(name)); // and search child feeds that the name would be in their range. var packagesByNameRange = Feeds.Where(feedGroup => feedGroup.Any(link => { var minName = link.Attributes[Iso19770_2.Discovery.MinimumName]; var maxName = link.Attributes[Iso19770_2.Discovery.MaximumName]; if (string.IsNullOrEmpty(minName) || string.IsNullOrEmpty(maxName)) { return false; } return (String.Compare(minName, name, StringComparison.OrdinalIgnoreCase) <= 0 && String.Compare(name, maxName, StringComparison.OrdinalIgnoreCase) <= 0); })).SelectMany(feed => new Feed(_request, feed).Query(name)); return packages.Concat(morePackages).Concat(packagesByName).Concat(packagesByNameRange); } /// <summary> /// Follows the feed to find the specific version of a package matching 'name' /// </summary> /// <param name="name"></param> /// <param name="version"></param> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query(string name, string version) { if (string.IsNullOrEmpty(version)) { return Query(name); } if (!IsValid || string.IsNullOrEmpty(name)) { return Enumerable.Empty<Package>(); } // first get all the packages that are in this feed with a matched name and version var packages = PackagesFilteredByName(name).Select(packageGroup => new Package(_request, packageGroup)) .Where(package => package.IsValid && package.Name.EqualsIgnoreCase(name) && SoftwareIdentityVersionComparer.CompareVersions(package.VersionScheme, package.Version, version) == 0); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query(name, version)); // let's search child feeds that declare that the name of the package in the feed matches the given name // and the version is either in the specified range of the link, or there is no specified version. var packagesByName = Feeds.Where(feedGroup => feedGroup.Any(link => { if (name.EqualsIgnoreCase(link.Attributes[Iso19770_2.Discovery.Name])) { var minVer = link.Attributes[Iso19770_2.Discovery.MinimumVersion]; if (!string.IsNullOrEmpty(minVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, minVer, version) > 0) { // the minimum version in the feed is greater than the specified version. return false; } } var maxVer = link.Attributes[Iso19770_2.Discovery.MaximumVersion]; if (!string.IsNullOrEmpty(maxVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, version, maxVer) > 0) { // the given version is greater than the maximum version in the feed. return false; } } return true; } return false; })).SelectMany(feed => new Feed(_request, feed).Query(name, version)); // and search child feeds that the name would be in their range. // (version matches have to wait till we Query() that feed, since name ranges and version ranges shouldn't be on the same link.) var packagesByNameRange = Feeds.Where(feedGroup => feedGroup.Any(link => { var minName = link.Attributes[Iso19770_2.Discovery.MinimumName]; var maxName = link.Attributes[Iso19770_2.Discovery.MaximumName]; if (string.IsNullOrEmpty(minName) || string.IsNullOrEmpty(maxName)) { return false; } return (String.Compare(minName, name, StringComparison.OrdinalIgnoreCase) <= 0 && String.Compare(name, maxName, StringComparison.OrdinalIgnoreCase) <= 0); })).SelectMany(feed => new Feed(_request, feed).Query(name, version)); return packages.Concat(morePackages).Concat(packagesByName).Concat(packagesByNameRange); } /// <summary> /// Follows the feed to find the all versions of a package matching 'name', in the given range /// </summary> /// <param name="name"></param> /// <param name="minimumVersion"></param> /// <param name="maximumVersion"></param> /// <returns>A set of packages</returns> internal IEnumerable<Package> Query(string name, string minimumVersion, string maximumVersion) { if (string.IsNullOrEmpty(minimumVersion) && string.IsNullOrEmpty(maximumVersion)) { return Query(name); } if (!IsValid || string.IsNullOrEmpty(name)) { return Enumerable.Empty<Package>(); } // first get all the packages that are in this feed with a matched name and version var packages = PackagesFilteredByName(name).Select(packageGroup => new Package(_request, packageGroup)).Where(package => { if (package.IsValid && package.Name.EqualsIgnoreCase(name)) { if (!string.IsNullOrWhiteSpace(minimumVersion)) { if (SoftwareIdentityVersionComparer.CompareVersions(package.VersionScheme, package.Version, minimumVersion) < 0) { // a minimum version was specified, but the package version is less than the specified minimumversion. return false; } } if (!string.IsNullOrWhiteSpace(maximumVersion)) { if (SoftwareIdentityVersionComparer.CompareVersions(package.VersionScheme, package.Version, maximumVersion) > 0) { // a maximum version was specified, but the package version is more than the specified maximumversion. return false; } } // the version is in the range asked for. return true; } // not a valid package, or incorrect name. return false; }); // then follow any supplemental links to more declared latest packages. var morePackages = More.SelectMany(nextGroup => new Feed(_request, nextGroup).Query(name, minimumVersion, maximumVersion)); // let's search child feeds that declare that the name of the package in the feed matches the given name // and the version is either in the specified range of the link, or there is no specified version. var packagesByName = Feeds.Where(feedGroup => feedGroup.Any(link => { if (name.EqualsIgnoreCase(link.Attributes[Iso19770_2.Discovery.Name])) { // first, ensure that the requested minimum version is lower than the maximum version found in the feed. var maxVer = link.Attributes[Iso19770_2.Discovery.MaximumVersion]; if (!string.IsNullOrEmpty(maxVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, minimumVersion, maxVer) <= 0) { // the minimum version is greater than the maximum version in the feed. return false; } } // and then ensure that the requested maximum version is greater than the minimum version found in the feed. var minVer = link.Attributes[Iso19770_2.Discovery.MinimumVersion]; if (!string.IsNullOrEmpty(minVer)) { // since we don't know the version scheme at this point, so we just have to guess. if (SoftwareIdentityVersionComparer.CompareVersions(Iso19770_2.VersionScheme.Unknown, maximumVersion, minVer) >= 0) { // the maximum version less than the minimum version in the feed. return false; } } return true; } return false; })).SelectMany(feed => new Feed(_request, feed).Query(name, minimumVersion, maximumVersion)); // and search child feeds that the name would be in their range. // (version matches have to wait till we Query() that feed, since name ranges and version ranges shouldn't be on the same link.) var packagesByNameRange = Feeds.Where(feedGroup => feedGroup.Any(link => { var minName = link.Attributes[Iso19770_2.Discovery.MinimumName]; var maxName = link.Attributes[Iso19770_2.Discovery.MaximumName]; if (string.IsNullOrEmpty(minName) || string.IsNullOrEmpty(maxName)) { return false; } return (String.Compare(minName, name, StringComparison.OrdinalIgnoreCase) <= 0 && String.Compare(name, maxName, StringComparison.OrdinalIgnoreCase) <= 0); })).SelectMany(feed => new Feed(_request, feed).Query(name, minimumVersion, maximumVersion)); return packages.Concat(morePackages).Concat(packagesByName).Concat(packagesByNameRange); } } }
using System; using System.Collections.Generic; using System.Linq; using Signum.Entities; using Signum.Engine.Maps; using Signum.Entities.Reflection; using Signum.Utilities; using System.Reflection; using Signum.Entities.Basics; using Signum.Engine.DynamicQuery; using Signum.Utilities.Reflection; namespace Signum.Engine.Basics { public static class TypeLogic { public static Dictionary<PrimaryKey, Type> IdToType { get { return Schema.Current.typeCachesLazy.Value.IdToType; } } public static Dictionary<Type, PrimaryKey> TypeToId { get { return Schema.Current.typeCachesLazy.Value.TypeToId; } } public static Dictionary<Type, TypeEntity> TypeToEntity { get { return Schema.Current.typeCachesLazy.Value.TypeToEntity; } } public static Dictionary<TypeEntity, Type> EntityToType { get { return Schema.Current.typeCachesLazy.Value.EntityToType; } } public static void AssertStarted(SchemaBuilder sb) { sb.AssertDefined(ReflectionTools.GetMethodInfo(() => Start(null!))); } public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { Schema schema = Schema.Current; sb.Include<TypeEntity>() .WithQuery(() => t => new { Entity = t, t.Id, t.TableName, t.CleanName, t.ClassName, t.Namespace, }); schema.SchemaCompleted += () => { var attributes = schema.Tables.Keys.Select(t => KeyValuePair.Create(t, t.GetCustomAttribute<EntityKindAttribute>(true))).ToList(); var errors = attributes.Where(a => a.Value == null).ToString(a => "Type {0} does not have an EntityTypeAttribute".FormatWith(a.Key.Name), "\r\n"); if (errors.HasText()) throw new InvalidOperationException(errors); }; schema.Initializing += () => { schema.typeCachesLazy.Load(); }; schema.typeCachesLazy = sb.GlobalLazy(() => new TypeCaches(schema), new InvalidateWith(typeof(TypeEntity)), Schema.Current.InvalidateMetadata); TypeEntity.SetTypeEntityCallbacks( t => TypeToEntity.GetOrThrow(t), t => EntityToType.GetOrThrow(t)); } } public static Dictionary<TypeEntity, Type> TryEntityToType(Replacements replacements) { return (from dn in Administrator.TryRetrieveAll<TypeEntity>(replacements) join t in Schema.Current.Tables.Keys on dn.FullClassName equals (EnumEntity.Extract(t) ?? t).FullName select (dn, t)).ToDictionary(a => a.dn, a => a.t); } public static SqlPreCommand? Schema_Synchronizing(Replacements replacements) { var schema = Schema.Current; var isPostgres = schema.Settings.IsPostgres; Dictionary<string, TypeEntity> should = GenerateSchemaTypes().ToDictionaryEx(s => s.TableName, "tableName in memory"); var currentList = Administrator.TryRetrieveAll<TypeEntity>(replacements); { //External entities are nt asked in SchemaSynchronizer replacements.AskForReplacements( currentList.Where(t => schema.IsExternalDatabase(ObjectName.Parse(t.TableName, isPostgres).Schema.Database)).Select(a => a.TableName).ToHashSet(), should.Values.Where(t => schema.IsExternalDatabase(ObjectName.Parse(t.TableName, isPostgres).Schema.Database)).Select(a => a.TableName).ToHashSet(), Replacements.KeyTables); } Dictionary<string, TypeEntity> current = ApplyReplacementsToOld(replacements, currentList.ToDictionaryEx(c => c.TableName, "tableName in database"), Replacements.KeyTables); { //Temporal solution until applications are updated var repeated = should.Keys.Select(k => ObjectName.Parse(k, isPostgres)).GroupBy(a => a.Name).Where(a => a.Count() > 1).Select(a => a.Key).Concat( current.Keys.Select(k => ObjectName.Parse(k, isPostgres)).GroupBy(a => a.Name).Where(a => a.Count() > 1).Select(a => a.Key)).ToList(); Func<string, string> simplify = tn => { ObjectName name = ObjectName.Parse(tn, isPostgres); return repeated.Contains(name.Name) ? name.ToString() : name.Name; }; should = should.SelectDictionary(simplify, v => v); current = current.SelectDictionary(simplify, v => v); } Table table = schema.Table<TypeEntity>(); using (replacements.WithReplacedDatabaseName()) return Synchronizer.SynchronizeScript( Spacing.Double, should, current, createNew: (tn, s) => table.InsertSqlSync(s), removeOld: (tn, c) => table.DeleteSqlSync(c, t => t.CleanName == c.CleanName), mergeBoth: (tn, s, c) => { var originalCleanName = c.CleanName; var originalFullName = c.FullClassName; if (c.TableName != s.TableName) { var pc = ObjectName.Parse(c.TableName, isPostgres); var ps = ObjectName.Parse(s.TableName, isPostgres); if (!EqualsIgnoringDatabasePrefix(pc, ps)) { c.TableName = ps.ToString(); } } c.CleanName = s.CleanName; c.Namespace = s.Namespace; c.ClassName = s.ClassName; return table.UpdateSqlSync(c, t => t.CleanName == originalCleanName, comment: originalFullName); }); } static bool EqualsIgnoringDatabasePrefix(ObjectName pc, ObjectName ps) => ps.Name == pc.Name && pc.Schema.Name == ps.Schema.Name && Suffix(pc.Schema.Database?.Name) == Suffix(ps.Schema.Database?.Name); static string? Suffix(string? name) => name.TryAfterLast("_") ?? name; static Dictionary<string, O> ApplyReplacementsToOld<O>(this Replacements replacements, Dictionary<string, O> oldDictionary, string replacementsKey) { if (!replacements.ContainsKey(replacementsKey)) return oldDictionary; Dictionary<string, string> dic = replacements[replacementsKey]; return oldDictionary.SelectDictionary(a => dic.TryGetC(a) ?? a, v => v); } internal static SqlPreCommand Schema_Generating() { Table table = Schema.Current.Table<TypeEntity>(); return GenerateSchemaTypes() .Select((e, i) => table.InsertSqlSync(e, suffix: i.ToString())) .Combine(Spacing.Simple)! .PlainSqlCommand(); } internal static List<TypeEntity> GenerateSchemaTypes() { var list = (from tab in Schema.Current.Tables.Values let type = EnumEntity.Extract(tab.Type) ?? tab.Type select new TypeEntity { TableName = tab.Name.ToString(), CleanName = Reflector.CleanTypeName(type), Namespace = type.Namespace!, ClassName = type.Name, }).ToList(); return list; } public static Dictionary<string, Type> NameToType { get { return Schema.Current.NameToType; } } public static Dictionary<Type, string> TypeToName { get { return Schema.Current.TypeToName; } } public static Type GetType(string cleanName) { return NameToType.GetOrThrow(cleanName, "Type {0} not found in the schema"); } public static Type? TryGetType(string cleanName) { return NameToType.TryGetC(cleanName); } public static string GetCleanName(Type type) { return TypeToName.GetOrThrow(type, "Type {0} not found in the schema"); } public static string? TryGetCleanName(Type type) { return TypeToName.TryGetC(type); } } internal class TypeCaches { public readonly Dictionary<Type, TypeEntity> TypeToEntity; public readonly Dictionary<TypeEntity, Type> EntityToType; public readonly Dictionary<PrimaryKey, Type> IdToType; public readonly Dictionary<Type, PrimaryKey> TypeToId; public TypeCaches(Schema current) { TypeToEntity = EnumerableExtensions.JoinRelaxed( Database.RetrieveAll<TypeEntity>(), current.Tables.Keys, t => t.FullClassName, t => (EnumEntity.Extract(t) ?? t).FullName, (typeEntity, type) => (typeEntity, type), "caching {0}".FormatWith(current.Table(typeof(TypeEntity)).Name) ).ToDictionary(a => a.type, a => a.typeEntity); EntityToType = TypeToEntity.Inverse(); TypeToId = TypeToEntity.SelectDictionary(k => k, v => v.Id); IdToType = TypeToId.Inverse(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using GoCardless.Internals; using GoCardless.Resources; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace GoCardless.Services { /// <summary> /// Service class for working with event resources. /// /// Events are stored for all webhooks. An event refers to a resource which /// has been updated, for example a payment which has been collected, or a /// mandate which has been transferred. See [here](#event-actions) for a /// complete list of event types. /// </summary> public class EventService { private readonly GoCardlessClient _goCardlessClient; /// <summary> /// Constructor. Users of this library should not call this. An instance of this /// class can be accessed through an initialised GoCardlessClient. /// </summary> public EventService(GoCardlessClient goCardlessClient) { _goCardlessClient = goCardlessClient; } /// <summary> /// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of /// your events. /// </summary> /// <param name="request">An optional `EventListRequest` representing the query parameters for this list request.</param> /// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param> /// <returns>A set of event resources</returns> public Task<EventListResponse> ListAsync(EventListRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new EventListRequest(); var urlParams = new List<KeyValuePair<string, object>> {}; return _goCardlessClient.ExecuteAsync<EventListResponse>("GET", "/events", urlParams, request, null, null, customiseRequestMessage); } /// <summary> /// Get a lazily enumerated list of events. /// This acts like the #list method, but paginates for you automatically. /// </summary> public IEnumerable<Event> All(EventListRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new EventListRequest(); string cursor = null; do { request.After = cursor; var result = Task.Run(() => ListAsync(request, customiseRequestMessage)).Result; foreach (var item in result.Events) { yield return item; } cursor = result.Meta?.Cursors?.After; } while (cursor != null); } /// <summary> /// Get a lazily enumerated list of events. /// This acts like the #list method, but paginates for you automatically. /// </summary> public IEnumerable<Task<IReadOnlyList<Event>>> AllAsync(EventListRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new EventListRequest(); return new TaskEnumerable<IReadOnlyList<Event>, string>(async after => { request.After = after; var list = await this.ListAsync(request, customiseRequestMessage); return Tuple.Create(list.Events, list.Meta?.Cursors?.After); }); } /// <summary> /// Retrieves the details of a single event. /// </summary> /// <param name="identity">Unique identifier, beginning with "EV".</param> /// <param name="request">An optional `EventGetRequest` representing the query parameters for this get request.</param> /// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param> /// <returns>A single event resource</returns> public Task<EventResponse> GetAsync(string identity, EventGetRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new EventGetRequest(); if (identity == null) throw new ArgumentException(nameof(identity)); var urlParams = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("identity", identity), }; return _goCardlessClient.ExecuteAsync<EventResponse>("GET", "/events/:identity", urlParams, request, null, null, customiseRequestMessage); } } /// <summary> /// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your /// events. /// </summary> public class EventListRequest { /// <summary> /// Limit to events with a given `action`. /// </summary> [JsonProperty("action")] public string Action { get; set; } /// <summary> /// Cursor pointing to the start of the desired set. /// </summary> [JsonProperty("after")] public string After { get; set; } /// <summary> /// Cursor pointing to the end of the desired set. /// </summary> [JsonProperty("before")] public string Before { get; set; } /// <summary> /// ID of a [billing request](#billing-requests-billing-requests). If /// specified, this endpoint will return all events for the given /// billing request. /// </summary> [JsonProperty("billing_request")] public string BillingRequest { get; set; } /// <summary> /// Limit to records created within certain times. /// </summary> [JsonProperty("created_at")] public CreatedAtParam CreatedAt { get; set; } /// <summary> /// Specify filters to limit records by creation time. /// </summary> public class CreatedAtParam { /// <summary> /// Limit to records created after the specified date-time. /// </summary> [JsonProperty("gt")] public DateTimeOffset? GreaterThan { get; set; } /// <summary> /// Limit to records created on or after the specified date-time. /// </summary> [JsonProperty("gte")] public DateTimeOffset? GreaterThanOrEqual { get; set; } /// <summary> /// Limit to records created before the specified date-time. /// </summary> [JsonProperty("lt")] public DateTimeOffset? LessThan { get; set; } /// <summary> ///Limit to records created on or before the specified date-time. /// </summary> [JsonProperty("lte")] public DateTimeOffset? LessThanOrEqual { get; set; } } /// <summary> /// Includes linked resources in the response. Must be used with the /// `resource_type` parameter specified. The include should be one of: /// <ul> /// <li>`payment`</li> /// <li>`mandate`</li> /// <li>`payer_authorisation`</li> /// <li>`payout`</li> /// <li>`refund`</li> /// <li>`subscription`</li> /// <li>`instalment_schedule`</li> /// <li>`creditor`</li> /// <li>`billing_request`</li> /// </ul> /// </summary> [JsonProperty("include")] public EventInclude? Include { get; set; } /// <summary> /// Includes linked resources in the response. Must be used with the /// `resource_type` parameter specified. The include should be one of: /// <ul> /// <li>`payment`</li> /// <li>`mandate`</li> /// <li>`payer_authorisation`</li> /// <li>`payout`</li> /// <li>`refund`</li> /// <li>`subscription`</li> /// <li>`instalment_schedule`</li> /// <li>`creditor`</li> /// <li>`billing_request`</li> /// </ul> /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum EventInclude { /// <summary>`include` with a value of "payment"</summary> [EnumMember(Value = "payment")] Payment, /// <summary>`include` with a value of "mandate"</summary> [EnumMember(Value = "mandate")] Mandate, /// <summary>`include` with a value of "payout"</summary> [EnumMember(Value = "payout")] Payout, /// <summary>`include` with a value of "refund"</summary> [EnumMember(Value = "refund")] Refund, /// <summary>`include` with a value of "subscription"</summary> [EnumMember(Value = "subscription")] Subscription, /// <summary>`include` with a value of "instalment_schedule"</summary> [EnumMember(Value = "instalment_schedule")] InstalmentSchedule, /// <summary>`include` with a value of "creditor"</summary> [EnumMember(Value = "creditor")] Creditor, /// <summary>`include` with a value of "payer_authorisation"</summary> [EnumMember(Value = "payer_authorisation")] PayerAuthorisation, /// <summary>`include` with a value of "billing_request"</summary> [EnumMember(Value = "billing_request")] BillingRequest, } /// <summary> /// Number of records to return. /// </summary> [JsonProperty("limit")] public int? Limit { get; set; } /// <summary> /// ID of a [mandate](#core-endpoints-mandates). If specified, this /// endpoint will return all events for the given mandate. /// </summary> [JsonProperty("mandate")] public string Mandate { get; set; } /// <summary> /// ID of an event. If specified, this endpoint will return all events /// whose parent_event is the given event ID. /// </summary> [JsonProperty("parent_event")] public string ParentEvent { get; set; } /// <summary> /// ID of a [payer authorisation](#core-endpoints-payer-authorisations). /// </summary> [JsonProperty("payer_authorisation")] public string PayerAuthorisation { get; set; } /// <summary> /// ID of a [payment](#core-endpoints-payments). If specified, this /// endpoint will return all events for the given payment. /// </summary> [JsonProperty("payment")] public string Payment { get; set; } /// <summary> /// ID of a [payout](#core-endpoints-payouts). If specified, this /// endpoint will return all events for the given payout. /// </summary> [JsonProperty("payout")] public string Payout { get; set; } /// <summary> /// ID of a [refund](#core-endpoints-refunds). If specified, this /// endpoint will return all events for the given refund. /// </summary> [JsonProperty("refund")] public string Refund { get; set; } /// <summary> /// Type of resource that you'd like to get all events for. Cannot be /// used together with the `payment`, `payer_authorisation`, /// `mandate`, `subscription`, `instalment_schedule`, `creditor`, /// `refund` or `payout` parameter. The type can be one of: /// <ul> /// <li>`billing_requests`</li> /// <li>`creditors`</li> /// <li>`instalment_schedules`</li> /// <li>`mandates`</li> /// <li>`payer_authorisations`</li> /// <li>`payments`</li> /// <li>`payouts`</li> /// <li>`refunds`</li> /// <li>`subscriptions`</li> /// </ul> /// </summary> [JsonProperty("resource_type")] public EventResourceType? ResourceType { get; set; } /// <summary> /// Type of resource that you'd like to get all events for. Cannot be /// used together with the `payment`, `payer_authorisation`, /// `mandate`, `subscription`, `instalment_schedule`, `creditor`, /// `refund` or `payout` parameter. The type can be one of: /// <ul> /// <li>`billing_requests`</li> /// <li>`creditors`</li> /// <li>`instalment_schedules`</li> /// <li>`mandates`</li> /// <li>`payer_authorisations`</li> /// <li>`payments`</li> /// <li>`payouts`</li> /// <li>`refunds`</li> /// <li>`subscriptions`</li> /// </ul> /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum EventResourceType { /// <summary>`resource_type` with a value of "billing_requests"</summary> [EnumMember(Value = "billing_requests")] BillingRequests, /// <summary>`resource_type` with a value of "creditors"</summary> [EnumMember(Value = "creditors")] Creditors, /// <summary>`resource_type` with a value of "instalment_schedules"</summary> [EnumMember(Value = "instalment_schedules")] InstalmentSchedules, /// <summary>`resource_type` with a value of "mandates"</summary> [EnumMember(Value = "mandates")] Mandates, /// <summary>`resource_type` with a value of "organisations"</summary> [EnumMember(Value = "organisations")] Organisations, /// <summary>`resource_type` with a value of "payer_authorisations"</summary> [EnumMember(Value = "payer_authorisations")] PayerAuthorisations, /// <summary>`resource_type` with a value of "payments"</summary> [EnumMember(Value = "payments")] Payments, /// <summary>`resource_type` with a value of "payouts"</summary> [EnumMember(Value = "payouts")] Payouts, /// <summary>`resource_type` with a value of "refunds"</summary> [EnumMember(Value = "refunds")] Refunds, /// <summary>`resource_type` with a value of "subscriptions"</summary> [EnumMember(Value = "subscriptions")] Subscriptions, } /// <summary> /// ID of a [subscription](#core-endpoints-subscriptions). If specified, /// this endpoint will return all events for the given subscription. /// </summary> [JsonProperty("subscription")] public string Subscription { get; set; } } /// <summary> /// Retrieves the details of a single event. /// </summary> public class EventGetRequest { } /// <summary> /// An API response for a request returning a single event. /// </summary> public class EventResponse : ApiResponse { /// <summary> /// The event from the response. /// </summary> [JsonProperty("events")] public Event Event { get; private set; } } /// <summary> /// An API response for a request returning a list of events. /// </summary> public class EventListResponse : ApiResponse { /// <summary> /// The list of events from the response. /// </summary> [JsonProperty("events")] public IReadOnlyList<Event> Events { get; private set; } /// <summary> /// Response metadata (e.g. pagination cursors) /// </summary> public Meta Meta { get; private set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.Transactions.Configuration; namespace System.Transactions { /// <summary> /// Summary description for TransactionException. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TransactionException : SystemException { internal static bool IncludeDistributedTxId(Guid distributedTxId) { return (distributedTxId != Guid.Empty && AppSettings.IncludeDistributedTxIdInExceptionMessage); } internal static TransactionException Create(string message, Exception innerException) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException==null?string.Empty:innerException.ToString()); } return new TransactionException(message, innerException); } internal static TransactionException Create(TraceSourceType traceSource, string message, Exception innerException) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException==null?string.Empty:innerException.ToString()); } return new TransactionException(message, innerException); } internal static TransactionException CreateTransactionStateException(Exception innerException) { return Create(SR.TransactionStateException, innerException); } internal static Exception CreateEnlistmentStateException(Exception innerException, Guid distributedTxId) { string messagewithTxId = SR.EnlistmentStateException; if (IncludeDistributedTxId(distributedTxId)) messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(TransactionExceptionType.InvalidOperationException, messagewithTxId, innerException==null?string.Empty:innerException.ToString()); } return new InvalidOperationException(messagewithTxId, innerException); } internal static Exception CreateInvalidOperationException(TraceSourceType traceSource, string message, Exception innerException) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.InvalidOperationException, message, innerException==null?string.Empty:innerException.ToString()); } return new InvalidOperationException(message, innerException); } /// <summary> /// /// </summary> public TransactionException() { } /// <summary> /// /// </summary> /// <param name="message"></param> public TransactionException(string message) : base(message) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TransactionException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected TransactionException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static TransactionException Create(string message, Guid distributedTxId) { if (IncludeDistributedTxId(distributedTxId)) { return new TransactionException(string.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId)); } return new TransactionException(message); } internal static TransactionException Create(string message, Exception innerException, Guid distributedTxId) { string messagewithTxId = message; if (IncludeDistributedTxId(distributedTxId)) messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); return Create(messagewithTxId, innerException); } internal static TransactionException Create(TraceSourceType traceSource, string message, Exception innerException, Guid distributedTxId) { string messagewithTxId = message; if (IncludeDistributedTxId(distributedTxId)) messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); return Create(traceSource, messagewithTxId, innerException); } internal static TransactionException Create(TraceSourceType traceSource, string message, Guid distributedTxId) { if (IncludeDistributedTxId(distributedTxId)) { return new TransactionException(string.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId)); } return new TransactionException(message); } internal static TransactionException CreateTransactionStateException(Exception innerException, Guid distributedTxId) { return Create(SR.TransactionStateException, innerException, distributedTxId); } internal static Exception CreateTransactionCompletedException(Guid distributedTxId) { string messagewithTxId = SR.TransactionAlreadyCompleted; if (IncludeDistributedTxId(distributedTxId)) messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(TransactionExceptionType.InvalidOperationException, messagewithTxId, string.Empty); } return new InvalidOperationException(messagewithTxId); } internal static Exception CreateInvalidOperationException(TraceSourceType traceSource, string message, Exception innerException, Guid distributedTxId) { string messagewithTxId = message; if (IncludeDistributedTxId(distributedTxId)) messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); return CreateInvalidOperationException(traceSource, messagewithTxId, innerException); } } /// <summary> /// Summary description for TransactionAbortedException. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TransactionAbortedException : TransactionException { internal static new TransactionAbortedException Create(string message, Exception innerException, Guid distributedTxId) { string messagewithTxId = message; if (IncludeDistributedTxId(distributedTxId)) messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); return TransactionAbortedException.Create(messagewithTxId, innerException); } internal static new TransactionAbortedException Create(string message, Exception innerException) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionAbortedException, message, innerException==null?string.Empty:innerException.ToString()); } return new TransactionAbortedException(message, innerException); } /// <summary> /// /// </summary> public TransactionAbortedException() : base(SR.TransactionAborted) { } /// <summary> /// /// </summary> /// <param name="message"></param> public TransactionAbortedException(string message) : base(message) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TransactionAbortedException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> internal TransactionAbortedException(Exception innerException) : base(SR.TransactionAborted, innerException) { } internal TransactionAbortedException(Exception innerException, Guid distributedTxId) : base(IncludeDistributedTxId(distributedTxId) ? string.Format(SR.DistributedTxIDInTransactionException, SR.TransactionAborted, distributedTxId) : SR.TransactionAborted, innerException) { } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected TransactionAbortedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Summary description for TransactionInDoubtException. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TransactionInDoubtException : TransactionException { internal static new TransactionInDoubtException Create(TraceSourceType traceSource, string message, Exception innerException, Guid distributedTxId) { string messagewithTxId = message; if (IncludeDistributedTxId(distributedTxId)) messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); return TransactionInDoubtException.Create(traceSource, messagewithTxId, innerException); } internal static new TransactionInDoubtException Create(TraceSourceType traceSource, string message, Exception innerException) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(traceSource, TransactionExceptionType.TransactionInDoubtException, message, innerException==null?string.Empty:innerException.ToString()); } return new TransactionInDoubtException(message, innerException); } /// <summary> /// /// </summary> public TransactionInDoubtException() : base(SR.TransactionIndoubt) { } /// <summary> /// /// </summary> /// <param name="message"></param> public TransactionInDoubtException(string message) : base(message) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TransactionInDoubtException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected TransactionInDoubtException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Summary description for TransactionManagerCommunicationException. /// </summary> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TransactionManagerCommunicationException : TransactionException { internal static new TransactionManagerCommunicationException Create(string message, Exception innerException) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionManagerCommunicationException, message, innerException==null?string.Empty:innerException.ToString()); } return new TransactionManagerCommunicationException(message, innerException); } internal static TransactionManagerCommunicationException Create(Exception innerException) { return Create(SR.TransactionManagerCommunicationException, innerException); } /// <summary> /// /// </summary> public TransactionManagerCommunicationException() : base(SR.TransactionManagerCommunicationException) { } /// <summary> /// /// </summary> /// <param name="message"></param> public TransactionManagerCommunicationException(string message) : base(message) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TransactionManagerCommunicationException( string message, Exception innerException ) : base(message, innerException) { } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected TransactionManagerCommunicationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TransactionPromotionException : TransactionException { /// <summary> /// /// </summary> public TransactionPromotionException() : this(SR.PromotionFailed) { } /// <summary> /// /// </summary> /// <param name="message"></param> public TransactionPromotionException(string message) : base(message) { } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TransactionPromotionException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected TransactionPromotionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.UserInterface; using osu.Framework.Testing; using osuTK; using osuTK.Input; namespace osu.Framework.Tests.Visual.UserInterface { public class TestSceneRearrangeableListContainer : ManualInputManagerTestScene { private TestRearrangeableList list; private Container listContainer; [SetUp] public void Setup() => Schedule(() => { Child = listContainer = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500, 300), Child = list = new TestRearrangeableList { RelativeSizeAxes = Axes.Both } }; }); [Test] public void TestAddItem() { for (int i = 0; i < 5; i++) { int localI = i; addItems(1); AddAssert($"last item is \"{i}\"", () => list.ChildrenOfType<RearrangeableListItem<int>>().Last().Model == localI); } } [Test] public void TestBindBeforeLoad() { AddStep("create list", () => list = new TestRearrangeableList { RelativeSizeAxes = Axes.Both }); AddStep("bind list to items", () => list.Items.BindTo(new BindableList<int>(new[] { 1, 2, 3 }))); AddStep("add list to hierarchy", () => listContainer.Add(list)); } [Test] public void TestAddDuplicateItemsFails() { const int item = 1; AddStep("add item 1", () => list.Items.Add(item)); AddAssert("add same item throws", () => { try { list.Items.Add(item); return false; } catch (InvalidOperationException) { return true; } }); } [Test] public void TestRemoveItem() { const int item_count = 5; addItems(item_count); List<Drawable> items = null; AddStep("get item references", () => items = new List<Drawable>(list.ItemMap.Values.ToList())); for (int i = 0; i < item_count; i++) { int localI = i; AddStep($"remove item \"{i}\"", () => list.Items.Remove(localI)); AddAssert($"first item is not \"{i}\"", () => list.ChildrenOfType<RearrangeableListItem<int>>().FirstOrDefault()?.Model != localI); } AddUntilStep("removed items were disposed", () => items.Count(i => i.IsDisposed) == item_count); } [Test] public void TestClearItems() { addItems(5); AddStep("clear items", () => list.Items.Clear()); AddAssert("no items contained", () => !list.ChildrenOfType<RearrangeableListItem<string>>().Any()); } [Test] public void TestRearrangeByDrag() { addItems(5); addDragSteps(1, 4, new[] { 0, 2, 3, 4, 1 }); addDragSteps(1, 3, new[] { 0, 2, 1, 3, 4 }); addDragSteps(0, 3, new[] { 2, 1, 3, 0, 4 }); addDragSteps(3, 4, new[] { 2, 1, 0, 4, 3 }); addDragSteps(4, 2, new[] { 4, 2, 1, 0, 3 }); addDragSteps(2, 4, new[] { 2, 4, 1, 0, 3 }); } [Test] public void TestRearrangeByDragWithHiddenItems() { addItems(6); AddStep("hide item zero", () => list.ListContainer.First(i => i.Model == 0).Hide()); addDragSteps(2, 5, new[] { 0, 1, 3, 4, 5, 2 }); addDragSteps(2, 4, new[] { 0, 1, 3, 2, 4, 5 }); addDragSteps(1, 4, new[] { 0, 3, 2, 4, 1, 5 }); addDragSteps(4, 5, new[] { 0, 3, 2, 1, 5, 4 }); addDragSteps(5, 3, new[] { 0, 5, 3, 2, 1, 4 }); addDragSteps(3, 5, new[] { 0, 3, 5, 2, 1, 4 }); } [Test] public void TestRearrangeByDragAfterRemoval() { addItems(5); addDragSteps(0, 4, new[] { 1, 2, 3, 4, 0 }); addDragSteps(1, 4, new[] { 2, 3, 4, 1, 0 }); addDragSteps(2, 4, new[] { 3, 4, 2, 1, 0 }); addDragSteps(3, 4, new[] { 4, 3, 2, 1, 0 }); AddStep("remove 3 and 2", () => { list.Items.Remove(3); list.Items.Remove(2); }); addDragSteps(4, 0, new[] { 1, 0, 4 }); addDragSteps(0, 1, new[] { 0, 1, 4 }); addDragSteps(4, 0, new[] { 4, 0, 1 }); } [Test] public void TestRemoveAfterDragScrollThenTryRearrange() { addItems(5); // Scroll AddStep("move mouse to first item", () => InputManager.MoveMouseTo(getItem(0))); AddStep("begin a drag", () => InputManager.PressButton(MouseButton.Left)); AddStep("move the mouse", () => InputManager.MoveMouseTo(getItem(0), new Vector2(0, 30))); AddStep("end the drag", () => InputManager.ReleaseButton(MouseButton.Left)); AddStep("remove all but one item", () => { for (int i = 0; i < 4; i++) list.Items.Remove(getItem(i).Model); }); // Drag AddStep("move mouse to first dragger", () => InputManager.MoveMouseTo(getDragger(4))); AddStep("begin a drag", () => InputManager.PressButton(MouseButton.Left)); AddStep("move the mouse", () => InputManager.MoveMouseTo(getDragger(4), new Vector2(0, 30))); AddStep("end the drag", () => InputManager.ReleaseButton(MouseButton.Left)); } [Test] public void TestScrolledWhenDraggedToBoundaries() { addItems(100); AddStep("scroll to item 50", () => list.ScrollTo(50)); float scrollPosition = 0; AddStep("get scroll position", () => scrollPosition = list.ScrollPosition); AddStep("move to 52", () => { InputManager.MoveMouseTo(getDragger(52)); InputManager.PressButton(MouseButton.Left); }); AddStep("drag to 0", () => InputManager.MoveMouseTo(getDragger(0), new Vector2(0, -1))); AddUntilStep("scrolling up", () => list.ScrollPosition < scrollPosition); AddUntilStep("52 is the first item", () => list.Items.First() == 52); AddStep("drag to 99", () => InputManager.MoveMouseTo(getDragger(99), new Vector2(0, 1))); AddUntilStep("scrolling down", () => list.ScrollPosition > scrollPosition); AddUntilStep("52 is the last item", () => list.Items.Last() == 52); } [Test] public void TestRearrangeWhileAddingItems() { addItems(2); AddStep("grab item 0", () => { InputManager.MoveMouseTo(getDragger(0)); InputManager.PressButton(MouseButton.Left); }); AddStep("move to bottom", () => InputManager.MoveMouseTo(list.ToScreenSpace(list.LayoutRectangle.BottomLeft) + new Vector2(0, 10))); addItems(10); AddUntilStep("0 is the last item", () => list.Items.Last() == 0); } [Test] public void TestRearrangeWhileRemovingItems() { addItems(50); AddStep("grab item 0", () => { InputManager.MoveMouseTo(getDragger(0)); InputManager.PressButton(MouseButton.Left); }); AddStep("move to bottom", () => InputManager.MoveMouseTo(list.ToScreenSpace(list.LayoutRectangle.BottomLeft) + new Vector2(0, 20))); int lastItem = 49; AddRepeatStep("remove item", () => { list.Items.Remove(lastItem--); }, 25); AddUntilStep("0 is the last item", () => list.Items.Last() == 0); AddRepeatStep("remove item", () => { list.Items.Remove(lastItem--); }, 25); AddStep("release button", () => InputManager.ReleaseButton(MouseButton.Left)); } [Test] public void TestNotScrolledToTopOnRemove() { addItems(100); float scrollPosition = 0; AddStep("scroll to item 50", () => { list.ScrollTo(50); scrollPosition = list.ScrollPosition; }); AddStep("remove item 50", () => list.Items.Remove(50)); AddAssert("scroll hasn't changed", () => list.ScrollPosition == scrollPosition); } [Test] public void TestRemoveDuringLoadAndReAdd() { TestDelayedLoadRearrangeableList delayedList = null; AddStep("create list", () => Child = delayedList = new TestDelayedLoadRearrangeableList()); AddStep("add item 1", () => delayedList.Items.Add(1)); AddStep("remove item 1", () => delayedList.Items.Remove(1)); AddStep("add item 1", () => delayedList.Items.Add(1)); AddStep("allow load", () => delayedList.AllowLoad.Release(100)); AddUntilStep("only one item", () => delayedList.ChildrenOfType<BasicRearrangeableListItem<int>>().Count() == 1); } private void addDragSteps(int from, int to, int[] expectedSequence) { AddStep($"move to {from}", () => { InputManager.MoveMouseTo(getDragger(from)); InputManager.PressButton(MouseButton.Left); }); AddStep($"drag to {to}", () => { var fromDragger = getDragger(from); var toDragger = getDragger(to); InputManager.MoveMouseTo(getDragger(to), fromDragger.ScreenSpaceDrawQuad.TopLeft.Y < toDragger.ScreenSpaceDrawQuad.TopLeft.Y ? new Vector2(0, 1) : new Vector2(0, -1)); }); assertSequence(expectedSequence); AddStep("release button", () => InputManager.ReleaseButton(MouseButton.Left)); } private void assertSequence(params int[] sequence) { AddAssert($"sequence is {string.Join(", ", sequence)}", () => list.Items.SequenceEqual(sequence.Select(value => value))); } private void addItems(int count) { AddStep($"add {count} item(s)", () => { int startId = list.Items.Count == 0 ? 0 : list.Items.Max() + 1; for (int i = 0; i < count; i++) list.Items.Add(startId + i); }); AddUntilStep("wait for items to load", () => list.ItemMap.Values.All(i => i.IsLoaded)); } private RearrangeableListItem<int> getItem(int index) => list.ChildrenOfType<RearrangeableListItem<int>>().First(i => i.Model == index); private BasicRearrangeableListItem<int>.Button getDragger(int index) => list.ChildrenOfType<BasicRearrangeableListItem<int>>().First(i => i.Model == index) .ChildrenOfType<BasicRearrangeableListItem<int>.Button>().First(); private class TestRearrangeableList : BasicRearrangeableListContainer<int> { public float ScrollPosition => ScrollContainer.Current; public new IReadOnlyDictionary<int, RearrangeableListItem<int>> ItemMap => base.ItemMap; public new FillFlowContainer<RearrangeableListItem<int>> ListContainer => base.ListContainer; public void ScrollTo(int item) => ScrollContainer.ScrollTo(this.ChildrenOfType<BasicRearrangeableListItem<int>>().First(i => i.Model == item), false); } private class TestDelayedLoadRearrangeableList : BasicRearrangeableListContainer<int> { public readonly SemaphoreSlim AllowLoad = new SemaphoreSlim(0, 100); protected override BasicRearrangeableListItem<int> CreateBasicItem(int item) => new TestRearrangeableListItem(item, AllowLoad); private class TestRearrangeableListItem : BasicRearrangeableListItem<int> { private readonly SemaphoreSlim allowLoad; public TestRearrangeableListItem(int item, SemaphoreSlim allowLoad) : base(item, false) { this.allowLoad = allowLoad; } [BackgroundDependencyLoader] private void load() { if (!allowLoad.Wait(TimeSpan.FromSeconds(10))) throw new TimeoutException(); } } } } }
// 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.Win32.SafeHandles; using System.Diagnostics; using System.Threading; using CFStringRef = System.IntPtr; using CFRunLoopRef = System.IntPtr; namespace System.Net.NetworkInformation { // OSX implementation of NetworkChange // See <SystemConfiguration/SystemConfiguration.h> and its documentation, as well as // the documentation for CFRunLoop for more information on the components involved. public partial class NetworkChange { private static object s_lockObj = new object(); // The dynamic store. We listen to changes in the IPv4 and IPv6 address keys. // When those keys change, our callback below is called (OnAddressChanged). private static SafeCreateHandle s_dynamicStoreRef; // The callback used when registered keys in the dynamic store change. private static readonly Interop.SystemConfiguration.SCDynamicStoreCallBack s_storeCallback = OnAddressChanged; // The RunLoop source, created over the above SCDynamicStore. private static SafeCreateHandle s_runLoopSource; // Listener thread that adds the RunLoopSource to its RunLoop. private static Thread s_runLoopThread; // The listener thread's CFRunLoop. private static CFRunLoopRef s_runLoop; // Use an event to try to prevent StartRaisingEvents from returning before the // RunLoop actually begins. This will mitigate a race condition where the watcher // thread hasn't completed initialization and stop is called before the RunLoop has even started. private static readonly AutoResetEvent s_runLoopStartedEvent = new AutoResetEvent(false); private static readonly AutoResetEvent s_runLoopEndedEvent = new AutoResetEvent(false); public static event NetworkAddressChangedEventHandler NetworkAddressChanged { add { if (value != null) { lock (s_lockObj) { if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0) { CreateAndStartRunLoop(); } s_addressChangedSubscribers.TryAdd(value, ExecutionContext.Capture()); } } } remove { if (value != null) { lock (s_lockObj) { bool hadAddressChangedSubscribers = s_addressChangedSubscribers.Count != 0; s_addressChangedSubscribers.Remove(value); if (hadAddressChangedSubscribers && s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0) { StopRunLoop(); } } } } } public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { if (value != null) { lock (s_lockObj) { if (s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0) { CreateAndStartRunLoop(); } else { Debug.Assert(s_runLoop != IntPtr.Zero); } s_availabilityChangedSubscribers.TryAdd(value, ExecutionContext.Capture()); } } } remove { if (value != null) { lock (s_lockObj) { bool hadSubscribers = s_addressChangedSubscribers.Count != 0 || s_availabilityChangedSubscribers.Count != 0; s_availabilityChangedSubscribers.Remove(value); if (hadSubscribers && s_addressChangedSubscribers.Count == 0 && s_availabilityChangedSubscribers.Count == 0) { StopRunLoop(); } } } } } private static unsafe void CreateAndStartRunLoop() { Debug.Assert(s_dynamicStoreRef == null); var storeContext = new Interop.SystemConfiguration.SCDynamicStoreContext(); using (SafeCreateHandle storeName = Interop.CoreFoundation.CFStringCreateWithCString("NetworkAddressChange.OSX")) { s_dynamicStoreRef = Interop.SystemConfiguration.SCDynamicStoreCreate( storeName.DangerousGetHandle(), s_storeCallback, &storeContext); } // Notification key string parts. We want to match notification keys // for any kind of IP address change, addition, or removal. using (SafeCreateHandle dynamicStoreDomainStateString = Interop.CoreFoundation.CFStringCreateWithCString("State:")) using (SafeCreateHandle compAnyRegexString = Interop.CoreFoundation.CFStringCreateWithCString("[^/]+")) using (SafeCreateHandle entNetIpv4String = Interop.CoreFoundation.CFStringCreateWithCString("IPv4")) using (SafeCreateHandle entNetIpv6String = Interop.CoreFoundation.CFStringCreateWithCString("IPv6")) { if (dynamicStoreDomainStateString.IsInvalid || compAnyRegexString.IsInvalid || entNetIpv4String.IsInvalid || entNetIpv6String.IsInvalid) { s_dynamicStoreRef.Dispose(); s_dynamicStoreRef = null; throw new NetworkInformationException(SR.net_PInvokeError); } using (SafeCreateHandle ipv4Pattern = Interop.SystemConfiguration.SCDynamicStoreKeyCreateNetworkServiceEntity( dynamicStoreDomainStateString.DangerousGetHandle(), compAnyRegexString.DangerousGetHandle(), entNetIpv4String.DangerousGetHandle())) using (SafeCreateHandle ipv6Pattern = Interop.SystemConfiguration.SCDynamicStoreKeyCreateNetworkServiceEntity( dynamicStoreDomainStateString.DangerousGetHandle(), compAnyRegexString.DangerousGetHandle(), entNetIpv6String.DangerousGetHandle())) using (SafeCreateHandle patterns = Interop.CoreFoundation.CFArrayCreate( new CFStringRef[2] { ipv4Pattern.DangerousGetHandle(), ipv6Pattern.DangerousGetHandle() }, (UIntPtr)2)) { // Try to register our pattern strings with the dynamic store instance. if (patterns.IsInvalid || !Interop.SystemConfiguration.SCDynamicStoreSetNotificationKeys( s_dynamicStoreRef.DangerousGetHandle(), IntPtr.Zero, patterns.DangerousGetHandle())) { s_dynamicStoreRef.Dispose(); s_dynamicStoreRef = null; throw new NetworkInformationException(SR.net_PInvokeError); } // Create a "RunLoopSource" that can be added to our listener thread's RunLoop. s_runLoopSource = Interop.SystemConfiguration.SCDynamicStoreCreateRunLoopSource( s_dynamicStoreRef.DangerousGetHandle(), IntPtr.Zero); } } s_runLoopThread = new Thread(RunLoopThreadStart); s_runLoopThread.Start(); s_runLoopStartedEvent.WaitOne(); // Wait for the new thread to finish initialization. } private static void RunLoopThreadStart() { Debug.Assert(s_runLoop == IntPtr.Zero); s_runLoop = Interop.RunLoop.CFRunLoopGetCurrent(); Interop.RunLoop.CFRunLoopAddSource( s_runLoop, s_runLoopSource.DangerousGetHandle(), Interop.RunLoop.kCFRunLoopDefaultMode.DangerousGetHandle()); s_runLoopStartedEvent.Set(); Interop.RunLoop.CFRunLoopRun(); Interop.RunLoop.CFRunLoopRemoveSource( s_runLoop, s_runLoopSource.DangerousGetHandle(), Interop.RunLoop.kCFRunLoopDefaultMode.DangerousGetHandle()); s_runLoop = IntPtr.Zero; s_runLoopSource.Dispose(); s_runLoopSource = null; s_dynamicStoreRef.Dispose(); s_dynamicStoreRef = null; s_runLoopEndedEvent.Set(); } private static void StopRunLoop() { Debug.Assert(s_runLoop != IntPtr.Zero); Debug.Assert(s_runLoopSource != null); Debug.Assert(s_dynamicStoreRef != null); // Allow RunLoop to finish current processing. SpinWait.SpinUntil(() => Interop.RunLoop.CFRunLoopIsWaiting(s_runLoop)); Interop.RunLoop.CFRunLoopStop(s_runLoop); s_runLoopEndedEvent.WaitOne(); } private static void OnAddressChanged(IntPtr store, IntPtr changedKeys, IntPtr info) { Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null; Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> availabilityChangedSubscribers = null; lock (s_lockObj) { if (s_addressChangedSubscribers.Count > 0) { addressChangedSubscribers = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers); } if (s_availabilityChangedSubscribers.Count > 0) { availabilityChangedSubscribers = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityChangedSubscribers); } } if (addressChangedSubscribers != null) { foreach (KeyValuePair<NetworkAddressChangedEventHandler, ExecutionContext> subscriber in addressChangedSubscribers) { NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(ec, s_runAddressChangedHandler, handler); } } } if (availabilityChangedSubscribers != null) { bool isAvailable = NetworkInterface.GetIsNetworkAvailable(); NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable; foreach (KeyValuePair<NetworkAvailabilityChangedEventHandler, ExecutionContext> subscriber in availabilityChangedSubscribers) { NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, args); } else { ExecutionContext.Run(ec, callbackContext, handler); } } } } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Text; using System.Text.RegularExpressions; /** * INSTRUCTIONS * * - Only modify properties in the USER SETTINGS region. * - All content is loaded from external files (pc_AboutEntry_YourProduct. Use the templates! */ /** * Used to pop up the window on import. */ public class pb_AboutWindowSetup : AssetPostprocessor { #region Initialization static void OnPostprocessAllAssets ( string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { string[] entries = System.Array.FindAll(importedAssets, name => name.Contains("pc_AboutEntry") && !name.EndsWith(".meta")); foreach(string str in entries) if( pb_AboutWindow.Init(str, false) ) break; } #endregion } public class pb_AboutWindow : EditorWindow { /** * Modify these constants to customize about screen. */ #region User Settings /* Path to the root folder */ const string ABOUT_ROOT = "Assets/ProCore/" + pb_Constant.PRODUCT_NAME + "/About"; /** * Changelog.txt file should follow this format: * * | -- Product Name 2.1.0 - * | * | # Features * | - All kinds of awesome stuff * | - New flux capacitor design achieves time travel at lower velocities. * | - Dark matter reactor recalibrated. * | * | # Bug Fixes * | - No longer explodes when spacebar is pressed. * | - Fix rolling issue in Rickmeter. * | * | # Changes * | - Changed Blue to Red. * | - Enter key now causes explosions. * * This path is relative to the PRODUCT_ROOT path. * * Note that your changelog may contain multiple entries. Only the top-most * entry will be displayed. */ /** * Advertisement thumb constructor is: * new AdvertisementThumb( PathToAdImage : string, URLToPurchase : string, ProductDescription : string ) * Provide as many or few (or none) as desired. * * Notes - The http:// part is required. Partial URLs do not work on Mac. */ [SerializeField] public static AdvertisementThumb[] advertisements = new AdvertisementThumb[] { new AdvertisementThumb( ABOUT_ROOT + "/Images/ProBuilder_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/probuilder/", "Build and Texture Geometry In-Editor"), new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGrids_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progrids/", "True Grids and Grid-Snapping"), new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGroups_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progroups/", "Hide, Freeze, Group, & Organize"), new AdvertisementThumb( ABOUT_ROOT + "/Images/Prototype_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/prototype/", "Design and Build With Zero Lag"), new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickBrush_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickbrush/", "Quickly Add Detail Geometry"), new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickDecals_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickdecals/", "Add Dirt, Splatters, Posters, etc"), new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickEdit_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickedit/", "Edit Imported Meshes!"), }; #endregion /* Recommend you do not modify these. */ #region Private Fields (automatically populated) private string AboutEntryPath = ""; private string ProductName = ""; // private string ProductIdentifer = ""; private string ProductVersion = ""; private string ProductRevision = ""; private string ChangelogPath = ""; private string BannerPath = ABOUT_ROOT + "/Images/Banner.png"; const int AD_HEIGHT = 96; /** * Struct containing data for use in Advertisement shelf. */ [System.Serializable] public struct AdvertisementThumb { public Texture2D image; public string url; public string about; public GUIContent guiContent; public AdvertisementThumb(string imagePath, string url, string about) { guiContent = new GUIContent("", about); this.image = LoadAssetAtPath<Texture2D>(imagePath); guiContent.image = this.image; this.url = url; this.about = about; } } Texture2D banner; // populated by first entry in changelog string changelog = ""; #endregion #region Init /** * Return true if Init took place, false if not. */ public static bool Init (string aboutEntryPath, bool fromMenu) { string identifier, version; if( !GetField(aboutEntryPath, "version: ", out version) || !GetField(aboutEntryPath, "identifier: ", out identifier)) return false; if(fromMenu || EditorPrefs.GetString(identifier) != version) { string tname; pb_AboutWindow win; if(GetField(aboutEntryPath, "name: ", out tname)) win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow), true, tname, true); else win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow)); win.SetAboutEntryPath(aboutEntryPath); win.ShowUtility(); EditorPrefs.SetString(identifier, version); return true; } else { return false; } } public void OnEnable() { banner = LoadAssetAtPath<Texture2D>(BannerPath); // With Unity 4 (on PC) if you have different values for minSize and maxSize, // they do not apply restrictions to window size. #if !UNITY_5 this.minSize = new Vector2(banner.width + 12, banner.height * 7); this.maxSize = new Vector2(banner.width + 12, banner.height * 7); #else this.minSize = new Vector2(banner.width + 12, banner.height * 6); this.maxSize = new Vector2(banner.width + 12, 1440); #endif } public void SetAboutEntryPath(string path) { AboutEntryPath = path; PopulateDataFields(AboutEntryPath); } static T LoadAssetAtPath<T>(string InPath) where T : UnityEngine.Object { return (T) AssetDatabase.LoadAssetAtPath(InPath, typeof(T)); } #endregion #region GUI Color LinkColor = new Color(0f, .682f, .937f, 1f); GUIStyle boldTextStyle, headerTextStyle, linkTextStyle; GUIStyle advertisementStyle; Vector2 scroll = Vector2.zero, adScroll = Vector2.zero; // int mm = 32; void OnGUI() { headerTextStyle = headerTextStyle ?? new GUIStyle( EditorStyles.boldLabel );//GUI.skin.label); headerTextStyle.fontSize = 16; linkTextStyle = linkTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label); linkTextStyle.normal.textColor = LinkColor; linkTextStyle.alignment = TextAnchor.MiddleLeft; boldTextStyle = boldTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label); boldTextStyle.fontStyle = FontStyle.Bold; boldTextStyle.alignment = TextAnchor.MiddleLeft; // #if UNITY_4 // richTextLabel.richText = true; // #endif advertisementStyle = advertisementStyle ?? new GUIStyle(GUI.skin.button); advertisementStyle.normal.background = null; if(banner != null) GUILayout.Label(banner); // mm = EditorGUI.IntField(new Rect(Screen.width - 200, 100, 200, 18), "W: ", mm); // grr stupid rich text faiiilluuure { GUILayout.Label("Thank you for purchasing " + ProductName + ". Your support allows us to keep developing this and future tools for everyone.", EditorStyles.wordWrappedLabel); GUILayout.Space(2); GUILayout.Label("Read these quick \"ProTips\" before starting:", headerTextStyle); GUILayout.BeginHorizontal(); GUILayout.Label("1) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Register", boldTextStyle, GUILayout.MinWidth(58), GUILayout.MaxWidth(58)); GUILayout.Label("for instant email updates, send your invoice # to", GUILayout.MinWidth(284), GUILayout.MaxWidth(284)); if( GUILayout.Button("contact@procore3d.com", linkTextStyle, GUILayout.MinWidth(142), GUILayout.MaxWidth(142)) ) Application.OpenURL("mailto:contact@procore3d.com?subject=Sign me up for the Beta!"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("2) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Report bugs", boldTextStyle, GUILayout.MinWidth(82), GUILayout.MaxWidth(82)); GUILayout.Label("to the ProCore Forum at", GUILayout.MinWidth(144), GUILayout.MaxWidth(144)); if( GUILayout.Button("www.procore3d.com/forum", linkTextStyle, GUILayout.MinWidth(162), GUILayout.MaxWidth(162)) ) Application.OpenURL("http://www.procore3d.com/forum"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("3) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Customize!", boldTextStyle, GUILayout.MinWidth(74), GUILayout.MaxWidth(74)); GUILayout.Label("Click on \"Edit > Preferences\" then \"" + ProductName + "\"", GUILayout.MinWidth(276), GUILayout.MaxWidth(276)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("4) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16)); GUILayout.Label("Documentation", boldTextStyle, GUILayout.MinWidth(102), GUILayout.MaxWidth(102)); GUILayout.Label("Tutorials, & more info:", GUILayout.MinWidth(132), GUILayout.MaxWidth(132)); if( GUILayout.Button("www.procore3d.com/" + ProductName.ToLower(), linkTextStyle, GUILayout.MinWidth(190), GUILayout.MaxWidth(190)) ) Application.OpenURL("http://www.procore3d.com/" + ProductName.ToLower()); GUILayout.EndHorizontal(); GUILayout.Space(4); GUILayout.BeginHorizontal(GUILayout.MaxWidth(50)); GUILayout.Label("Links:", boldTextStyle); linkTextStyle.fontStyle = FontStyle.Italic; linkTextStyle.alignment = TextAnchor.MiddleCenter; if( GUILayout.Button("procore3d.com", linkTextStyle)) Application.OpenURL("http://www.procore3d.com"); if( GUILayout.Button("facebook", linkTextStyle)) Application.OpenURL("http://www.facebook.com/probuilder3d"); if( GUILayout.Button("twitter", linkTextStyle)) Application.OpenURL("http://www.twitter.com/probuilder3d"); linkTextStyle.fontStyle = FontStyle.Normal; GUILayout.EndHorizontal(); GUILayout.Space(4); } HorizontalLine(); // always bold the first line (cause it's the version info stuff) scroll = EditorGUILayout.BeginScrollView(scroll); GUILayout.Label(ProductName + " | version: " + ProductVersion + " | revision: " + ProductRevision, EditorStyles.boldLabel); GUILayout.Label("\n" + changelog); EditorGUILayout.EndScrollView(); HorizontalLine(); GUILayout.Label("More ProCore Products", EditorStyles.boldLabel); int pad = advertisements.Length * AD_HEIGHT > Screen.width ? 22 : 6; adScroll = EditorGUILayout.BeginScrollView(adScroll, false, false, GUILayout.MinHeight(AD_HEIGHT + pad), GUILayout.MaxHeight(AD_HEIGHT + pad)); GUILayout.BeginHorizontal(); foreach(AdvertisementThumb ad in advertisements) { if(ad.url.ToLower().Contains(ProductName.ToLower())) continue; if(GUILayout.Button(ad.guiContent, advertisementStyle, GUILayout.MinWidth(AD_HEIGHT), GUILayout.MaxWidth(AD_HEIGHT), GUILayout.MinHeight(AD_HEIGHT), GUILayout.MaxHeight(AD_HEIGHT))) { Application.OpenURL(ad.url); } } GUILayout.EndHorizontal(); EditorGUILayout.EndScrollView(); /* shill other products */ } /** * Draw a horizontal line across the screen and update the guilayout. */ void HorizontalLine() { Rect r = GUILayoutUtility.GetLastRect(); Color og = GUI.backgroundColor; GUI.backgroundColor = Color.black; GUI.Box(new Rect(0f, r.y + r.height + 2, Screen.width, 2f), ""); GUI.backgroundColor = og; GUILayout.Space(6); } #endregion #region Data Parsing /* rich text ain't wuurkin' in unity 3.5 */ const string RemoveBraketsRegex = "(\\<.*?\\>)"; /** * Open VersionInfo and Changelog and pull out text to populate vars for OnGUI to display. */ void PopulateDataFields(string entryPath) { /* Get data from VersionInfo.txt */ TextAsset versionInfo = LoadAssetAtPath<TextAsset>( entryPath ); ProductName = ""; // ProductIdentifer = ""; ProductVersion = ""; ProductRevision = ""; ChangelogPath = ""; if(versionInfo != null) { string[] txt = versionInfo.text.Split('\n'); foreach(string cheese in txt) { if(cheese.StartsWith("name:")) ProductName = cheese.Replace("name: ", "").Trim(); else if(cheese.StartsWith("version:")) ProductVersion = cheese.Replace("version: ", "").Trim(); else if(cheese.StartsWith("revision:")) ProductRevision = cheese.Replace("revision: ", "").Trim(); else if(cheese.StartsWith("changelog:")) ChangelogPath = cheese.Replace("changelog: ", "").Trim(); } } // notes = notes.Trim(); /* Get first entry in changelog.txt */ TextAsset changelogText = LoadAssetAtPath<TextAsset>( ChangelogPath ); if(changelogText) { string[] split = changelogText.text.Split( new string[] {"--"}, System.StringSplitOptions.RemoveEmptyEntries ); StringBuilder sb = new StringBuilder(); string[] newLineSplit = split[0].Trim().Split('\n'); for(int i = 2; i < newLineSplit.Length; i++) sb.AppendLine(newLineSplit[i]); changelog = sb.ToString(); } } private static bool GetField(string path, string field, out string value) { TextAsset entry = LoadAssetAtPath<TextAsset>(path); value = ""; if(!entry) return false; foreach(string str in entry.text.Split('\n')) { if(str.Contains(field)) { value = str.Replace(field, "").Trim(); return true; } } return false; } #endregion }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Client.Cache { using System.Collections.Generic; using System.Threading.Tasks; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Client.Cache; /// <summary> /// Cache client async wrapper. /// </summary> public class CacheClientAsyncWrapper<TK, TV> : ICacheClient<TK, TV> { /** */ private readonly ICacheClient<TK, TV> _cache; /// <summary> /// Initializes a new instance of the <see cref="CacheClientAsyncWrapper{TK, TV}"/> class. /// </summary> /// <param name="cache">The cache.</param> public CacheClientAsyncWrapper(ICacheClient<TK, TV> cache) { _cache = cache; } /** <inheritDoc /> */ public string Name { get { return _cache.Name; } } /** <inheritDoc /> */ public void Put(TK key, TV val) { _cache.PutAsync(key, val).WaitResult(); } /** <inheritDoc /> */ public Task PutAsync(TK key, TV val) { return _cache.PutAsync(key, val); } /** <inheritDoc /> */ public TV Get(TK key) { return _cache.GetAsync(key).GetResult(); } /** <inheritDoc /> */ public Task<TV> GetAsync(TK key) { return _cache.GetAsync(key); } /** <inheritDoc /> */ public bool TryGet(TK key, out TV value) { var res = _cache.TryGetAsync(key).GetResult(); value = res.Value; return res.Success; } /** <inheritDoc /> */ public Task<CacheResult<TV>> TryGetAsync(TK key) { return _cache.TryGetAsync(key); } /** <inheritDoc /> */ public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys) { return _cache.GetAllAsync(keys).GetResult(); } /** <inheritDoc /> */ public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys) { return _cache.GetAllAsync(keys); } /** <inheritDoc /> */ public TV this[TK key] { get { return _cache[key]; } set { _cache[key] = value; } } /** <inheritDoc /> */ public bool ContainsKey(TK key) { return _cache.ContainsKeyAsync(key).GetResult(); } /** <inheritDoc /> */ public Task<bool> ContainsKeyAsync(TK key) { return _cache.ContainsKeyAsync(key); } /** <inheritDoc /> */ public bool ContainsKeys(IEnumerable<TK> keys) { return _cache.ContainsKeysAsync(keys).GetResult(); } /** <inheritDoc /> */ public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys) { return _cache.ContainsKeysAsync(keys); } /** <inheritDoc /> */ public IQueryCursor<ICacheEntry<TK, TV>> Query(ScanQuery<TK, TV> scanQuery) { return _cache.Query(scanQuery); } /** <inheritDoc /> */ #pragma warning disable 618 public IQueryCursor<ICacheEntry<TK, TV>> Query(SqlQuery sqlQuery) { return _cache.Query(sqlQuery); } #pragma warning restore 618 /** <inheritDoc /> */ public IFieldsQueryCursor Query(SqlFieldsQuery sqlFieldsQuery) { return _cache.Query(sqlFieldsQuery); } /** <inheritDoc /> */ public CacheResult<TV> GetAndPut(TK key, TV val) { return _cache.GetAndPutAsync(key, val).GetResult(); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val) { return _cache.GetAndPutAsync(key, val); } /** <inheritDoc /> */ public CacheResult<TV> GetAndReplace(TK key, TV val) { return _cache.GetAndReplaceAsync(key, val).GetResult(); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val) { return _cache.GetAndReplaceAsync(key, val); } /** <inheritDoc /> */ public CacheResult<TV> GetAndRemove(TK key) { return _cache.GetAndRemoveAsync(key).GetResult(); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndRemoveAsync(TK key) { return _cache.GetAndRemoveAsync(key); } /** <inheritDoc /> */ public bool PutIfAbsent(TK key, TV val) { return _cache.PutIfAbsentAsync(key, val).GetResult(); } /** <inheritDoc /> */ public Task<bool> PutIfAbsentAsync(TK key, TV val) { return _cache.PutIfAbsentAsync(key, val); } /** <inheritDoc /> */ public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val) { return _cache.GetAndPutIfAbsentAsync(key, val).GetResult(); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val) { return _cache.GetAndPutIfAbsentAsync(key, val); } /** <inheritDoc /> */ public bool Replace(TK key, TV val) { return _cache.ReplaceAsync(key, val).GetResult(); } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV val) { return _cache.ReplaceAsync(key, val); } /** <inheritDoc /> */ public bool Replace(TK key, TV oldVal, TV newVal) { return _cache.ReplaceAsync(key, oldVal, newVal).GetResult(); } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal) { return _cache.ReplaceAsync(key, oldVal, newVal); } /** <inheritDoc /> */ public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals) { _cache.PutAllAsync(vals).WaitResult(); } /** <inheritDoc /> */ public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals) { return _cache.PutAllAsync(vals); } /** <inheritDoc /> */ public void Clear() { _cache.ClearAsync().WaitResult(); } /** <inheritDoc /> */ public Task ClearAsync() { return _cache.ClearAsync(); } /** <inheritDoc /> */ public void Clear(TK key) { _cache.ClearAsync(key).WaitResult(); } /** <inheritDoc /> */ public Task ClearAsync(TK key) { return _cache.ClearAsync(key); } /** <inheritDoc /> */ public void ClearAll(IEnumerable<TK> keys) { _cache.ClearAllAsync(keys).WaitResult(); } /** <inheritDoc /> */ public Task ClearAllAsync(IEnumerable<TK> keys) { return _cache.ClearAllAsync(keys); } /** <inheritDoc /> */ public bool Remove(TK key) { return _cache.RemoveAsync(key).GetResult(); } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key) { return _cache.RemoveAsync(key); } /** <inheritDoc /> */ public bool Remove(TK key, TV val) { return _cache.RemoveAsync(key, val).GetResult(); } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key, TV val) { return _cache.RemoveAsync(key, val); } /** <inheritDoc /> */ public void RemoveAll(IEnumerable<TK> keys) { _cache.RemoveAllAsync(keys).WaitResult(); } /** <inheritDoc /> */ public Task RemoveAllAsync(IEnumerable<TK> keys) { return _cache.RemoveAllAsync(keys); } /** <inheritDoc /> */ public void RemoveAll() { _cache.RemoveAllAsync().WaitResult(); } /** <inheritDoc /> */ public Task RemoveAllAsync() { return _cache.RemoveAllAsync(); } /** <inheritDoc /> */ public long GetSize(params CachePeekMode[] modes) { return _cache.GetSizeAsync(modes).GetResult(); } /** <inheritDoc /> */ public Task<long> GetSizeAsync(params CachePeekMode[] modes) { return _cache.GetSizeAsync(modes); } /** <inheritDoc /> */ public CacheClientConfiguration GetConfiguration() { return _cache.GetConfiguration(); } /** <inheritDoc /> */ public ICacheClient<TK1, TV1> WithKeepBinary<TK1, TV1>() { return _cache.WithKeepBinary<TK1, TV1>(); } /** <inheritDoc /> */ public ICacheClient<TK, TV> WithExpiryPolicy(IExpiryPolicy plc) { return _cache.WithExpiryPolicy(plc); } } }
using System; using System.Reflection; using System.IO; using MonoMac.Foundation; using System.Xml.Linq; using System.Linq; using System.Xml.XPath; using System.Xml; using System.Text; using System.Collections.Generic; class CtorUpdater { static Dictionary<string,Dictionary<string,List<string>>> eventArgsUsage = new Dictionary<string,Dictionary<string,List<string>>>(); static int Record (Type t, string evtsig, string last) { string evt = evtsig.Substring (evtsig.IndexOf ('<')+1); evt = evt.Substring (0, evt.IndexOf ('>')); if (last.EndsWith (";")) last = last.Substring (0, last.Length-1); //Console.WriteLine ("Recording: {0} {1} {2}", t, evt, last); if (!eventArgsUsage.ContainsKey (evt)){ eventArgsUsage [evt] = new Dictionary<string,List<string>>(); } var v = eventArgsUsage [evt]; if (!v.ContainsKey (t.FullName)){ v [t.FullName] = new List<string> (); } v [t.FullName].Add (last); return 1; } public static void Save (XDocument xmldoc, Type t) { string xmldocpath = String.Format ("{0}/{1}/{2}.xml", monotouch_dir, t.Namespace, t.Name); var s = new XmlWriterSettings (); s.Indent = true; s.Encoding = new UTF8Encoding (false); s.OmitXmlDeclaration = true; using (var stream = File.Create (xmldocpath)){ using (var xmlw = XmlWriter.Create (stream, s)){ xmldoc.Save (xmlw); } stream.Write (new byte [] { 10 }, 0, 1); } } public static void ProcessEventArgs (Type t) { var xmldoc = LoadDoc (t); var summary = xmldoc.XPathSelectElement ("Type/Docs/summary"); var sb = new StringBuilder (); int count = 0; if (eventArgsUsage.ContainsKey (t.FullName)){ foreach (var e in eventArgsUsage [t.FullName]){ int n = e.Value.Count; int i = 0; foreach (var s in e.Value){ i++; if (sb.Length != 0){ if (i == n) sb.Append (" and "); else sb.Append (", "); } sb.Append (String.Format ("<see cref=\"E:{0}.{1}\"/>", t.FullName, s)); count++; } } } // else Console.WriteLine ("NO users for {0}", t); summary.ReplaceAll (XElement.Parse ("<Root>Provides data for the " + sb.ToString () + (count > 1 ? " events." : " event.") + "</Root>").DescendantNodes ()); var remarks = xmldoc.XPathSelectElement ("Type/Docs/remarks"); if (remarks.Value == "To be added.") remarks.Value = ""; var ctorSummary = xmldoc.XPathSelectElement ("Type/Members/Member[@MemberName='.ctor']/Docs/summary"); if (ctorSummary != null) ctorSummary.Value = "Initializes a new instance of the " + t.Name + " class."; // else Console.WriteLine ("NO ctor for {0}", t.Name); var ctorRemarks = xmldoc.XPathSelectElement ("Type/Members/Member[@MemberName='.ctor']/Docs/remarks"); if (ctorRemarks != null){ if (ctorRemarks.Value == "To be added.") ctorRemarks.Value = ""; } Save (xmldoc, t); } public static void ProcessNSO (Type t) { var xmldoc = LoadDoc (t); var flagctor = from el in xmldoc.XPathSelectElements ("Type/Members/Member") let y = el.XPathSelectElements ("MemberSignature").FirstOrDefault () where y != null where y.Attribute ("Value").Value.IndexOf ("MonoMac.Foundation.NSObjectFlag") != -1 select el; var coderctor = from el in xmldoc.XPathSelectElements ("Type/Members/Member") let y = el.XPathSelectElements ("MemberSignature").FirstOrDefault () where y != null where y.Attribute ("Value").Value.IndexOf ("NSCoder") != -1 select el; var intptrctor = from el in xmldoc.XPathSelectElements ("Type/Members/Member") let y = el.XPathSelectElements ("MemberSignature").FirstOrDefault () where y != null where y.Attribute ("Value").Value.IndexOf ("IntPtr handle") != -1 select el; var classhandles = from el in xmldoc.XPathSelectElements ("Type/Members/Member[@MemberName='ClassHandle']") let y = el.XPathSelectElements ("MemberSignature").FirstOrDefault () where y != null let value = y.Attribute ("Value").Value where value == "public virtual IntPtr ClassHandle { get; }" || value == "public override IntPtr ClassHandle { get; }" select el; var delegates = from el in xmldoc.XPathSelectElements ("Type/Members/Member[@MemberName='Delegate']") select el; var weakdelegates = from el in xmldoc.XPathSelectElements ("Type/Members/Member[@MemberName='WeakDelegate']") select el; foreach (var x in classhandles){ var e = x.XPathSelectElement ("Docs/summary"); e.Value = "The handle for this class."; e = x.XPathSelectElement ("Docs/value"); e.Value = "The pointer to the Objective-C class."; e = x.XPathSelectElement ("Docs/remarks"); e.Value = "Each MonoMac class mirrors an unmanaged Objective-C class. This value contains the pointer to the Objective-C class, it is similar to calling objc_getClass with the object name."; } foreach (var x in flagctor){ var e = x.XPathSelectElement ("Docs/param"); e.Value = "Unused sentinel value, pass NSObjectFlag.Empty."; e = x.XPathSelectElement ("Docs/summary"); e.Value = "Constructor to call on derived classes when the derived class has an [Export] constructor."; e = x.XPathSelectElement ("Docs/remarks"); e.RemoveAll (); e.Add (XElement.Parse ("<para>This constructor should be called by derived classes when they are initialized using an [Export] attribute. " + "The argument value is ignore, typically the chaining would look like this:</para>")); e.Add (XElement.Parse ("<example><code lang=\"C#\">\n" + "public class MyClass : BaseClass {\n"+ " [Export (\"initWithFoo:\")]\n" + " public MyClass (string foo) : base (NSObjectFlag.Empty)\n"+ " {\n" + " ...\n" + " }\n" + "</code></example>")); } foreach (var x in coderctor){ var e = x.XPathSelectElement ("Docs/param"); if (e != null) e.Value = "The unarchiver object."; e = x.XPathSelectElement ("Docs/summary"); e.Value = "A constructor that initializes the object from the data stored in the unarchiver object."; e = x.XPathSelectElement ("Docs/remarks"); e.RemoveAll (); e.Value = "This constructor is provided to allow the class to be initialized from an unarchiver (for example, during NIB deserialization)."; } foreach (var x in intptrctor){ var e = x.XPathSelectElement ("Docs/param"); e.Value = "Pointer (handle) to the unmanaged object."; e = x.XPathSelectElement ("Docs/summary"); e.Value = "A constructor used when creating managed representations of unmanaged objects; Called by the runtime."; e = x.XPathSelectElement ("Docs/remarks"); e.RemoveAll (); e.Add (XElement.Parse ("<para>This constructor is invoked by the runtime infrastructure (<see cref=\"M:MonoMac.ObjCRuntime.GetNSObject (System.IntPtr)\"/>) to create a new managed representation for a pointer to an unmanaged Objective-C object. You should not invoke this method directly, instead you should call the GetNSObject method as it will prevent two instances of a managed object to point to the same native object.</para>")); } foreach (var x in delegates){ var dtype = x.XPathSelectElement ("ReturnValue/ReturnType").Value; var e = x.XPathSelectElement ("Docs/summary"); e.Value = String.Format ("An instance of the {0} model class which acts as the class delegate.", dtype); e = x.XPathSelectElement ("Docs/value"); e.Value = String.Format ("The instance of the {0} model class", dtype); e = x.XPathSelectElement ("Docs/remarks"); e.RemoveAll (); e.Add (XElement.Parse ("<para>The delegate instance assigned to this object will be used to handle events or provide data on demand to this class.</para>")); e.Add (XElement.Parse ("<para>When setting the Delegate or WeakDelegate values events will be delivered to the specified instance instead of being delivered to the C#-style events</para>")); e.Add (XElement.Parse ("<para>This is the strongly typed version of the object, use the WeakDelegate property instead if you want to merely assign a class derived from NSObject that has been decorated with [Export] attributes.</para>")); } foreach (var x in weakdelegates){ var e = x.XPathSelectElement ("Docs/summary"); e.Value = "An object that can respond to the delegate protocol for this type"; e = x.XPathSelectElement ("Docs/value"); e.Value = "The instance that will respond to events and data requests."; e = x.XPathSelectElement ("Docs/remarks"); e.RemoveAll (); e.Add (XElement.Parse ("<para>The delegate instance assigned to this object will be used to handle events or provide data on demand to this class.</para>")); e.Add (XElement.Parse ("<para>When setting the Delegate or WeakDelegate values events will be delivered to the specified instance instead of being delivered to the C#-style events</para>")); e.Add (XElement.Parse ("<para> Methods must be decorated with the [Export (\"selectorName\")] attribute to respond to each method from the protocol. Alternatively use the Delegate method which is strongly typed and does not require the [Export] attributes on methods.</para>")); } Save (xmldoc, t); } static string monotouch_dir; static public XDocument LoadDoc (Type t) { string xmldocpath = String.Format ("{0}/{1}/{2}.xml", monotouch_dir, t.Namespace, t.Name); return XDocument.Load (xmldocpath); } public static void ScanEvents (Type t) { var xmldoc = LoadDoc (t); var events = from el in xmldoc.XPathSelectElements ("Type/Members/Member") let p = el.XPathSelectElements ("MemberType").FirstOrDefault () where p != null && p.Value == "Event" || p.Value == "Field" let y = el.XPathSelectElements ("MemberSignature").FirstOrDefault ().Attribute ("Value") where y.Value.IndexOf ("EventArgs>") != -1 && y.Value.IndexOf ("<EventArgs>") == -1 select Record (t, y.Value, y.Value.Substring (y.Value.LastIndexOf ('>')+1).Trim ()); // Run query events.ToList (); } public static void DocumentHandle (Type t) { var xmldoc = LoadDoc (t); var h = xmldoc.XPathSelectElement ("Type/Members/Member[@MemberName='Handle']"); if (h == null) return; var e = h.XPathSelectElement ("Docs/summary"); e.Value = "Handle (pointer) to the unmanaged object representation."; e = h.XPathSelectElement ("Docs/value"); e.Value = "A pointer"; e = h.XPathSelectElement ("Docs/remarks"); e.Value = "This IntPtr is a handle to the underlying unmanaged representation for this object."; Save (xmldoc, t); } public static void DocumentDisposable (Type t) { var xmldoc = LoadDoc (t); var dispose = from el in xmldoc.XPathSelectElements ("Type/Members/Member[@MemberName='Dispose' or @MemberName='System.IDisposable.Dispose']") let c = el.XPathSelectElements ("MemberSignature").FirstOrDefault ().Attribute ("Value") where c.Value.IndexOf ("Dispose ()") != -1 select el; var disposevirt = from el in xmldoc.XPathSelectElements ("Type/Members/Member[@MemberName='Dispose']") let c = el.XPathSelectElements ("MemberSignature").FirstOrDefault ().Attribute ("Value") where c.Value.IndexOf ("Dispose (bool") != -1 select el; var finalize = from el in xmldoc.XPathSelectElements ("Type/Members/Member[@MemberName='Finalize']") select el; foreach (var f in finalize){ var e = f.XPathSelectElement ("Docs/summary"); e.Value = "Finalizer for the " + t.Name + " object"; e = f.XPathSelectElement ("Docs/remarks"); e.Value = ""; } foreach (var d in dispose){ var e = d.XPathSelectElement ("Docs/summary"); e.Value = "Releases the resources used by the " + t.Name + " object."; e = d.XPathSelectElement ("Docs/remarks"); e.RemoveAll (); e.Add (XElement.Parse ("<para>The Dispose method releases the resources used by the " + t.Name + " class.</para>")); e.Add (XElement.Parse ("<para>Calling the Dispose method when you are finished using the " +t.Name + " ensures that all external resources used by this managed object are released as soon as possible. Once you have invoked the Dispose method, the object is no longer useful and you should no longer make any calls to it. For more information on releasing resources see ``Cleaning up Unmananaged Resources'' at http://msdn.microsoft.com/en-us/library/498928w2.aspx</para>")); } foreach (var d in disposevirt){ var e = d.XPathSelectElement ("Docs/summary"); e.Value = "Releases the resources used by the " + t.Name + " object."; e = d.XPathSelectElement ("Docs/param[@name='disposing']"); //e = d.XPathSelectElement ("Docs/param"); if (e != null){ e.RemoveAll (); // Add it back after removeall e.Add (new XAttribute ("name", "disposing")); e.Add (XElement.Parse ("<para>If set to <see langword=\"true\"/>, the method is invoked directly and will dispose manage and unmanaged resources; If set to <see langword=\"false\"/> the method is being called by the garbage collector finalizer and should only release unmanaged resources.</para>")); } e = d.XPathSelectElement ("Docs/remarks"); e.RemoveAll (); e.Add (XElement.Parse ("<para>This Dispose method releases the resources used by the " + t.Name + " class.</para>")); e.Add (XElement.Parse ("<para>This method is called by both the Dispose() method and the object finalizer (Finalize). When invoked by the Dispose method, the parameter disposting <paramref name=\"disposing\"/> is set to <see langword=\"true\"/> and any managed object references that this object holds are also disposed or released; when invoked by the object finalizer, on the finalizer thread the value is set to <see langword=\"false\"/>. </para>")); e.Add (XElement.Parse ("<para>Calling the Dispose method when you are finished using the " +t.Name + " ensures that all external resources used by this managed object are released as soon as possible. Once you have invoked the Dispose method, the object is no longer useful and you should no longer make any calls to it.</para>")); e.Add (XElement.Parse ("<para> For more information on how to override this method and on the Dispose/IDisposable pattern, read the ``Implementing a Dispose Method'' document at http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx</para>")); } Save (xmldoc, t); } public static int Main (string [] args) { Assembly monotouch = typeof (MonoMac.Foundation.NSObject).Assembly; bool update_events = false; var dir = args [0]; if (File.Exists (Path.Combine (dir, "en"))){ Console.WriteLine ("The directory does not seem to be the root for documentation (missing en directory)"); return 1; } monotouch_dir = Path.Combine (dir, "en"); Type nso = monotouch.GetType ("MonoMac.Foundation.NSObject"); foreach (Type t in monotouch.GetTypes ()){ if (t.IsNotPublic || t.IsNested) continue; if (typeof (IDisposable).IsAssignableFrom (t)){ DocumentDisposable (t); } DocumentHandle (t); if (typeof (MonoMac.ObjCRuntime.INativeObject).IsAssignableFrom (t)){ } if (update_events) ScanEvents (t); if (t == nso || t.IsSubclassOf (nso)) ProcessNSO (t); } // Now go and populate EventArgs if (update_events){ foreach (Type t in monotouch.GetTypes ()){ if (t.IsNotPublic || t.IsNested) continue; if (t.IsSubclassOf (typeof (EventArgs))){ ProcessEventArgs (t); } } } return 0; } }
// // This code was created by Jeff Molofee '99 // // If you've found this code useful, please let me know. // // Visit me at www.demonews.com/hosted/nehe // //===================================================================== // Converted to C# and MonoMac by Kenneth J. Pouncey // http://www.cocoa-mono.org // // Copyright (c) 2011 Kenneth J. Pouncey // // // 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.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.CoreVideo; using MonoMac.OpenGL; namespace NeHeLesson7 { public partial class MyOpenGLView : MonoMac.AppKit.NSView { NSOpenGLContext openGLContext; NSOpenGLPixelFormat pixelFormat; MainWindowController controller; CVDisplayLink displayLink; NSObject notificationProxy; float[] LightAmbient = new float[] { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values ( NEW ) float[] LightDiffuse = new float[] { 1.0f, 1.0f, 1.0f, 1.0f }; // Diffuse Light Values ( NEW ) float[] LightPosition = { 0.0f, 0.0f, 2.0f, 1.0f }; // Light Position ( NEW ) [Export("initWithFrame:")] public MyOpenGLView (RectangleF frame) : this(frame, null) { } public MyOpenGLView (RectangleF frame, NSOpenGLContext context) : base(frame) { var attribs = new object[] { NSOpenGLPixelFormatAttribute.Accelerated, NSOpenGLPixelFormatAttribute.NoRecovery, NSOpenGLPixelFormatAttribute.DoubleBuffer, NSOpenGLPixelFormatAttribute.ColorSize, 24, NSOpenGLPixelFormatAttribute.DepthSize, 16 }; pixelFormat = new NSOpenGLPixelFormat (attribs); if (pixelFormat == null) Console.WriteLine ("No OpenGL pixel format"); // NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead openGLContext = new NSOpenGLContext (pixelFormat, context); openGLContext.MakeCurrentContext (); // Synchronize buffer swaps with vertical refresh rate openGLContext.SwapInterval = true; // Initialize our newly created view. InitGL (); SetupDisplayLink (); // Look for changes in view size // Note, -reshape will not be called automatically on size changes because NSView does not export it to override notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.NSViewGlobalFrameDidChangeNotification, HandleReshape); } public override void DrawRect (RectangleF dirtyRect) { // Ignore if the display link is still running if (!displayLink.IsRunning && controller != null) DrawView (); } public override bool AcceptsFirstResponder () { // We want this view to be able to receive key events return true; } public override void LockFocus () { base.LockFocus (); if (openGLContext.View != this) openGLContext.View = this; } public override void KeyDown (NSEvent theEvent) { controller.KeyDown (theEvent); } public override void MouseDown (NSEvent theEvent) { controller.MouseDown (theEvent); } // All Setup For OpenGL Goes Here public bool InitGL () { // Enable Texture Mapping ( NEW ) GL.Enable (EnableCap.Texture2D); // Enables Smooth Shading GL.ShadeModel (ShadingModel.Smooth); // Set background color to black GL.ClearColor (Color.Black); // Setup Depth Testing // Depth Buffer setup GL.ClearDepth (1.0); // Enables Depth testing GL.Enable (EnableCap.DepthTest); // The type of depth testing to do GL.DepthFunc (DepthFunction.Lequal); // Really Nice Perspective Calculations GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); // And let there be light // Setup the Ambient Light GL.Light (LightName.Light1, LightParameter.Ambient, LightAmbient); // Setup the Diffuse Light GL.Light (LightName.Light1, LightParameter.Ambient, LightDiffuse); // Setup the light position GL.Light (LightName.Light1, LightParameter.Position, LightPosition); // Enable Light 1 GL.Enable (EnableCap.Light1); return true; } private void DrawView () { // This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop) // Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Make sure we draw to the right context openGLContext.MakeCurrentContext (); // Delegate to the scene object for rendering controller.Scene.DrawGLScene (); openGLContext.FlushBuffer (); openGLContext.CGLContext.Unlock (); } private void SetupDisplayLink () { // Create a display link capable of being used with all active displays displayLink = new CVDisplayLink (); // Set the renderer output callback function displayLink.SetOutputCallback (MyDisplayLinkOutputCallback); // Set the display link for the current renderer CGLContext cglContext = openGLContext.CGLContext; CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat; displayLink.SetCurrentDisplay (cglContext, cglPixelFormat); } public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut) { CVReturn result = GetFrameForTime (inOutputTime); return result; } private CVReturn GetFrameForTime (CVTimeStamp outputTime) { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { // Update the animation DrawView (); } return CVReturn.Success; } public NSOpenGLContext OpenGLContext { get { return openGLContext; } } public NSOpenGLPixelFormat PixelFormat { get { return pixelFormat; } } public MainWindowController MainController { set { controller = value; } } public void UpdateView () { // This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Delegate to the scene object to update for a change in the view size controller.Scene.ResizeGLScene (Bounds); openGLContext.Update (); openGLContext.CGLContext.Unlock (); } private void HandleReshape (NSNotification note) { UpdateView (); } public void StartAnimation () { if (displayLink != null && !displayLink.IsRunning) displayLink.Start (); } public void StopAnimation () { if (displayLink != null && displayLink.IsRunning) displayLink.Stop (); } // Clean up the notifications public void DeAllocate () { displayLink.Stop (); displayLink.SetOutputCallback (null); NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy); } [Export("toggleFullScreen:")] public void toggleFullScreen (NSObject sender) { controller.toggleFullScreen (sender); } } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. ======================= This version of the META tools is a fork of an original version produced by Vanderbilt University's Institute for Software Integrated Systems (ISIS). Their license statement: Copyright (C) 2011-2014 Vanderbilt University Developed with the sponsorship of the Defense Advanced Research Projects Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights as defined in DFARS 252.227-7013. Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; using System.Text; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; using System.Windows.Forms; using System.Xml.Serialization; using System.Xml; using System.Linq; using System.Diagnostics; using Newtonsoft.Json; using CyPhyGUIs; using META; namespace CyPhy2CAD_CSharp { /// <summary> /// This class implements the necessary COM interfaces for a GME interpreter component. /// </summary> [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public partial class CyPhy2CAD_CSharpInterpreter : IMgaComponentEx, IGMEVersionInfo, ICyPhyInterpreter { /// <summary> /// Contains information about the GUI event that initiated the invocation. /// </summary> public enum ComponentStartMode { GME_MAIN_START = 0, // Not used by GME GME_BROWSER_START = 1, // Right click in the GME Tree Browser window GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window GME_EMBEDDED_START = 3, // Not used by GME GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window GME_ICON_START = 32, // Not used by GME GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME } const string OptionNameConsole = "console_messages"; const string OptionNameOutputDir = "output_dir"; const string OptionNameAutomation = "automation"; const string OptionNameDoConfig = "do_config"; const string OptionNameRunCmd = "runCommand"; const string OptionNameCadDir = "cadFile_dir"; const string OptionNameIFab = "prepIFab"; const string OptionNameProjectDir = "original_project_file"; //private CyPhy2CAD_UILib.CADOptions cadoptionHolder; private bool Automation; public CyPhy2CAD_CSharpInterpreter() { this.componentParameters = new SortedDictionary<string, object>(); this.componentParameters[OptionNameConsole] = "on"; this.componentParameters[OptionNameOutputDir] = ".\\"; this.componentParameters[OptionNameAutomation] = "false"; this.componentParameters[OptionNameDoConfig] = "true"; this.componentParameters[OptionNameRunCmd] = "runCADJob.bat"; this.componentParameters[OptionNameCadDir] = ".\\"; this.componentParameters[OptionNameIFab] = "false"; this.componentParameters[OptionNameProjectDir] = ""; var resultzip = CyPhy2CAD_CSharp.Properties.Resources.ResultZip; this.componentParameters["results_zip_py"] = resultzip.ToString(); //cadoptionHolder = new CyPhy2CAD_UILib.CADOptions(); Automation = false; } /// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a tansaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { // TODO: Add your initialization code here... Contract.Requires(project != null); GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); } /// <summary> /// The main entry point of the interpreter. A transaction is already open, /// GMEConsole is available. A general try-catch block catches all the exceptions /// coming from this function, you don't need to add it. For more information, see InvokeEx. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> /// <param name="currentobj">The model open in the active tab in GME. Its value is null if no model is open (no GME modeling windows open). </param> /// <param name="selectedobjs"> /// A collection for the selected model elements. It is never null. /// If the interpreter is invoked by the context menu of the GME Tree Browser, then the selected items in the tree browser. Folders /// are never passed (they are not FCOs). /// If the interpreter is invoked by clicking on the toolbar icon or the context menu of the modeling window, then the selected items /// in the active GME modeling window. If nothing is selected, the collection is empty (contains zero elements). /// </param> /// <param name="startMode">Contains information about the GUI event that initiated the invocation.</param> /// <returns>true if successful</returns> [ComVisible(false)] public bool Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // TODO: Add your interpreter code //GMEConsole.Clear(); GMEConsole.Out.WriteLine("Running CyPhy2CAD interpreter..."); // TODO: show how to initialize DSML-generated classes // Get RootFolder //IMgaFolder rootFolder = project.RootFolder; //GMEConsole.Out.WriteLine(rootFolder.Name); // Check Model // Grab all components // Create Intermediate Data Representations // Walk representation + find islands // Convert to DAG try { // META-1971: ADM + ACM file export for blast + ballistics // ACM { CallComponentExporter(project, currentobj); } result.Success = true; ProcessCAD(currentobj); Logger.Instance.DumpLog(GMEConsole, LogDir); GMEConsole.Out.WriteLine("Finished CyPhy2CAD with " + (result.Success ? "success" : "failure")); return result.Success; } catch (Exception ex) { Logger.Instance.AddLogMessage(ex.Message, Severity.Error); Logger.Instance.DumpLog(GMEConsole, LogDir); GMEConsole.Out.WriteLine("Finished CyPhy2CAD with failure."); return false; } } private string LogDir { get { string logDir = Path.Combine(this.settings.OutputDirectory, "log"); if (!Directory.Exists(logDir)) Directory.CreateDirectory(logDir); return logDir; } } #region IMgaComponentEx Members MgaGateway MgaGateway { get; set; } GMEConsole GMEConsole { get; set; } public void InvokeEx( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } if (currentobj == null) { GMEConsole.Error.WriteLine("Please select a CADTestBench, Ballistic Testbench, FEA Testbench, Blast Testbench or CadAssembly."); return; } string currentWorkDir = System.IO.Directory.GetCurrentDirectory(); try { var parameters = new InterpreterMainParameters(); this.mainParameters = parameters; parameters.ProjectDirectory = Path.GetDirectoryName(currentobj.Project.ProjectConnStr.Substring("MGA=".Length)); FetchSettings(); // Show UI using (MainForm mf = new MainForm(settings)) { mf.ShowDialog(); DialogResult ok = mf.DialogResult; if (ok == DialogResult.OK) { settings = mf.ConfigOptions; parameters.OutputDirectory = settings.OutputDirectory; parameters.config = settings; } else { GMEConsole.Warning.WriteLine("Process was cancelled."); return; } } SaveSettings(); MgaGateway.PerformInTransaction(delegate { Elaborate(project, currentobj, selectedobjs, param); Main(project, currentobj, selectedobjs, Convert(param)); }, abort: true); } finally { MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } } private ComponentStartMode Convert(int param) { switch (param) { case (int)ComponentStartMode.GME_BGCONTEXT_START: return ComponentStartMode.GME_BGCONTEXT_START; case (int)ComponentStartMode.GME_BROWSER_START: return ComponentStartMode.GME_BROWSER_START; case (int)ComponentStartMode.GME_CONTEXT_START: return ComponentStartMode.GME_CONTEXT_START; case (int)ComponentStartMode.GME_EMBEDDED_START: return ComponentStartMode.GME_EMBEDDED_START; case (int)ComponentStartMode.GME_ICON_START: return ComponentStartMode.GME_ICON_START; case (int)ComponentStartMode.GME_MAIN_START: return ComponentStartMode.GME_MAIN_START; case (int)ComponentStartMode.GME_MENU_START: return ComponentStartMode.GME_MENU_START; case (int)ComponentStartMode.GME_SILENT_MODE: return ComponentStartMode.GME_SILENT_MODE; } return ComponentStartMode.GME_SILENT_MODE; } private void SaveSettings() { string projectDirectory = ""; if (this.mainParameters != null) projectDirectory = this.mainParameters.ProjectDirectory; var settingsFilename = Path.Combine(projectDirectory, CyPhy2CADSettings.ConfigFilename); META.ComComponent.SerializeConfiguration(projectDirectory, settings, this.ComponentProgID); } private void SaveSettings(string projectDirectory) { META.ComComponent.SerializeConfiguration(projectDirectory, settings, this.ComponentProgID); } private void FetchSettings() { string projectDirectory = ""; if (mainParameters != null) projectDirectory = mainParameters.ProjectDirectory; var config = META.ComComponent.DeserializeConfiguration(projectDirectory, typeof(CyPhy2CADSettings), this.ComponentProgID) as CyPhy2CADSettings; settings = config; if (settings == null) { settings = new CyPhy2CADSettings(); } } private bool Elaborate( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { try { bool Expanded = this.componentParameters[OptionNameIFab] as String == "true"; if (!Expanded) { try { var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter(); elaborator.Logger = new GMELogger(project); elaborator.Logger.AddWriter(Logger.Instance); var result = elaborator.RunInTransaction(project, currentobj, selectedobjs, param); if (result == false) { throw new ApplicationException("see elaborator log"); } if (this.result.Traceability == null) { this.result.Traceability = new META.MgaTraceability(); } if (elaborator.Traceability != null) { elaborator.Traceability.CopyTo(this.result.Traceability); } } catch (Exception e) { Logger.Instance.AddLogMessage("Elaborator exception occurred: " + e.Message, Severity.Error); throw new Exception(e.Message); } } } catch (Exception ex) { Logger.Instance.AddLogMessage(ex.ToString(), Severity.Error); return false; } return true; } private bool CallComponentExporter(MgaProject project, MgaFCO currentobj ) { try { if (currentobj.MetaBase.Name == "BallisticTestBench" || currentobj.MetaBase.Name == "BlastTestBench") { // call component exporter to traverse design and build component index CyPhyComponentExporter.CyPhyComponentExporterInterpreter compExport = new CyPhyComponentExporter.CyPhyComponentExporterInterpreter(); compExport.Initialize(project); compExport.TraverseTestBenchForComponentExport(currentobj, this.mainParameters.OutputDirectory, this.mainParameters.ProjectDirectory); } } catch (Exception ex) { Logger.Instance.AddLogMessage("ACM generation exception from ComponentExporter: " + ex.Message, Severity.Error); return false; } return true; } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion public IInterpreterPreConfiguration PreConfig(IPreConfigParameters parameters) { return null; } public IInterpreterConfiguration DoGUIConfiguration(IInterpreterPreConfiguration preConfig, IInterpreterConfiguration previousConfig) { if (previousConfig != null) { settings = (CyPhy2CADSettings)previousConfig; } // show main form //FetchSettings(); bool prepIFab = false; using (MainForm mf = new MainForm(settings, true, prepIFab)) { mf.ShowDialog(); DialogResult ok = mf.DialogResult; if (ok == DialogResult.OK) { settings = mf.ConfigOptions; return settings; } else return null; } } private bool CopySTL = false; private CyPhy2CADSettings settings = new CyPhy2CADSettings(); private InterpreterResult result = new InterpreterResult(); private InterpreterMainParameters mainParameters; public IInterpreterResult Main(IInterpreterMainParameters parameters) { result.RunCommand = "runCADJob.bat"; result.Labels = "Creo&&CADCreoParametricCreateAssembly.exev1.4&&" + JobManager.Job.DefaultLabels; var ProjectIsNotInTransaction = (parameters.Project.ProjectStatus & 8) == 0; if (ProjectIsNotInTransaction) { parameters.Project.BeginTransactionInNewTerr(); } Dictionary<string, string> workflowParameters = new Dictionary<string, string>(); var workflowRef = parameters .CurrentFCO .ChildObjects .OfType<MgaReference>() .FirstOrDefault(x => x.Meta.Name == "WorkflowRef"); if (workflowRef != null) { string Parameters = workflowRef.Referred .ChildObjects .OfType<MgaAtom>() .FirstOrDefault(x => x.Meta.Name == "Task") .StrAttrByName["Parameters"]; try { workflowParameters = (Dictionary<string, string>)Newtonsoft.Json.JsonConvert.DeserializeObject(Parameters, typeof(Dictionary<string, string>)); if (workflowParameters == null) { workflowParameters = new Dictionary<string, string>(); } } catch (Newtonsoft.Json.JsonReaderException) { } } META.AnalysisTool.ApplyToolSelection(this.ComponentProgID, workflowParameters, this.result, parameters, modifyLabels: false); if (ProjectIsNotInTransaction) { parameters.Project.AbortTransaction(); } this.CopySTL = workflowParameters.ContainsValue("FreedLinkageAssembler"); var resultzip = CyPhy2CAD_CSharp.Properties.Resources.ResultZip; result.ZippyServerSideHook = Encoding.UTF8.GetString(resultzip); result.LogFileDirectory = Path.Combine(parameters.OutputDirectory, "log"); this.mainParameters = (InterpreterMainParameters)parameters; if (this.mainParameters.config == null) { var config = META.ComComponent.DeserializeConfiguration(this.mainParameters.ProjectDirectory, typeof(CyPhy2CADSettings), this.ComponentProgID) as CyPhy2CADSettings; if (config != null) { this.mainParameters.config = config; settings = config; } else { this.mainParameters.config = new CyPhy2CADSettings(); } } if (this.result.Traceability == null) { this.result.Traceability = new META.MgaTraceability(); } // getting traceability from caller, like master interpreter if (this.mainParameters.Traceability != null) { this.mainParameters.Traceability.CopyTo(this.result.Traceability); } //CyPhy2CAD_CSharp.CyPhy2CADSettings configSettings = (CyPhy2CAD_CSharp.CyPhy2CADSettings)parameters.config; //settings = configSettings; settings = (CyPhy2CAD_CSharp.CyPhy2CADSettings)this.mainParameters.config; settings.OutputDirectory = parameters.OutputDirectory; Automation = true; Logger.Instance.AddLogMessage("Main:Aux Directory is: " + settings.AuxiliaryDirectory, Severity.Info); Logger.Instance.AddLogMessage("Output Directory is: " + settings.OutputDirectory, Severity.Info); MgaGateway.voidDelegate action = delegate { if (Elaborate(parameters.Project, parameters.CurrentFCO, parameters.SelectedFCOs, parameters.StartModeParam)) { result.Success = Main(parameters.Project, parameters.CurrentFCO, parameters.SelectedFCOs, Convert(parameters.StartModeParam)); } else { result.Success = false; Logger.Instance.DumpLog(GMEConsole, LogDir); } }; if ((parameters.Project.ProjectStatus & 8) == 0) { MgaGateway.PerformInTransaction( d: action, mode: transactiontype_enum.TRANSACTION_NON_NESTED, abort: true); } else { action.Invoke(); } return result; } public string InterpreterConfigurationProgId { get { return (typeof(CyPhy2CADSettings).GetCustomAttributes(typeof(ProgIdAttribute), false)[0] as ProgIdAttribute).Value; } } } }
using System; using System.Linq; using System.Text; using DemoGame.Server.AI; using DemoGame.Server.Queries; using NetGore; using NetGore.Db; namespace DemoGame.Server { /// <summary> /// Handles commands entered directly into the server through the server's console. /// </summary> class ConsoleCommands { const string _separator = "-------------------"; static readonly string _newLine = Environment.NewLine; readonly ConsoleCommandParser _parser = new ConsoleCommandParser(); readonly Server _server; /// <summary> /// Initializes a new instance of the <see cref="ConsoleCommands"/> class. /// </summary> /// <param name="server">The server.</param> public ConsoleCommands(Server server) { _server = server; } /// <summary> /// Gets the <see cref="IDbController"/> instance. /// </summary> public IDbController DbController { get { return Server.DbController; } } /// <summary> /// Gets the <see cref="Server"/> instance. /// </summary> public Server Server { get { return _server; } } /// <summary> /// Counts the number of characters in an account. /// </summary> /// <param name="accountName">The name of the account.</param> /// <returns>The number of characters in the account.</returns> [ConsoleCommand("CountAccountCharacters")] public string CountAccountCharacters(string accountName) { if (!GameData.AccountName.IsValid(accountName)) return "Invalid account name"; var accountID = DbController.GetQuery<SelectAccountIDFromNameQuery>().Execute(accountName); if (!accountID.HasValue) return string.Format("No account with the name `{0}` exists.", accountName); return CountAccountCharacters((int)accountID.Value); } /// <summary> /// Counts the number of characters in an account. /// </summary> /// <param name="id">The ID of the account.</param> /// <returns>The number of characters in the account.</returns> [ConsoleCommand("CountAccountCharacters")] public string CountAccountCharacters(int id) { var accountID = new AccountID(id); var result = DbController.GetQuery<CountAccountCharactersByIDQuery>().TryExecute(accountID); if (!result.HasValue) { // Invalid account return string.Format("Account ID `{0}` does not exist.", id); } else { // Valid account return string.Format("There are {0} characters in account ID {1}.", result.Value, accountID); } } /// <summary> /// Creates a new account. /// </summary> /// <param name="accountName">The account name.</param> /// <param name="accountPassword">The account password.</param> /// <param name="email">The account email address.</param> /// <returns>The results of the operation.</returns> [ConsoleCommand("CreateAccount")] public string CreateAccount(string accountName, string accountPassword, string email) { GameMessage failReason; var success = Server.UserAccountManager.TryCreateAccount(null, accountName, accountPassword, email, out failReason); if (success) return string.Format("Created account `{0}`.", accountName); else return "Failed to create new account: " + failReason; } /// <summary> /// Creates a user on an account. /// </summary> /// <param name="accountName">The account to add the user to.</param> /// <param name="userName">The name of the user to create.</param> /// <returns>The results of the operation.</returns> [ConsoleCommand("CreateAccountUser")] public string CreateAccountUser(string accountName, string userName) { string errorMsg; if (!Server.UserAccountManager.TryAddCharacter(accountName, userName, out errorMsg)) return string.Format("Failed to create character `{0}` on account `{1}`: {2}", userName, accountName, errorMsg); return "Character successfully added to account."; } /// <summary> /// Tries to execute a command. /// </summary> /// <param name="commandString">The command string to execute.</param> /// <returns>The </returns> public string ExecuteCommand(string commandString) { ThreadAsserts.IsMainThread(); string result; if (!_parser.TryParse(this, commandString, out result)) { if (string.IsNullOrEmpty(result)) { const string errmsg = "Failed to execute command string: {0}"; result = string.Format(errmsg, commandString); } } return result; } /// <summary> /// Finds where a live item resides. /// </summary> /// <param name="itemID">The ID of the item to search for.</param> /// <returns>The location of the live item, or null if not found.</returns> [ConsoleCommand("FindItem")] public string FindItem(string itemID) { ItemID id; if (!Parser.Current.TryParse(itemID, out id)) return string.Format("Invalid ItemID `{0}`.", id); object source; var item = FindItem(id, out source); if (item == null) return "Item not found."; if (source is Map) return string.Format("Item `{0}` is on Map `{1}` at `{2}`.", item, source, item.Position); else if (source is CharacterEquipped) return string.Format("Item `{0}` is equipped by Character `{1}`.", item, ((CharacterEquipped)source).Character); else if (source is CharacterInventory) return string.Format("Item `{0}` is in the inventory of Character `{1}`.", item, ((CharacterInventory)source).Character); else return string.Format("Item `{0}` found at unknown source `{1}`.", item, source); } /// <summary> /// Finds an item in the world. /// </summary> /// <param name="id">The ID of the item to find.</param> /// <param name="source">When this method returns a non-null value, contains the object that was holding the item.</param> /// <returns>The <see cref="ItemEntity"/> for the given <paramref name="id"/>; otherwise null.</returns> public ItemEntity FindItem(ItemID id, out object source) { // Search all maps in the world foreach (var map in Server.World.Maps) { // Check if the item is on the map itself foreach (var item in map.DynamicEntities.OfType<ItemEntity>().Where(item => item.ID == id)) { source = map; return item; } // Check for the item in the inventory of characters foreach (var character in map.DynamicEntities.OfType<Character>()) { // Check the equipment foreach (var item in character.Equipped.Select(x => x.Value).Where(item => item.ID == id)) { source = character.Equipped; return item; } // Check the inventory foreach (var item in character.Inventory.Select(x => x.Value).Where(item => item.ID == id)) { source = character.Inventory; return item; } } } source = null; return null; } /// <summary> /// Gets the ID of an account. /// </summary> /// <param name="accountName">The name of the account.</param> /// <returns>The ID of the account.</returns> [ConsoleCommand("GetAccountID")] public string GetAccountID(string accountName) { if (!GameData.AccountName.IsValid(accountName)) return "Invalid account name."; AccountID accountID; if (!Server.UserAccountManager.TryGetAccountID(accountName, out accountID)) return string.Format("Account {0} does not exist.", accountName); else return string.Format("Account {0} has the ID {1}.", accountName, accountID); } /// <summary> /// Gets the basic spatial information for a <see cref="Character"/>. /// </summary> /// <param name="c">The <see cref="Character"/>.</param> /// <returns>The information for the <paramref name="c"/> as a string.</returns> static string GetCharacterInfoShort(Character c) { var sb = new StringBuilder(); sb.Append(c.ToString()); sb.Append("\t Map: "); if (c.Map != null) sb.Append(c.Map); else sb.Append("[null]"); sb.Append(" @ "); sb.Append(c.Position); return sb.ToString(); } /// <summary> /// Gets the header string for a command. /// </summary> /// <param name="header">The header.</param> /// <param name="args">The arguments.</param> /// <returns>The string to display.</returns> static string GetCommandHeader(string header, params object[] args) { return _separator + _newLine + string.Format(header, args) + _newLine + _separator + _newLine; } /// <summary> /// Displays the console command help. /// </summary> /// <returns>The console command help.</returns> [ConsoleCommand("Help")] public string Help() { var sb = new StringBuilder(); var cmdsSorted = _parser.GetCommands().OrderBy(x => x.Key); sb.AppendLine("Server console commands:"); foreach (var cmd in cmdsSorted) { sb.Append(" * "); sb.Append(cmd.Key); sb.Append("("); var first = cmd.Value.Select(x => x.Method).FirstOrDefault(); if (first != null) sb.Append(StringCommandParser.GetParameterInfo(first)); sb.Append(")"); var count = cmd.Value.Count(); if (count > 1) { sb.Append(" [+"); sb.Append(count - 1); sb.Append(" overload(s)]"); } sb.AppendLine(); } return sb.ToString(); } /// <summary> /// Terminates the server. /// </summary> /// <returns>The results of the operation.</returns> [ConsoleCommand("Quit")] public string Quit() { _server.Shutdown(); return "Server shutting down"; } /// <summary> /// Shows all of the users that are currently online. /// </summary> /// <returns>All of the online users.</returns> [ConsoleCommand("ShowUsers")] public string ShowUsers() { var users = Server.World.GetUsers(); var userInfo = users.Select(GetCharacterInfoShort).Implode(Environment.NewLine); return GetCommandHeader("Total Users: {0}", users.Count()) + userInfo; } /// <summary> /// Toggles the AI. /// </summary> /// <returns>The results of the operation.</returns> [ConsoleCommand("ToggleAI")] public string ToggleAI() { if (!AISettings.AIDisabled) { AISettings.AIDisabled = true; return "AI has been disabled."; } else { AISettings.AIDisabled = false; return "AI has been enabled."; } } /// <summary> /// Parser for the console commands. The actual handling is done in the <see cref="ConsoleCommands"/> class. /// </summary> class ConsoleCommandParser : StringCommandParser<ConsoleCommandAttribute> { /// <summary> /// Initializes a new instance of the <see cref="ConsoleCommandParser"/> class. /// </summary> public ConsoleCommandParser() : base(typeof(ConsoleCommands)) { } } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\LightComponentBase.h:14 namespace UnrealEngine { public partial class ULightComponentBase : USceneComponent { public ULightComponentBase(IntPtr adress) : base(adress) { } public ULightComponentBase(UObject Parent = null, string Name = "LightComponentBase") : base(IntPtr.Zero) { NativePointer = E_NewObject_ULightComponentBase(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_ULightComponentBase_Brightness_DEPRECATED_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULightComponentBase_Brightness_DEPRECATED_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_ULightComponentBase_IndirectLightingIntensity_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULightComponentBase_IndirectLightingIntensity_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_ULightComponentBase_Intensity_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULightComponentBase_Intensity_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_ULightComponentBase_SamplesPerPixel_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULightComponentBase_SamplesPerPixel_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_ULightComponentBase_VolumetricScatteringIntensity_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_ULightComponentBase_VolumetricScatteringIntensity_SET(IntPtr Ptr, float Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_ULightComponentBase(IntPtr Parent, string Name); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_ULightComponentBase_GetLightColor(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULightComponentBase_HasStaticLighting(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULightComponentBase_HasStaticShadowing(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_ULightComponentBase_IsMovable(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULightComponentBase_SetAffectReflection(IntPtr self, bool bNewValue); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULightComponentBase_SetCastRaytracedShadow(IntPtr self, bool bNewValue); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULightComponentBase_SetCastShadows(IntPtr self, bool bNewValue); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULightComponentBase_SetCastVolumetricShadow(IntPtr self, bool bNewValue); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULightComponentBase_SetSamplesPerPixel(IntPtr self, int newValue); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULightComponentBase_UpdateLightGUIDs(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_ULightComponentBase_ValidateLightGUIDs(IntPtr self); #endregion #region Property public float Brightness_DEPRECATED { get => E_PROP_ULightComponentBase_Brightness_DEPRECATED_GET(NativePointer); set => E_PROP_ULightComponentBase_Brightness_DEPRECATED_SET(NativePointer, value); } /// <summary> /// Scales the indirect lighting contribution from this light. /// <para>A value of 0 disables any GI from this light. Default is 1. </para> /// </summary> public float IndirectLightingIntensity { get => E_PROP_ULightComponentBase_IndirectLightingIntensity_GET(NativePointer); set => E_PROP_ULightComponentBase_IndirectLightingIntensity_SET(NativePointer, value); } /// <summary> /// Total energy that the light emits. /// </summary> public float Intensity { get => E_PROP_ULightComponentBase_Intensity_GET(NativePointer); set => E_PROP_ULightComponentBase_Intensity_SET(NativePointer, value); } /// <summary> /// Samples per pixel for ray tracing /// </summary> public int SamplesPerPixel { get => E_PROP_ULightComponentBase_SamplesPerPixel_GET(NativePointer); set => E_PROP_ULightComponentBase_SamplesPerPixel_SET(NativePointer, value); } /// <summary> /// Intensity of the volumetric scattering from this light. This scales Intensity and LightColor. /// </summary> public float VolumetricScatteringIntensity { get => E_PROP_ULightComponentBase_VolumetricScatteringIntensity_GET(NativePointer); set => E_PROP_ULightComponentBase_VolumetricScatteringIntensity_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// Gets the light color as a linear color /// </summary> public FLinearColor GetLightColor() => E_ULightComponentBase_GetLightColor(this); /// <summary> /// Return True if a light's parameters as well as its position is static during gameplay, and can thus use static lighting. /// <para>A light with HasStaticLighting() == true will always have HasStaticShadowing() == true as well. </para> /// </summary> public bool HasStaticLighting() => E_ULightComponentBase_HasStaticLighting(this); /// <summary> /// Whether the light has static direct shadowing. /// <para>The light may still have dynamic brightness and color. </para> /// The light may or may not also have static lighting. /// </summary> public bool HasStaticShadowing() => E_ULightComponentBase_HasStaticShadowing(this); /// <summary> /// Returns true if the light's Mobility is set to Movable /// </summary> public bool IsMovable() => E_ULightComponentBase_IsMovable(this); public void SetAffectReflection(bool bNewValue) => E_ULightComponentBase_SetAffectReflection(this, bNewValue); public void SetCastRaytracedShadow(bool bNewValue) => E_ULightComponentBase_SetCastRaytracedShadow(this, bNewValue); /// <summary> /// Sets whether this light casts shadows /// </summary> public void SetCastShadows(bool bNewValue) => E_ULightComponentBase_SetCastShadows(this, bNewValue); public void SetCastVolumetricShadow(bool bNewValue) => E_ULightComponentBase_SetCastVolumetricShadow(this, bNewValue); public void SetSamplesPerPixel(int newValue) => E_ULightComponentBase_SetSamplesPerPixel(this, newValue); /// <summary> /// Update/reset light GUIDs. /// </summary> public virtual void UpdateLightGUIDs() => E_ULightComponentBase_UpdateLightGUIDs(this); /// <summary> /// Validate light GUIDs and resets as appropriate. /// </summary> public void ValidateLightGUIDs() => E_ULightComponentBase_ValidateLightGUIDs(this); #endregion public static implicit operator IntPtr(ULightComponentBase self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ULightComponentBase(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ULightComponentBase>(PtrDesc); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; using System.Windows; using System.Windows.Controls; using Microsoft.Phone.Controls; //using Windows.Devices.Geolocation; //using Windows.UI.Core; using WPCordovaClassLib; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.Commands; using WPCordovaClassLib.Cordova.JSON; using GoogleAds; namespace Cordova.Extension.Commands { /// /// Google AD Mob wrapper for showing banner and interstitial adverts /// public sealed class AdMob : BaseCommand { #region Const // ad size // only banner and smart banner supported on windows phones, see: // https://developers.google.com/mobile-ads-sdk/docs/admob/wp/banner public const string ADSIZE_BANNER = "BANNER"; public const string ADSIZE_SMART_BANNER = "SMART_BANNER"; //public const string ADSIZE_MEDIUM_RECTANGLE = "MEDIUM_RECTANGLE"; //public const string ADSIZE_FULL_BANNER = "FULL_BANNER"; //public const string ADSIZE_LEADERBOARD = "LEADERBOARD"; //public const string ADSIZE_SKYSCRAPER = "SKYSCRAPPER"; //public const string ADSIZE_CUSTOM = "CUSTOM"; // ad event public const string EVENT_AD_LOADED = "onAdLoaded"; public const string EVENT_AD_FAILLOAD = "onAdFailLoad"; public const string EVENT_AD_PRESENT = "onAdPresent"; public const string EVENT_AD_LEAVEAPP = "onAdLeaveApp"; public const string EVENT_AD_DISMISS = "onAdDismiss"; public const string EVENT_AD_WILLPRESENT = "onAdWillPresent"; public const string EVENT_AD_WILLDISMISS = "onAdWillDismiss"; // ad type public const string ADTYPE_BANNER = "banner"; public const string ADTYPE_INTERSTITIAL = "interstitial"; public const string ADTYPE_NATIVE = "native"; // options public const string OPT_ADID = "adId"; public const string OPT_AUTO_SHOW = "autoShow"; public const string OPT_IS_TESTING = "isTesting"; public const string OPT_LOG_VERBOSE = "logVerbose"; public const string OPT_AD_SIZE = "adSize"; public const string OPT_WIDTH = "width"; public const string OPT_HEIGHT = "height"; public const string OPT_OVERLAP = "overlap"; public const string OPT_ORIENTATION_RENEW = "orientationRenew"; public const string OPT_POSITION = "position"; public const string OPT_X = "x"; public const string OPT_Y = "y"; public const string OPT_BANNER_ID = "bannerId"; public const string OPT_INTERSTITIAL_ID = "interstitialId"; private const string TEST_BANNER_ID = "ca-app-pub-6869992474017983/9375997553"; private const string TEST_INTERSTITIAL_ID = "ca-app-pub-6869992474017983/1355127956"; // banner positions public const int NO_CHANGE = 0; public const int TOP_LEFT = 1; public const int TOP_CENTER = 2; public const int TOP_RIGHT = 3; public const int LEFT = 4; public const int CENTER = 5; public const int RIGHT = 6; public const int BOTTOM_LEFT = 7; public const int BOTTOM_CENTER = 8; public const int BOTTOM_RIGHT = 9; public const int POS_XY = 10; #endregion #region Members private bool isTesting = false; private bool logVerbose = false; private string bannerId = ""; private string interstitialId = ""; private AdFormats adSize = AdFormats.SmartBanner; private int adWidth = 320; private int adHeight = 50; private bool overlap = false; private bool orientationRenew = true; private int adPosition = BOTTOM_CENTER; private int posX = 0; private int posY = 0; private bool autoShowBanner = true; private bool autoShowInterstitial = false; private bool bannerVisible = false; private const string UI_LAYOUT_ROOT = "LayoutRoot"; private const string UI_CORDOVA_VIEW = "CordovaView"; private const int BANNER_HEIGHT_PORTRAIT = 50; private const int BANNER_HEIGHT_LANDSCAPE = 32; private RowDefinition row = null; private AdView bannerAd = null; private InterstitialAd interstitialAd = null; private double initialViewHeight = 0.0; private double initialViewWidth = 0.0; #endregion static AdFormats adSizeFromString(String size) { if (ADSIZE_BANNER.Equals (size)) { return AdFormats.Banner; //Banner (320x50, Phones and Tablets) } else { return AdFormats.SmartBanner; //Smart banner (Auto size, Phones and Tablets) } } #region Public methods public void setOptions(string args) { if(logVerbose) Debug.WriteLine("AdMob.setOptions: " + args); try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { var options = JsonHelper.Deserialize<AdMobOptions>(inputs[0]); __setOptions(options); } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message)); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } public void createBanner(string args) { if (logVerbose) Debug.WriteLine("AdMob.createBanner: " + args); try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { var options = JsonHelper.Deserialize<AdMobOptions>(inputs[0]); if (options != null) { __setOptions(options); string adId = TEST_BANNER_ID; bool autoShow = true; if (!string.IsNullOrEmpty(options.adId)) adId = options.adId; //if (options.ContainsKey(OPT_AUTO_SHOW)) // autoShow = Convert.ToBoolean(options[OPT_AUTO_SHOW]); __createBanner(adId, autoShow); } } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message)); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } public void removeBanner(string args) { if (logVerbose) Debug.WriteLine("AdMob.removeBanner: " + args); // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { __hideBanner(); // Remove event handlers bannerAd.FailedToReceiveAd -= banner_onAdFailLoad; bannerAd.LeavingApplication -= banner_onAdLeaveApp; bannerAd.ReceivedAd -= banner_onAdLoaded; bannerAd.ShowingOverlay -= banner_onAdPresent; bannerAd.DismissingOverlay -= banner_onAdDismiss; bannerAd = null; }); DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } public void prepareInterstitial(string args) { if (logVerbose) Debug.WriteLine("AdMob.prepareInterstitial: " + args); string adId = ""; bool autoShow = false; try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { var options = JsonHelper.Deserialize<AdMobOptions>(inputs[0]); if (options != null) { __setOptions(options); if (!string.IsNullOrEmpty(options.adId)) { adId = options.adId; //if (options.ContainsKey(OPT_AUTO_SHOW)) // autoShow = Convert.ToBoolean(options[OPT_AUTO_SHOW]); __prepareInterstitial(adId, autoShow); } } } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message)); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } public void hideBanner(string args) { if (logVerbose) Debug.WriteLine("AdMob.hideBanner: " + args); __hideBanner(); DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } public void showInterstitial(string args) { if (logVerbose) Debug.WriteLine("AdMob.showInterstitial: " + args); if (interstitialAd != null) { __showInterstitial(); } else { __prepareInterstitial(interstitialId, true); } DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } #endregion #region Private methods private void __setOptions(AdMobOptions options) { if (options == null) return; if (options.isTesting.HasValue) isTesting = options.isTesting.Value; if (options.logVerbose.HasValue) logVerbose = options.logVerbose.Value; if (options.overlap.HasValue) overlap = options.overlap.Value; if (options.orientationRenew.HasValue) orientationRenew = options.orientationRenew.Value; if (options.position.HasValue) adPosition = options.position.Value; if (options.x.HasValue) posX = options.x.Value; if (options.y.HasValue) posY = options.y.Value; if (options.bannerId != null) bannerId = options.bannerId; if (options.interstitialId != null) interstitialId = options.interstitialId; if (options.adSize != null) adSize = adSizeFromString( options.adSize ); if (options.width.HasValue) adWidth = options.width.Value; if (options.height.HasValue) adHeight = options.height.Value; } private void __createBanner(string adId, bool autoShow) { if (bannerAd != null) { if(logVerbose) Debug.WriteLine("banner already created."); return; } if (isTesting) adId = TEST_BANNER_ID; if ((adId!=null) && (adId.Length > 0)) bannerId = adId; else adId = bannerId; autoShowBanner = autoShow; // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { if(bannerAd == null) { bannerAd = new AdView { Format = adSize, AdUnitID = bannerId }; // Add event handlers bannerAd.FailedToReceiveAd += banner_onAdFailLoad; bannerAd.LeavingApplication += banner_onAdLeaveApp; bannerAd.ReceivedAd += banner_onAdLoaded; bannerAd.ShowingOverlay += banner_onAdPresent; bannerAd.DismissingOverlay += banner_onAdDismiss; } bannerVisible = false; AdRequest adRequest = new AdRequest(); adRequest.ForceTesting = isTesting; bannerAd.LoadAd( adRequest ); if(autoShowBanner) { __showBanner(adPosition, posX, posY); } }); } private void showBanner(string args) { if(logVerbose) Debug.WriteLine("AdMob.showBanner: " + args); try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { int position = Convert.ToInt32(inputs[0]); __showBanner(position, 0, 0); } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message)); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } private void showBannerAtXY(string args) { if(logVerbose) Debug.WriteLine("AdMob.showBannerAtXY: " + args); try { string[] inputs = JsonHelper.Deserialize<string[]>(args); if (inputs != null && inputs.Length >= 1) { int x = Convert.ToInt32(inputs[0]); int y = Convert.ToInt32(inputs[1]); __showBanner(POS_XY, x, y); } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message)); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK)); } private void __showBanner(int argPos, int argX, int argY) { if (bannerAd == null) { if(logVerbose) Debug.WriteLine("banner is null, call createBanner() first."); return; } // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame; PhoneApplicationPage page; CordovaView view; Grid grid; if (TryCast(Application.Current.RootVisual, out frame) && TryCast(frame.Content, out page) && TryCast(page.FindName(UI_CORDOVA_VIEW), out view) && TryCast(page.FindName(UI_LAYOUT_ROOT), out grid)) { if(grid.Children.Contains(bannerAd)) grid.Children.Remove(bannerAd); if(overlap) { __showBannerOverlap(grid, adPosition); } else { if(! bannerVisible) { initialViewHeight = view.ActualHeight; initialViewWidth = view.ActualWidth; frame.OrientationChanged += onOrientationChanged; } __showBannerSplit(grid, view, adPosition); setCordovaViewHeight(frame, view); } bannerAd.Visibility = Visibility.Visible; bannerVisible = true; } }); } private void __showBannerOverlap(Grid grid, int position) { switch ((position - 1) % 3) { case 0: bannerAd.HorizontalAlignment = HorizontalAlignment.Left; break; case 1: bannerAd.HorizontalAlignment = HorizontalAlignment.Center; break; case 2: bannerAd.HorizontalAlignment = HorizontalAlignment.Right; break; } switch ((position - 1) / 3) { case 0: bannerAd.VerticalAlignment = VerticalAlignment.Top; break; case 1: bannerAd.VerticalAlignment = VerticalAlignment.Center; break; case 2: bannerAd.VerticalAlignment = VerticalAlignment.Bottom; break; } grid.Children.Add (bannerAd); } private void __showBannerSplit(Grid grid, CordovaView view, int position) { if(row == null) { row = new RowDefinition(); row.Height = GridLength.Auto; } grid.Children.Add(bannerAd); switch((position-1)/3) { case 0: grid.RowDefinitions.Insert(0,row); Grid.SetRow(bannerAd, 0); Grid.SetRow(view, 1); break; case 1: case 2: grid.RowDefinitions.Add(row); Grid.SetRow(bannerAd, 1); break; } } private void __hideBanner() { if (bannerAd == null) { if(logVerbose) Debug.WriteLine("banner is null, call createBanner() first."); return; } // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame; PhoneApplicationPage page; CordovaView view; Grid grid; if (TryCast(Application.Current.RootVisual, out frame) && TryCast(frame.Content, out page) && TryCast(page.FindName(UI_CORDOVA_VIEW), out view) && TryCast(page.FindName(UI_LAYOUT_ROOT), out grid)) { grid.Children.Remove(bannerAd); grid.RowDefinitions.Remove(row); row = null; bannerAd.Visibility = Visibility.Collapsed; bannerVisible = false; if(! overlap) { frame.OrientationChanged -= onOrientationChanged; setCordovaViewHeight(frame, view); } } }); } private void __prepareInterstitial(string adId, bool autoShow) { if (isTesting) adId = TEST_INTERSTITIAL_ID; if ((adId != null) && (adId.Length > 0)) { interstitialId = adId; } else { adId = interstitialId; } autoShowInterstitial = autoShow; // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { interstitialAd = new InterstitialAd( interstitialId ); // Add event listeners interstitialAd.ReceivedAd += interstitial_onAdLoaded; interstitialAd.FailedToReceiveAd += interstitial_onAdFailLoad; interstitialAd.ShowingOverlay += interstitial_onAdPresent; interstitialAd.DismissingOverlay += interstitial_onAdDismiss; AdRequest adRequest = new AdRequest(); adRequest.ForceTesting = isTesting; interstitialAd.LoadAd(adRequest); }); } private void __showInterstitial() { if (interstitialAd == null) { if(logVerbose) Debug.WriteLine("interstitial is null, call prepareInterstitial() first."); return; } Deployment.Current.Dispatcher.BeginInvoke(() => { interstitialAd.ShowAd (); }); } // Events -------- // Device orientation private void onOrientationChanged(object sender, OrientationChangedEventArgs e) { // Asynchronous UI threading call Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame; PhoneApplicationPage page; CordovaView view; Grid grid; if (TryCast(Application.Current.RootVisual, out frame) && TryCast(frame.Content, out page) && TryCast(page.FindName(UI_CORDOVA_VIEW), out view) && TryCast(page.FindName(UI_LAYOUT_ROOT), out grid)) { setCordovaViewHeight(frame, view); } }); } /// Set cordova view height based on banner height and frame orientation private void setCordovaViewHeight(PhoneApplicationFrame frame, CordovaView view) { bool deduct = bannerVisible && (! overlap); if (frame.Orientation == PageOrientation.Portrait || frame.Orientation == PageOrientation.PortraitDown || frame.Orientation == PageOrientation.PortraitUp) { view.Height = initialViewHeight - (deduct ? BANNER_HEIGHT_PORTRAIT : 0); } else { view.Height = initialViewWidth - (deduct ? BANNER_HEIGHT_LANDSCAPE : 0); } fireEvent ("window", "resize", null); } // Banner events private void banner_onAdFailLoad(object sender, AdErrorEventArgs args) { fireAdErrorEvent (EVENT_AD_FAILLOAD, ADTYPE_BANNER, getErrCode(args.ErrorCode), getErrStr(args.ErrorCode)); } private void banner_onAdLoaded(object sender, AdEventArgs args) { fireAdEvent (EVENT_AD_LOADED, ADTYPE_BANNER); if( (! bannerVisible) && autoShowBanner ) { __showBanner(adPosition, posX, posY); } } private void banner_onAdPresent(object sender, AdEventArgs args) { fireAdEvent (EVENT_AD_PRESENT, ADTYPE_BANNER); } private void banner_onAdLeaveApp(object sender, AdEventArgs args) { fireAdEvent (EVENT_AD_LEAVEAPP, ADTYPE_BANNER); } private void banner_onAdDismiss(object sender, AdEventArgs args) { fireAdEvent (EVENT_AD_DISMISS, ADTYPE_BANNER); } // Interstitial events private void interstitial_onAdFailLoad(object sender, AdErrorEventArgs args) { fireAdErrorEvent (EVENT_AD_FAILLOAD, ADTYPE_INTERSTITIAL, getErrCode(args.ErrorCode), getErrStr(args.ErrorCode)); } private void interstitial_onAdLoaded(object sender, AdEventArgs args) { fireAdEvent (EVENT_AD_LOADED, ADTYPE_INTERSTITIAL); if (autoShowInterstitial) { __showInterstitial (); } } private void interstitial_onAdPresent(object sender, AdEventArgs args) { fireAdEvent (EVENT_AD_PRESENT, ADTYPE_INTERSTITIAL); } private void interstitial_onAdDismiss(object sender, AdEventArgs args) { fireAdEvent (EVENT_AD_DISMISS, ADTYPE_INTERSTITIAL); } private int getErrCode(AdErrorCode errorCode) { switch(errorCode) { case AdErrorCode.InternalError: return 0; case AdErrorCode.InvalidRequest: return 1; case AdErrorCode.NetworkError: return 2; case AdErrorCode.NoFill: return 3; case AdErrorCode.Cancelled: return 4; case AdErrorCode.StaleInterstitial: return 5; case AdErrorCode.NoError: return 6; } return -1; } private string getErrStr(AdErrorCode errorCode) { switch(errorCode) { case AdErrorCode.InternalError: return "Internal error"; case AdErrorCode.InvalidRequest: return "Invalid request"; case AdErrorCode.NetworkError: return "Network error"; case AdErrorCode.NoFill: return "No fill"; case AdErrorCode.Cancelled: return "Cancelled"; case AdErrorCode.StaleInterstitial: return "Stale interstitial"; case AdErrorCode.NoError: return "No error"; } return "Unknown"; } private void fireAdEvent(string adEvent, string adType) { string json = "{'adNetwork':'AdMob','adType':'" + adType + "','adEvent':'" + adEvent + "'}"; fireEvent("document", adEvent, json); } private void fireAdErrorEvent(string adEvent, string adType, int errCode, string errMsg) { string json = "{'adNetwork':'AdMob','adType':'" + adType + "','adEvent':'" + adEvent + "','error':" + errCode + ",'reason':'" + errMsg + "'}"; fireEvent("document", adEvent, json); } private void fireEvent(string obj, string eventName, string jsonData) { if(logVerbose) Debug.WriteLine( eventName ); string js = ""; if("window".Equals(obj)) { js = "var evt=document.createEvent('UIEvents');evt.initUIEvent('" + eventName + "',true,false,window,0);window.dispatchEvent(evt);"; } else { js = "javascript:cordova.fireDocumentEvent('" + eventName + "'"; if(jsonData != null) { js += "," + jsonData; } js += ");"; } Deployment.Current.Dispatcher.BeginInvoke(() => { PhoneApplicationFrame frame; PhoneApplicationPage page; CordovaView view; if (TryCast(Application.Current.RootVisual, out frame) && TryCast(frame.Content, out page) && TryCast(page.FindName(UI_CORDOVA_VIEW), out view)) { // Asynchronous threading call view.Browser.Dispatcher.BeginInvoke(() =>{ try { view.Browser.InvokeScript("eval", new string[] { js }); } catch { if(logVerbose) Debug.WriteLine("AdMob.fireEvent: Failed to invoke script: " + js); } }); } }); } #endregion static bool TryCast<T>(object obj, out T result) where T : class { result = obj as T; return result != null; } } }
// // CTFontDescriptor.cs: Implements the managed CTFontDescriptor // // Authors: Mono Team // // Copyright 2010 Novell, Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; using MonoMac.Foundation; namespace MonoMac.CoreText { [Since (3,2)] public enum CTFontOrientation : uint { Default = 0, Horizontal = 1, Vertical = 2, } [Since (3,2)] public enum CTFontFormat : uint { Unrecognized = 0, OpenTypePostScript = 1, OpenTypeTrueType = 2, TrueType = 3, PostScript = 4, Bitmap = 5, } [Since (3,2)] public enum CTFontPriority : uint { System = 10000, Network = 20000, Computer = 30000, User = 40000, Dynamic = 50000, Process = 60000, } [Since (3,2)] public static class CTFontDescriptorAttributeKey { public static readonly NSString Url; public static readonly NSString Name; public static readonly NSString DisplayName; public static readonly NSString FamilyName; public static readonly NSString StyleName; public static readonly NSString Traits; public static readonly NSString Variation; public static readonly NSString Size; public static readonly NSString Matrix; public static readonly NSString CascadeList; public static readonly NSString CharacterSet; public static readonly NSString Languages; public static readonly NSString BaselineAdjust; public static readonly NSString MacintoshEncodings; public static readonly NSString Features; public static readonly NSString FeatureSettings; public static readonly NSString FixedAdvance; public static readonly NSString FontOrientation; public static readonly NSString FontFormat; public static readonly NSString RegistrationScope; public static readonly NSString Priority; public static readonly NSString Enabled; static CTFontDescriptorAttributeKey () { var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0); if (handle == IntPtr.Zero) return; try { Url = Dlfcn.GetStringConstant (handle, "kCTFontURLAttribute"); Name = Dlfcn.GetStringConstant (handle, "kCTFontNameAttribute"); DisplayName = Dlfcn.GetStringConstant (handle, "kCTFontDisplayNameAttribute"); FamilyName = Dlfcn.GetStringConstant (handle, "kCTFontFamilyNameAttribute"); StyleName = Dlfcn.GetStringConstant (handle, "kCTFontStyleNameAttribute"); Traits = Dlfcn.GetStringConstant (handle, "kCTFontTraitsAttribute"); Variation = Dlfcn.GetStringConstant (handle, "kCTFontVariationAttribute"); Size = Dlfcn.GetStringConstant (handle, "kCTFontSizeAttribute"); Matrix = Dlfcn.GetStringConstant (handle, "kCTFontMatrixAttribute"); CascadeList = Dlfcn.GetStringConstant (handle, "kCTFontCascadeListAttribute"); CharacterSet = Dlfcn.GetStringConstant (handle, "kCTFontCharacterSetAttribute"); Languages = Dlfcn.GetStringConstant (handle, "kCTFontLanguagesAttribute"); BaselineAdjust = Dlfcn.GetStringConstant (handle, "kCTFontBaselineAdjustAttribute"); MacintoshEncodings = Dlfcn.GetStringConstant (handle, "kCTFontMacintoshEncodingsAttribute"); Features = Dlfcn.GetStringConstant (handle, "kCTFontFeaturesAttribute"); FeatureSettings = Dlfcn.GetStringConstant (handle, "kCTFontFeatureSettingsAttribute"); FixedAdvance = Dlfcn.GetStringConstant (handle, "kCTFontFixedAdvanceAttribute"); FontOrientation = Dlfcn.GetStringConstant (handle, "kCTFontOrientationAttribute"); FontFormat = Dlfcn.GetStringConstant (handle, "kCTFontFormatAttribute"); RegistrationScope = Dlfcn.GetStringConstant (handle, "kCTFontRegistrationScopeAttribute"); Priority = Dlfcn.GetStringConstant (handle, "kCTFontPriorityAttribute"); Enabled = Dlfcn.GetStringConstant (handle, "kCTFontEnabledAttribute"); } finally { Dlfcn.dlclose (handle); } } } [Since (3,2)] public class CTFontDescriptorAttributes { public CTFontDescriptorAttributes () : this (new NSMutableDictionary ()) { } public CTFontDescriptorAttributes (NSDictionary dictionary) { if (dictionary == null) throw new ArgumentNullException ("dictionary"); Dictionary = dictionary; } public NSDictionary Dictionary {get; private set;} public NSUrl Url { get {return (NSUrl) Dictionary [CTFontDescriptorAttributeKey.Url];} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Url, value);} } public string Name { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.Name);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Name, value);} } public string DisplayName { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.DisplayName);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.DisplayName, value);} } public string FamilyName { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.FamilyName);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FamilyName, value);} } public string StyleName { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.StyleName);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.StyleName, value);} } public CTFontTraits Traits { get { var traits = (NSDictionary) Dictionary [CTFontDescriptorAttributeKey.Traits]; if (traits == null) return null; return new CTFontTraits (traits); } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Traits, value == null ? null : value.Dictionary); } } public CTFontVariation Variation { get { var variation = (NSDictionary) Dictionary [CTFontDescriptorAttributeKey.Variation]; return variation == null ? null : new CTFontVariation (variation); } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Variation, value == null ? null : value.Dictionary); } } public float? Size { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.Size);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Size, value);} } public unsafe CGAffineTransform? Matrix { get { var d = (NSData) Dictionary [CTFontDescriptorAttributeKey.Matrix]; if (d == null) return null; return (CGAffineTransform) Marshal.PtrToStructure (d.Bytes, typeof (CGAffineTransform)); } set { if (!value.HasValue) Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Matrix, (NSObject) null); else { byte[] data = new byte [Marshal.SizeOf (typeof (CGAffineTransform))]; fixed (byte* p = data) { Marshal.StructureToPtr (value.Value, (IntPtr) p, false); } Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Matrix, NSData.FromArray (data)); } } } public IEnumerable<CTFontDescriptor> CascadeList { get { return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.CascadeList, d => new CTFontDescriptor (d, false)); } set {Adapter.SetNativeValue (Dictionary, CTFontDescriptorAttributeKey.CascadeList, value);} } public NSCharacterSet CharacterSet { get {return (NSCharacterSet) Dictionary [CTFontDescriptorAttributeKey.CharacterSet];} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.CharacterSet, value);} } public IEnumerable<string> Languages { get {return Adapter.GetStringArray (Dictionary, CTFontDescriptorAttributeKey.Languages);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Languages, value);} } public float? BaselineAdjust { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.BaselineAdjust);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.BaselineAdjust, value);} } public float? MacintoshEncodings { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.MacintoshEncodings);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.MacintoshEncodings, value);} } public IEnumerable<CTFontFeatures> Features { get { return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.Features, d => new CTFontFeatures ((NSDictionary) Runtime.GetNSObject (d))); } set { List<CTFontFeatures> v; if (value == null || (v = new List<CTFontFeatures> (value)).Count == 0) { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, (NSObject) null); return; } Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, NSArray.FromNSObjects (v.ConvertAll (e => (NSObject) e.Dictionary))); } } public IEnumerable<CTFontFeatureSettings> FeatureSettings { get { return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.Features, d => new CTFontFeatureSettings ((NSDictionary) Runtime.GetNSObject (d))); } set { List<CTFontFeatureSettings> v; if (value == null || (v = new List<CTFontFeatureSettings> (value)).Count == 0) { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, (NSObject) null); return; } Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FeatureSettings, NSArray.FromNSObjects (v.ConvertAll (e => (NSObject) e.Dictionary))); } } public float? FixedAdvance { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.FixedAdvance);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FixedAdvance, value);} } public CTFontOrientation? FontOrientation { get { var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.FontOrientation); return !value.HasValue ? null : (CTFontOrientation?) value.Value; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FontOrientation, value.HasValue ? (uint?) value.Value : null); } } public CTFontFormat? FontFormat { get { var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.FontFormat); return !value.HasValue ? null : (CTFontFormat?) value.Value; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FontFormat, value.HasValue ? (uint?) value.Value : null); } } // TODO: docs mention CTFontManagerScope values, but I don't see any such enumeration. public NSNumber RegistrationScope { get {return (NSNumber) Dictionary [CTFontDescriptorAttributeKey.RegistrationScope];} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.RegistrationScope, value);} } public CTFontPriority? Priority { get { var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.Priority); return !value.HasValue ? null : (CTFontPriority?) value.Value; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Priority, value.HasValue ? (uint?) value.Value : null); } } public bool Enabled { get { var value = (NSNumber) Dictionary [CTFontDescriptorAttributeKey.Enabled]; if (value == null) return false; return value.Int32Value != 0; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Enabled, value ? new NSNumber (1) : null); } } } [Since (3,2)] public class CTFontDescriptor : INativeObject, IDisposable { internal IntPtr handle; internal CTFontDescriptor (IntPtr handle) : this (handle, false) { } internal CTFontDescriptor (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw ConstructorError.ArgumentNull (this, "handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } ~CTFontDescriptor () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get {return handle;} } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #region Descriptor Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateWithNameAndSize (IntPtr name, float size); public CTFontDescriptor (string name, float size) { if (name == null) throw ConstructorError.ArgumentNull (this, "name"); using (CFString n = name) handle = CTFontDescriptorCreateWithNameAndSize (n.Handle, size); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateWithAttributes (IntPtr attributes); public CTFontDescriptor (CTFontDescriptorAttributes attributes) { if (attributes == null) throw ConstructorError.ArgumentNull (this, "attributes"); handle = CTFontDescriptorCreateWithAttributes (attributes.Dictionary.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateCopyWithAttributes (IntPtr original, IntPtr attributes); public CTFontDescriptor WithAttributes (NSDictionary attributes) { if (attributes == null) throw new ArgumentNullException ("attributes"); return CreateDescriptor (CTFontDescriptorCreateCopyWithAttributes (handle, attributes.Handle)); } static CTFontDescriptor CreateDescriptor (IntPtr h) { if (h == IntPtr.Zero) return null; return new CTFontDescriptor (h, true); } public CTFontDescriptor WithAttributes (CTFontDescriptorAttributes attributes) { if (attributes == null) throw new ArgumentNullException ("attributes"); return CreateDescriptor (CTFontDescriptorCreateCopyWithAttributes (handle, attributes.Dictionary.Handle)); } // TODO: is there a better type to use for variationIdentifier? // uint perhaps? "This is the four character code of the variation axis" [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateCopyWithVariation (IntPtr original, IntPtr variationIdentifier, float variationValue); public CTFontDescriptor WithVariation (uint variationIdentifier, float variationValue) { using (var id = new NSNumber (variationIdentifier)) return CreateDescriptor (CTFontDescriptorCreateCopyWithVariation (handle, id.Handle, variationValue)); } // TODO: is there a better type to use for featureTypeIdentifier, featureSelectorIdentifier? [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateCopyWithFeature (IntPtr original, IntPtr featureTypeIdentifier, IntPtr featureSelectorIdentifier); public CTFontDescriptor WithFeature (NSNumber featureTypeIdentifier, NSNumber featureSelectorIdentifier) { if (featureTypeIdentifier == null) throw new ArgumentNullException ("featureTypeIdentifier"); if (featureSelectorIdentifier == null) throw new ArgumentNullException ("featureSelectorIdentifier"); return CreateDescriptor (CTFontDescriptorCreateCopyWithFeature (handle, featureTypeIdentifier.Handle, featureSelectorIdentifier.Handle)); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateMatchingFontDescriptors (IntPtr descriptor, IntPtr mandatoryAttributes); public CTFontDescriptor[] GetMatchingFontDescriptors (NSSet mandatoryAttributes) { var cfArrayRef = CTFontDescriptorCreateMatchingFontDescriptors (handle, mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle); if (cfArrayRef == IntPtr.Zero) return new CTFontDescriptor [0]; var matches = NSArray.ArrayFromHandle (cfArrayRef, fd => new CTFontDescriptor (cfArrayRef, false)); CFObject.CFRelease (cfArrayRef); return matches; } public CTFontDescriptor[] GetMatchingFontDescriptors (params NSString[] mandatoryAttributes) { NSSet attrs = NSSet.MakeNSObjectSet (mandatoryAttributes); return GetMatchingFontDescriptors (attrs); } public CTFontDescriptor[] GetMatchingFontDescriptors () { NSSet attrs = null; return GetMatchingFontDescriptors (attrs); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateMatchingFontDescriptor (IntPtr descriptor, IntPtr mandatoryAttributes); public CTFontDescriptor GetMatchingFontDescriptor (NSSet mandatoryAttributes) { return CreateDescriptor (CTFontDescriptorCreateMatchingFontDescriptors (handle, mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle)); } public CTFontDescriptor GetMatchingFontDescriptor (params NSString[] mandatoryAttributes) { NSSet attrs = NSSet.MakeNSObjectSet (mandatoryAttributes); return GetMatchingFontDescriptor (attrs); } public CTFontDescriptor GetMatchingFontDescriptor () { NSSet attrs = null; return GetMatchingFontDescriptor (attrs); } #endregion #region Descriptor Accessors [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyAttributes (IntPtr descriptor); public CTFontDescriptorAttributes GetAttributes() { var cfDictRef = CTFontDescriptorCopyAttributes (handle); if (cfDictRef == IntPtr.Zero) return null; var dict = (NSDictionary) Runtime.GetNSObject (cfDictRef); dict.Release (); return new CTFontDescriptorAttributes (dict); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyAttribute (IntPtr descriptor, IntPtr attribute); public NSObject GetAttribute (NSString attribute) { if (attribute == null) throw new ArgumentNullException ("attribute"); return Runtime.GetNSObject (CTFontDescriptorCopyAttribute (handle, attribute.Handle)); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyLocalizedAttribute (IntPtr descriptor, IntPtr attribute, IntPtr language); public NSObject GetLocalizedAttribute (NSString attribute) { return Runtime.GetNSObject (CTFontDescriptorCopyLocalizedAttribute (handle, attribute.Handle, IntPtr.Zero)); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyLocalizedAttribute (IntPtr descriptor, IntPtr attribute, out IntPtr language); public NSObject GetLocalizedAttribute (NSString attribute, out NSString language) { IntPtr lang; var o = Runtime.GetNSObject (CTFontDescriptorCopyLocalizedAttribute (handle, attribute.Handle, out lang)); language = (NSString) Runtime.GetNSObject (lang); if (lang != IntPtr.Zero) CFObject.CFRelease (lang); return o; } #endregion } }
//----------------------------------------------------------------------- // <copyright file="Share.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> // Portions of this task are based on the http://www.codeplex.com/sdctasks. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved. //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.FileSystem { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Management; using Microsoft.Build.Framework; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>CheckExists</i> (<b>Required: </b> ShareName <b>Output:</b> Exists)</para> /// <para><i>Create</i> (<b>Required: </b> ShareName, SharePath <b>Optional: </b>Description, MaximumAllowed, CreateSharePath, AllowUsers, DenyUsers)</para> /// <para><i>Delete</i> (<b>Required: </b> ShareName)</para> /// <para><i>ModifyPermissions</i> (<b>Required: </b> ShareName <b>Optional: </b>AllowUsers, DenyUsers).</para> /// <para><i>SetPermissions</i> (<b>Required: </b> ShareName <b>Optional: </b>AllowUsers, DenyUsers). SetPermissions will reset all existing permissions.</para> /// <para><b>Remote Execution Support:</b> Yes</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="3.5" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <Target Name="Default"> /// <ItemGroup> /// <Allow Include="ADomain\ADomainUser"/> /// <Allow Include="AMachine\ALocalReadUser"> /// <Permission>Read</Permission> /// </Allow> /// <Allow Include="AMachine\ALocalChangeUser"> /// <Permission>Change</Permission> /// </Allow> /// </ItemGroup> /// <!-- Delete shares --> /// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Delete" ShareName="MSBEPS1"/> /// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Delete" ShareName="MSBEPS2"/> /// <!-- Create a share and specify users. The share path will be created if it doesnt exist. --> /// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Create" AllowUsers="@(Allow)" CreateSharePath="true" SharePath="C:\fff1" ShareName="MSBEPS1" Description="A Description of MSBEPS1"/> /// <!-- Create a share. Defaults to full permission for Everyone. --> /// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Create" SharePath="C:\fffd" ShareName="MSBEPS2" Description="A Description of MSBEPS2"/> /// <!-- Create a share on a remote server --> /// <MSBuild.ExtensionPack.FileSystem.Share TaskAction="Create" AllowUsers="@(Allow)" CreateSharePath="true" MachineName="MyFileShareServer" ShareName="Temp" SharePath="D:\Temp" Description="Folder for shared files used." /> /// </Target> /// </Project> /// ]]></code> /// </example> [HelpUrl("http://www.msbuildextensionpack.com/help/3.5.12.0/html/c9f431c3-c240-26ab-32da-74fc81894a72.htm")] public class Share : BaseTask { private const string ModifyPermissionsTaskAction = "ModifyPermissions"; private const string CheckExistsTaskAction = "CheckExists"; private const string DeleteTaskAction = "Delete"; private const string CreateTaskAction = "Create"; private const string SetPermissionsTaskAction = "SetPermissions"; private int newPermissionCount; #region enums private enum ReturnCode : uint { /// <summary> /// Success /// </summary> Success = 0, /// <summary> /// AccessDenied /// </summary> AccessDenied = 2, /// <summary> /// UnknownFailure /// </summary> UnknownFailure = 8, /// <summary> /// InvalidName /// </summary> InvalidName = 9, /// <summary> /// InvalidLevel /// </summary> InvalidLevel = 10, /// <summary> /// InvalidParameter /// </summary> InvalidParameter = 21, /// <summary> /// ShareAlreadyExists /// </summary> ShareAlreadyExists = 22, /// <summary> /// RedirectedPath /// </summary> RedirectedPath = 23, /// <summary> /// UnknownDeviceOrDirectory /// </summary> UnknownDeviceOrDirectory = 24, /// <summary> /// NetNameNotFound /// </summary> NetNameNotFound = 25 } #endregion [DropdownValue(CheckExistsTaskAction)] [DropdownValue(CreateTaskAction)] [DropdownValue(DeleteTaskAction)] [DropdownValue(SetPermissionsTaskAction)] public override string TaskAction { get { return base.TaskAction; } set { base.TaskAction = value; } } /// <summary> /// Sets the desctiption for the share /// </summary> [TaskAction(CreateTaskAction, false)] public string Description { get; set; } /// <summary> /// Sets the share name /// </summary> [Required] [TaskAction(CheckExistsTaskAction, true)] [TaskAction(CreateTaskAction, true)] [TaskAction(DeleteTaskAction, true)] [TaskAction(SetPermissionsTaskAction, true)] public string ShareName { get; set; } /// <summary> /// Sets the share path /// </summary> [TaskAction(CreateTaskAction, true)] public string SharePath { get; set; } /// <summary> /// Sets the maximum number of allowed users for the share /// </summary> [TaskAction(CreateTaskAction, false)] public int MaximumAllowed { get; set; } /// <summary> /// Sets whether to create the SharePath if it doesnt exist. Default is false /// </summary> [TaskAction(CreateTaskAction, false)] public bool CreateSharePath { get; set; } /// <summary> /// Gets whether the share exists /// </summary> [Output] [TaskAction(CheckExistsTaskAction, false)] public bool Exists { get; set; } /// <summary> /// Sets a collection of users allowed to access the share. Use the Permission metadata tag to specify permissions. Default is Full. /// <para/> /// <code lang="xml"><![CDATA[ /// <Allow Include="AUser"> /// <Permission>Full, Read or Change etc</Permission> /// </Allow> /// ]]></code> /// </summary> [TaskAction(CreateTaskAction, false)] [TaskAction(SetPermissionsTaskAction, false)] public ITaskItem[] AllowUsers { get; set; } /// <summary> /// Sets a collection of users not allowed to access the share /// </summary> [TaskAction(CreateTaskAction, false)] [TaskAction(SetPermissionsTaskAction, false)] public ITaskItem[] DenyUsers { get; set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { switch (this.TaskAction) { case CreateTaskAction: this.Create(); break; case DeleteTaskAction: this.Delete(); break; case CheckExistsTaskAction: this.CheckExists(); break; case SetPermissionsTaskAction: this.SetPermissions(); break; case ModifyPermissionsTaskAction: this.ModifyPermissions(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private static ManagementObject GetSecurityIdentifier(ManagementBaseObject account) { // get the sid string sidString = (string)account.Properties["SID"].Value; string sidPathString = string.Format(CultureInfo.InvariantCulture, "Win32_SID.SID='{0}'", sidString); ManagementPath sidPath = new ManagementPath(sidPathString); ManagementObject sid = new ManagementObject(sidPath); try { sid.Get(); return sid; } catch (ManagementException ex) { throw new Exception(string.Format(CultureInfo.InvariantCulture, @"Could not find SID '{0}' for account '{1}\{2}'.", sidString, account.Properties["Domain"].Value, account.Properties["Name"].Value), ex); } } private void CheckExists() { this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Checking whether share: {0} exists on: {1}", this.ShareName, this.MachineName)); this.GetManagementScope(@"\root\cimv2"); ManagementPath fullSharePath = new ManagementPath("Win32_Share.Name='" + this.ShareName + "'"); ManagementObject shareObject = new ManagementObject(this.Scope, fullSharePath, null); // try bind to the share to see if it exists try { shareObject.Get(); this.Exists = true; } catch { this.Exists = false; } } private void Delete() { this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Deleting share: {0} on: {1}", this.ShareName, this.MachineName)); this.GetManagementScope(@"\root\cimv2"); ManagementPath fullSharePath = new ManagementPath("Win32_Share.Name='" + this.ShareName + "'"); ManagementObject shareObject = new ManagementObject(this.Scope, fullSharePath, null); // try bind to the share to see if it exists try { shareObject.Get(); } catch { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.InvariantCulture, "Did not find share: {0} on: {1}", this.ShareName, this.MachineName)); return; } // execute the method and check the return code ManagementBaseObject outputParams = shareObject.InvokeMethod("Delete", null, null); ReturnCode returnCode = (ReturnCode)Convert.ToUInt32(outputParams.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture); if (returnCode != ReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Failed to delete the share. ReturnCode: {0}.", returnCode)); return; } } private void SetPermissions() { this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Set Permissions for share: {0} on: {1}", this.ShareName, this.MachineName)); this.GetManagementScope(@"\root\cimv2"); ManagementPath fullSharePath = new ManagementPath("Win32_Share.Name='" + this.ShareName + "'"); ManagementObject shareObject = new ManagementObject(this.Scope, fullSharePath, null); // try bind to the share to see if it exists try { shareObject.Get(); } catch { this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Did not find share: {0} on: {1}", this.ShareName, this.MachineName)); return; } // Set the input parameters ManagementBaseObject inParams = shareObject.GetMethodParameters("SetShareInfo"); inParams["Access"] = this.SetAccessPermissions(); // execute the method and check the return code ManagementBaseObject outputParams = shareObject.InvokeMethod("SetShareInfo", inParams, null); ReturnCode returnCode = (ReturnCode)Convert.ToUInt32(outputParams.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture); if (returnCode != ReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Failed to set the share permissions. ReturnCode: {0}.", returnCode)); return; } } private void ModifyPermissions() { this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Modify permissions on share: {0} on: {1}", this.ShareName, this.MachineName)); this.GetManagementScope(@"\root\cimv2"); ManagementObject shareObject = null; ObjectQuery query = new ObjectQuery("Select * from Win32_LogicalShareSecuritySetting where Name = '" + this.ShareName + "'"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query)) { ManagementObjectCollection moc = searcher.Get(); if (moc.Count > 0) { shareObject = moc.Cast<ManagementObject>().FirstOrDefault(); } else { this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Did not find share: {0} on: {1}", this.ShareName, this.MachineName)); return; } } ManagementBaseObject securityDescriptorObject = shareObject.InvokeMethod("GetSecurityDescriptor", null, null); if (securityDescriptorObject == null) { this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Error extracting security descriptor from: {0}.", this.ShareName)); return; } ManagementBaseObject[] newaccessControlList = this.BuildAccessControlList(); ManagementBaseObject securityDescriptor = securityDescriptorObject.Properties["Descriptor"].Value as ManagementBaseObject; int existingAcessControlEntriesCount = 0; ManagementBaseObject[] accessControlList = securityDescriptor.Properties["DACL"].Value as ManagementBaseObject[]; if (accessControlList == null) { accessControlList = new ManagementBaseObject[this.newPermissionCount]; } else { existingAcessControlEntriesCount = accessControlList.Length; Array.Resize(ref accessControlList, accessControlList.Length + this.newPermissionCount); } for (int i = 0; i < newaccessControlList.Length; i++) { accessControlList[existingAcessControlEntriesCount + i] = newaccessControlList[i]; } securityDescriptor.Properties["DACL"].Value = accessControlList; ManagementBaseObject parameterForSetSecurityDescriptor = shareObject.GetMethodParameters("SetSecurityDescriptor"); parameterForSetSecurityDescriptor["Descriptor"] = securityDescriptor; shareObject.InvokeMethod("SetSecurityDescriptor", parameterForSetSecurityDescriptor, null); } private void Create() { this.LogTaskMessage(string.Format(CultureInfo.InvariantCulture, "Creating share: {0} on: {1}", this.ShareName, this.MachineName)); this.GetManagementScope(@"\root\cimv2"); ManagementPath path = new ManagementPath("Win32_Share"); ManagementClass managementClass = new ManagementClass(this.Scope, path, null); if (!this.TargetingLocalMachine(true)) { // we need to operate remotely string fullQuery = @"Select * From Win32_Directory Where Name = '" + this.SharePath.Replace("\\", "\\\\") + "'"; ObjectQuery query1 = new ObjectQuery(fullQuery); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query1)) { ManagementObjectCollection queryCollection = searcher.Get(); if (queryCollection.Count == 0) { if (this.CreateSharePath) { this.LogTaskMessage(MessageImportance.Low, "Attempting to create remote folder for share"); ManagementPath path2 = new ManagementPath("Win32_Process"); ManagementClass managementClass2 = new ManagementClass(this.Scope, path2, null); ManagementBaseObject inParams1 = managementClass2.GetMethodParameters("Create"); string tex = "cmd.exe /c md \"" + this.SharePath + "\""; inParams1["CommandLine"] = tex; ManagementBaseObject outParams1 = managementClass2.InvokeMethod("Create", inParams1, null); uint rc = Convert.ToUInt32(outParams1.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture); if (rc != 0) { this.Log.LogError(string.Format(CultureInfo.InvariantCulture, "Non-zero return code attempting to create remote share location: {0}", rc)); return; } // adding a sleep as it may take a while to register. System.Threading.Thread.Sleep(1000); } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SharePath not found: {0}. Set CreateSharePath to true to create a SharePath that does not exist.", this.SharePath)); return; } } } } else { // we are working locally if (!Directory.Exists(this.SharePath)) { if (this.CreateSharePath) { Directory.CreateDirectory(this.SharePath); // adding a sleep as it may take a while to register. System.Threading.Thread.Sleep(1000); } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SharePath not found: {0}. Set CreateSharePath to true to create a SharePath that does not exist.", this.SharePath)); return; } } } // Set the input parameters ManagementBaseObject inParams = managementClass.GetMethodParameters("Create"); inParams["Description"] = this.Description; inParams["Name"] = this.ShareName; inParams["Path"] = this.SharePath; // build the access permissions if (this.AllowUsers != null | this.DenyUsers != null) { inParams["Access"] = this.SetAccessPermissions(); } // Disk Drive inParams["Type"] = 0x0; if (this.MaximumAllowed > 0) { inParams["MaximumAllowed"] = this.MaximumAllowed; } ManagementBaseObject outParams = managementClass.InvokeMethod("Create", inParams, null); ReturnCode returnCode = (ReturnCode)Convert.ToUInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.InvariantCulture); switch (returnCode) { case ReturnCode.Success: break; case ReturnCode.AccessDenied: this.Log.LogError("Access Denied"); break; case ReturnCode.UnknownFailure: this.Log.LogError("Unknown Failure"); break; case ReturnCode.InvalidName: this.Log.LogError("Invalid Name"); break; case ReturnCode.InvalidLevel: this.Log.LogError("Invalid Level"); break; case ReturnCode.InvalidParameter: this.Log.LogError("Invalid Parameter"); break; case ReturnCode.RedirectedPath: this.Log.LogError("Redirected Path"); break; case ReturnCode.UnknownDeviceOrDirectory: this.Log.LogError("Unknown Device or Directory"); break; case ReturnCode.NetNameNotFound: this.Log.LogError("Net name not found"); break; case ReturnCode.ShareAlreadyExists: this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "The share already exists: {0}", this.ShareName)); break; } } private ManagementObject SetAccessPermissions() { // build the security descriptor ManagementPath securityDescriptorPath = new ManagementPath("Win32_SecurityDescriptor"); ManagementObject securityDescriptor = new ManagementClass(this.Scope, securityDescriptorPath, null).CreateInstance(); // default owner | default group | DACL present | default SACL securityDescriptor.Properties["ControlFlags"].Value = 0x1U | 0x2U | 0x4U | 0x20U; securityDescriptor.Properties["DACL"].Value = this.BuildAccessControlList(); return securityDescriptor; } private ManagementObject[] BuildAccessControlList() { List<ManagementObject> acl = new List<ManagementObject>(); if (this.AllowUsers != null) { foreach (ITaskItem user in this.AllowUsers) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Allowing user: {0}", user.ItemSpec)); ManagementObject trustee = this.BuildTrustee(user.ItemSpec); acl.Add(this.BuildAccessControlEntry(user, trustee, false)); } } if (this.DenyUsers != null) { foreach (ITaskItem user in this.DenyUsers) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Denying user: {0}", user.ItemSpec)); ManagementObject trustee = this.BuildTrustee(user.ItemSpec); acl.Add(this.BuildAccessControlEntry(user, trustee, true)); } } this.newPermissionCount = acl.Count; return acl.ToArray(); } private ManagementObject BuildTrustee(string userName) { if (!userName.Contains(@"\")) { // default to local user userName = Environment.MachineName + @"\" + userName; } // build the trustee string[] userNameParts = userName.Split('\\'); string domain = userNameParts[0]; string alias = userNameParts[1]; ManagementObject account = this.GetAccount(domain, alias); ManagementObject sid = GetSecurityIdentifier(account); ManagementPath trusteePath = new ManagementPath("Win32_Trustee"); ManagementObject trustee = new ManagementClass(this.Scope, trusteePath, null).CreateInstance(); trustee.Properties["Domain"].Value = domain; trustee.Properties["Name"].Value = alias; trustee.Properties["SID"].Value = sid.Properties["BinaryRepresentation"].Value; trustee.Properties["SidLength"].Value = sid.Properties["SidLength"].Value; trustee.Properties["SIDString"].Value = sid.Properties["SID"].Value; return trustee; } private ManagementObject GetAccount(string domain, string alias) { // get the account - try to get it by searching those on the machine first which gets local accounts string queryString = string.Format(CultureInfo.InvariantCulture, "select * from Win32_Account where Name = '{0}' and Domain='{1}'", alias, domain); ObjectQuery query = new ObjectQuery(queryString); ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query); foreach (ManagementObject returnedAccount in searcher.Get()) { return returnedAccount; } // didn't find it on the machine so we'll try to bind to it using a path - this works for domain accounts string accountPathString = string.Format(CultureInfo.InvariantCulture, "Win32_Account.Name='{0}',Domain='{1}'", alias, domain); ManagementPath accountPath = new ManagementPath(accountPathString); ManagementObject account = new ManagementObject(accountPath); try { account.Get(); return account; } catch (ManagementException ex) { throw new Exception(string.Format(CultureInfo.InvariantCulture, @"Could not find account '{0}\{1}'.", domain, alias), ex); } } private ManagementObject BuildAccessControlEntry(ITaskItem user, ManagementObject trustee, bool deny) { ManagementPath acePath = new ManagementPath("Win32_ACE"); ManagementObject ace = new ManagementClass(this.Scope, acePath, null).CreateInstance(); string permissions = user.GetMetadata("Permission"); if (string.IsNullOrEmpty(permissions) | permissions.IndexOf("Full", StringComparison.OrdinalIgnoreCase) >= 0) { // apply all permissions this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Setting Full permission for: {0}", user.ItemSpec)); ace.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x10000U | 0x20000U | 0x40000U | 0x80000U | 0x100000U; } else { if (permissions.IndexOf("Read", StringComparison.OrdinalIgnoreCase) >= 0) { // readonly permission this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Setting Read permission for: {0}", user.ItemSpec)); ace.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x20000U | 0x40000U | 0x80000U | 0x100000U; } if (permissions.IndexOf("Change", StringComparison.OrdinalIgnoreCase) >= 0) { // change permission this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Setting Change permission for: {0}", user.ItemSpec)); ace.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x10000U | 0x20000U | 0x40000U | 0x100000U; } } // no flags ace.Properties["AceFlags"].Value = 0x0U; // 0 = allow, 1 = deny ace.Properties["AceType"].Value = deny ? 1U : 0U; ace.Properties["Trustee"].Value = trustee; return ace; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.Isam.Esent.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Esent { internal partial class EsentStorage { // set db page size to 8K and version store page size to 16K private const int DatabasePageSize = 2 * 4 * 1024; private const int VersionStorePageSize = 4 * 4 * 1024; // JET parameter consts private const int JET_paramIOPriority = 152; private const int JET_paramCheckpointIOMax = 135; private const int JET_paramVerPageSize = 128; private const int JET_paramDisablePerfmon = 107; private const int JET_paramPageHintCacheSize = 101; private const int JET_paramLogFileCreateAsynch = 69; private const int JET_paramOutstandingIOMax = 30; private const int JET_paramLRUKHistoryMax = 26; private const int JET_paramCommitDefault = 16; private readonly string _databaseFile; private readonly bool _enablePerformanceMonitor; private readonly Dictionary<TableKinds, AbstractTable> _tables; private readonly ConcurrentStack<OpenSession> _sessionCache; private readonly CancellationTokenSource _shutdownCancellationTokenSource; private Instance _instance; private Session _primarySessionId; private JET_DBID _primaryDatabaseId; public EsentStorage(string databaseFile, bool enablePerformanceMonitor = false) { Contract.Requires(!string.IsNullOrWhiteSpace(databaseFile)); _databaseFile = databaseFile; _enablePerformanceMonitor = enablePerformanceMonitor; // order of tables are fixed. don't change it _tables = new Dictionary<TableKinds, AbstractTable>() { { TableKinds.Name, new NameTable() }, { TableKinds.Solution, new SolutionTable() }, { TableKinds.Project, new ProjectTable() }, { TableKinds.Document, new DocumentTable() }, { TableKinds.Identifier, new IdentifierNameTable() }, { TableKinds.IdentifierLocations, new IdentifierLocationTable() }, }; _sessionCache = new ConcurrentStack<OpenSession>(); _shutdownCancellationTokenSource = new CancellationTokenSource(); } public void Initialize() { _instance = CreateEsentInstance(); _primarySessionId = new Session(_instance); InitializeDatabaseAndTables(); } public bool IsClosed { get { return _instance == null; } } public void Close() { if (_instance != null) { var handle = _instance; _instance = null; // try to free all allocated session - if succeeded we can try to do a clean shutdown _shutdownCancellationTokenSource.Cancel(); try { // just close the instance - all associated objects will be closed as well _primarySessionId.Dispose(); handle.Dispose(); } catch { // ignore exception if whatever reason esent throws an exception. } _shutdownCancellationTokenSource.Dispose(); } } public int GetUniqueId(string value) { return GetUniqueId(value, TableKinds.Name); } public int GetUniqueIdentifierId(string value) { return GetUniqueId(value, TableKinds.Identifier); } private int GetUniqueId(string value, TableKinds tableKind) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(value)); using (var accessor = (StringNameTableAccessor)GetTableAccessor(tableKind)) { return accessor.GetUniqueId(value); } } public SolutionTableAccessor GetSolutionTableAccessor() { return (SolutionTableAccessor)GetTableAccessor(TableKinds.Solution); } public ProjectTableAccessor GetProjectTableAccessor() { return (ProjectTableAccessor)GetTableAccessor(TableKinds.Project); } public DocumentTableAccessor GetDocumentTableAccessor() { return (DocumentTableAccessor)GetTableAccessor(TableKinds.Document); } public IdentifierLocationTableAccessor GetIdentifierLocationTableAccessor() { return (IdentifierLocationTableAccessor)GetTableAccessor(TableKinds.IdentifierLocations); } private AbstractTableAccessor GetTableAccessor(TableKinds tableKind) { return _tables[tableKind].GetTableAccessor(GetOpenSession()); } private OpenSession GetOpenSession() { OpenSession session; if (_sessionCache.TryPop(out session)) { return session; } return new OpenSession(this, _databaseFile, _shutdownCancellationTokenSource.Token); } private void CloseSession(OpenSession session) { if (_shutdownCancellationTokenSource.IsCancellationRequested) { session.Close(); return; } if (_sessionCache.Count > 5) { session.Close(); return; } _sessionCache.Push(session); } private Instance CreateEsentInstance() { var instanceDataFolder = Path.GetDirectoryName(_databaseFile); TryInitializeGlobalParameters(); var instance = new Instance(Path.GetFileName(_databaseFile), _databaseFile, TermGrbit.Complete); // create log file preemptively Api.JetSetSystemParameter(instance.JetInstance, JET_SESID.Nil, (JET_param)JET_paramLogFileCreateAsynch, /* true */ 1, null); // set default commit mode Api.JetSetSystemParameter(instance.JetInstance, JET_SESID.Nil, (JET_param)JET_paramCommitDefault, /* lazy */ 1, null); // remove transaction log file that is not needed anymore instance.Parameters.CircularLog = true; // transaction log file buffer 1M (1024 * 2 * 512 bytes) instance.Parameters.LogBuffers = 2 * 1024; // transaction log file is 2M (2 * 1024 * 1024 bytes) instance.Parameters.LogFileSize = 2 * 1024; // db directories instance.Parameters.LogFileDirectory = instanceDataFolder; instance.Parameters.SystemDirectory = instanceDataFolder; instance.Parameters.TempDirectory = instanceDataFolder; // Esent uses version pages to store intermediate non-committed data during transactions // smaller values may cause VersionStoreOutOfMemory error when dealing with multiple transactions\writing lot's of data in transaction or both // it is about 16MB - this is okay to be big since most of it is temporary memory that will be released once the last transaction goes away instance.Parameters.MaxVerPages = 16 * 1024 * 1024 / VersionStorePageSize; // set the size of max transaction log size (in bytes) that should be replayed after the crash // small values: smaller log files but potentially longer transaction flushes if there was a crash (6M) instance.Parameters.CheckpointDepthMax = 6 * 1024 * 1024; // how much db grows when it finds db is full (1M) // (less I/O as value gets bigger) instance.Parameters.DbExtensionSize = 1024 * 1024 / DatabasePageSize; // fail fast if log file is wrong. we will recover from it by creating db from scratch instance.Parameters.CleanupMismatchedLogFiles = true; instance.Parameters.EnableIndexChecking = true; // now, actually initialize instance instance.Init(); return instance; } private void TryInitializeGlobalParameters() { int instances; JET_INSTANCE_INFO[] infos; Api.JetGetInstanceInfo(out instances, out infos); // already initialized nothing we can do. if (instances != 0) { return; } try { // use small configuration so that esent use process heap and windows file cache SystemParameters.Configuration = 0; // allow many esent instances SystemParameters.MaxInstances = 1024; // enable perf monitor if requested Api.JetSetSystemParameter(JET_INSTANCE.Nil, JET_SESID.Nil, (JET_param)JET_paramDisablePerfmon, _enablePerformanceMonitor ? 0 : 1, null); // set max IO queue (bigger value better IO perf) Api.JetSetSystemParameter(JET_INSTANCE.Nil, JET_SESID.Nil, (JET_param)JET_paramOutstandingIOMax, 1024, null); // set max current write to db Api.JetSetSystemParameter(JET_INSTANCE.Nil, JET_SESID.Nil, (JET_param)JET_paramCheckpointIOMax, 32, null); // better cache management (4M) Api.JetSetSystemParameter(JET_INSTANCE.Nil, JET_SESID.Nil, (JET_param)JET_paramLRUKHistoryMax, 4 * 1024 * 1024 / DatabasePageSize, null); // better db performance (100K bytes) Api.JetSetSystemParameter(JET_INSTANCE.Nil, JET_SESID.Nil, (JET_param)JET_paramPageHintCacheSize, 100 * 1024, null); // set version page size to normal 16K Api.JetSetSystemParameter(JET_INSTANCE.Nil, JET_SESID.Nil, (JET_param)JET_paramVerPageSize, VersionStorePageSize, null); // use windows file system cache SystemParameters.EnableFileCache = true; // don't use mapped file for database. this will waste more VM. SystemParameters.EnableViewCache = false; // this is the unit where chunks are loaded into memory/locked and etc SystemParameters.DatabasePageSize = DatabasePageSize; // set max cache size - don't use too much memory for cache (8MB) SystemParameters.CacheSizeMax = 8 * 1024 * 1024 / DatabasePageSize; // set min cache size - Esent tries to adjust this value automatically but often it is better to help him. // small cache sizes => more I\O during random seeks // currently set to 2MB SystemParameters.CacheSizeMin = 2 * 1024 * 1024 / DatabasePageSize; // set box of when cache eviction starts (1% - 2% of max cache size) SystemParameters.StartFlushThreshold = 20; SystemParameters.StopFlushThreshold = 40; } catch (EsentAlreadyInitializedException) { // can't change global status } } private void InitializeDatabaseAndTables() { // open database for the first time: database file will be created if necessary // first quick check whether file exist if (!File.Exists(_databaseFile)) { Api.JetCreateDatabase(_primarySessionId, _databaseFile, null, out _primaryDatabaseId, CreateDatabaseGrbit.None); CreateTables(); return; } // file exist, just attach the db. try { // if this succeed, it will lock the file. Api.JetAttachDatabase(_primarySessionId, _databaseFile, AttachDatabaseGrbit.None); } catch (EsentFileNotFoundException) { // if someone has deleted the file, while we are attaching. Api.JetCreateDatabase(_primarySessionId, _databaseFile, null, out _primaryDatabaseId, CreateDatabaseGrbit.None); CreateTables(); return; } Api.JetOpenDatabase(_primarySessionId, _databaseFile, null, out _primaryDatabaseId, OpenDatabaseGrbit.None); InitializeTables(); } private void CreateTables() { foreach (var table in _tables.Values) { table.Create(_primarySessionId, _primaryDatabaseId); } } private void InitializeTables() { foreach (var table in _tables.Values) { table.Initialize(_primarySessionId, _primaryDatabaseId); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Text; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class HttpUtilitiesTest { [Theory] [InlineData("CONNECT / HTTP/1.1", true, "CONNECT", (int)HttpMethod.Connect)] [InlineData("DELETE / HTTP/1.1", true, "DELETE", (int)HttpMethod.Delete)] [InlineData("GET / HTTP/1.1", true, "GET", (int)HttpMethod.Get)] [InlineData("HEAD / HTTP/1.1", true, "HEAD", (int)HttpMethod.Head)] [InlineData("PATCH / HTTP/1.1", true, "PATCH", (int)HttpMethod.Patch)] [InlineData("POST / HTTP/1.1", true, "POST", (int)HttpMethod.Post)] [InlineData("PUT / HTTP/1.1", true, "PUT", (int)HttpMethod.Put)] [InlineData("OPTIONS / HTTP/1.1", true, "OPTIONS", (int)HttpMethod.Options)] [InlineData("TRACE / HTTP/1.1", true, "TRACE", (int)HttpMethod.Trace)] [InlineData("GET/ HTTP/1.1", false, null, (int)HttpMethod.Custom)] [InlineData("get / HTTP/1.1", false, null, (int)HttpMethod.Custom)] [InlineData("GOT / HTTP/1.1", false, null, (int)HttpMethod.Custom)] [InlineData("ABC / HTTP/1.1", false, null, (int)HttpMethod.Custom)] [InlineData("PO / HTTP/1.1", false, null, (int)HttpMethod.Custom)] [InlineData("PO ST / HTTP/1.1", false, null, (int)HttpMethod.Custom)] [InlineData("short ", false, null, (int)HttpMethod.Custom)] public void GetsKnownMethod(string input, bool expectedResult, string expectedKnownString, int intExpectedMethod) { var expectedMethod = (HttpMethod)intExpectedMethod; // Arrange var block = new ReadOnlySpan<byte>(Encoding.ASCII.GetBytes(input)); // Act var result = block.GetKnownMethod(out var knownMethod, out var length); string toString = null; if (knownMethod != HttpMethod.Custom) { toString = HttpUtilities.MethodToString(knownMethod); } // Assert Assert.Equal(expectedResult, result); Assert.Equal(expectedMethod, knownMethod); Assert.Equal(toString, expectedKnownString); Assert.Equal(length, expectedKnownString?.Length ?? 0); } [Theory] [InlineData("HTTP/1.0\r", true, "HTTP/1.0", (int)HttpVersion.Http10)] [InlineData("HTTP/1.1\r", true, "HTTP/1.1", (int)HttpVersion.Http11)] [InlineData("HTTP/1.1\rmoretext", true, "HTTP/1.1", (int)HttpVersion.Http11)] [InlineData("HTTP/3.0\r", false, null, (int)HttpVersion.Unknown)] [InlineData("http/1.0\r", false, null, (int)HttpVersion.Unknown)] [InlineData("http/1.1\r", false, null, (int)HttpVersion.Unknown)] [InlineData("short ", false, null, (int)HttpVersion.Unknown)] public void GetsKnownVersion(string input, bool expectedResult, string expectedKnownString, int intVersion) { var version = (HttpVersion)intVersion; // Arrange var block = new ReadOnlySpan<byte>(Encoding.ASCII.GetBytes(input)); // Act var result = block.GetKnownVersion(out HttpVersion knownVersion, out var length); string toString = null; if (knownVersion != HttpVersion.Unknown) { toString = HttpUtilities.VersionToString(knownVersion); } // Assert Assert.Equal(version, knownVersion); Assert.Equal(expectedResult, result); Assert.Equal(expectedKnownString, toString); Assert.Equal(expectedKnownString?.Length ?? 0, length); } [Theory] [InlineData("HTTP/1.0\r", "HTTP/1.0")] [InlineData("HTTP/1.1\r", "HTTP/1.1")] public void KnownVersionsAreInterned(string input, string expected) { TestKnownStringsInterning(input, expected, span => { HttpUtilities.GetKnownVersion(span, out var version, out var _); return HttpUtilities.VersionToString(version); }); } [Theory] [InlineData("https://host/", "https://")] [InlineData("http://host/", "http://")] public void KnownSchemesAreInterned(string input, string expected) { TestKnownStringsInterning(input, expected, span => { HttpUtilities.GetKnownHttpScheme(span, out var scheme); return HttpUtilities.SchemeToString(scheme); }); } [Theory] [InlineData("CONNECT / HTTP/1.1", "CONNECT")] [InlineData("DELETE / HTTP/1.1", "DELETE")] [InlineData("GET / HTTP/1.1", "GET")] [InlineData("HEAD / HTTP/1.1", "HEAD")] [InlineData("PATCH / HTTP/1.1", "PATCH")] [InlineData("POST / HTTP/1.1", "POST")] [InlineData("PUT / HTTP/1.1", "PUT")] [InlineData("OPTIONS / HTTP/1.1", "OPTIONS")] [InlineData("TRACE / HTTP/1.1", "TRACE")] public void KnownMethodsAreInterned(string input, string expected) { TestKnownStringsInterning(input, expected, span => { HttpUtilities.GetKnownMethod(span, out var method, out var length); return HttpUtilities.MethodToString(method); }); } private void TestKnownStringsInterning(string input, string expected, Func<byte[], string> action) { // Act var knownString1 = action(Encoding.ASCII.GetBytes(input)); var knownString2 = action(Encoding.ASCII.GetBytes(input)); // Assert Assert.Equal(knownString1, expected); Assert.Same(knownString1, knownString2); } public static TheoryData<string> HostHeaderData { get { return new TheoryData<string> { "z", "1", "y:1", "1:1", "[ABCdef]", "[abcDEF]:0", "[abcdef:127.2355.1246.114]:0", "[::1]:80", "127.0.0.1:80", "900.900.900.900:9523547852", "foo", "foo:234", "foo.bar.baz", "foo.BAR.baz:46245", "foo.ba-ar.baz:46245", "-foo:1234", "xn--asdfaf:134", "-", "_", "~", "!", "$", "'", "(", ")", }; } } [Theory] [MemberData(nameof(HostHeaderData))] public void ValidHostHeadersParsed(string host) { Assert.True(HttpUtilities.IsHostHeaderValid(host)); } public static TheoryData<string> HostHeaderInvalidData { get { // see https://tools.ietf.org/html/rfc7230#section-5.4 var data = new TheoryData<string> { "[]", // Too short "[::]", // Too short "[ghijkl]", // Non-hex "[afd:adf:123", // Incomplete "[afd:adf]123", // Missing : "[afd:adf]:", // Missing port digits "[afd adf]", // Space "[ad-314]", // dash ":1234", // Missing host "a:b:c", // Missing [] "::1", // Missing [] "::", // Missing everything "abcd:1abcd", // Letters in port "abcd:1.2", // Dot in port "1.2.3.4:", // Missing port digits "1.2 .4", // Space }; // These aren't allowed anywhere in the host header var invalid = "\"#%*+,/;<=>?@[]\\^`{}|"; foreach (var ch in invalid) { data.Add(ch.ToString()); } invalid = "!\"#$%&'()*+,/;<=>?@[]\\^_`{}|~-"; foreach (var ch in invalid) { data.Add("[abd" + ch + "]:1234"); } invalid = "!\"#$%&'()*+,/;<=>?@[]\\^_`{}|~:abcABC-."; foreach (var ch in invalid) { data.Add("a.b.c:" + ch); } return data; } } [Theory] [MemberData(nameof(HostHeaderInvalidData))] public void InvalidHostHeadersRejected(string host) { Assert.False(HttpUtilities.IsHostHeaderValid(host)); } public static TheoryData<Func<string, Encoding>> ExceptionThrownForCRLFData { get { return new TheoryData<Func<string, Encoding>> { KestrelServerOptions.DefaultHeaderEncodingSelector, str => null, str => Encoding.Latin1 }; } } [Theory] [MemberData(nameof(ExceptionThrownForCRLFData))] private void ExceptionThrownForCRLF(Func<string, Encoding> selector) { byte[] encodedBytes = { 0x01, 0x0A, 0x0D }; Assert.Throws<InvalidOperationException>(() => HttpUtilities.GetRequestHeaderString(encodedBytes.AsSpan(), HeaderNames.Accept, selector, checkForNewlineChars : true)); } [Theory] [MemberData(nameof(ExceptionThrownForCRLFData))] private void ExceptionNotThrownForCRLF(Func<string, Encoding> selector) { byte[] encodedBytes = { 0x01, 0x0A, 0x0D }; HttpUtilities.GetRequestHeaderString(encodedBytes.AsSpan(), HeaderNames.Accept, selector, checkForNewlineChars : false); } } }
#pragma warning disable 0168 using System; using System.Collections.Generic; using System.Linq; using nHydrate.Generator.Common.Util; namespace nHydrate.Dsl { partial class Entity : nHydrate.Dsl.IDatabaseEntity, nHydrate.Dsl.IFieldContainer, nHydrate.Generator.Common.GeneratorFramework.IDirtyable { public string DatabaseName => this.Name; public string PascalName { get { if (!string.IsNullOrEmpty(this.CodeFacade)) return StringHelper.DatabaseNameToPascalCase(this.CodeFacade); else return StringHelper.DatabaseNameToPascalCase(this.Name); } } /// <summary> /// Get the full hierarchy of tables starting with this table /// and working back to the most base table /// </summary> public IEnumerable<Entity> GetTableHierarchy() { return new[] {this}; } /// <summary> /// Returns the generated columns for this table only (not hierarchy) /// </summary> public IEnumerable<Field> GeneratedColumns { get { return this.Fields.OrderBy(x => x.Name); } } /// <summary> /// Determines the fields that constitute the table primary key. /// </summary> public IList<Field> PrimaryKeyFields { get { return this.Fields.Where(x => x.IsPrimaryKey).ToList(); } } public IList<Index> IndexList { get { return this.Store.ElementDirectory.AllElements .Where(x => x is Index) .ToList() .Cast<Index>() .Where(x => x.Entity == this) .ToList(); } } public IList<EntityHasEntities> RelationshipList { get { return this.Store.ElementDirectory.AllElements .Where(x => x is EntityHasEntities) .ToList() .Cast<EntityHasEntities>() .Where(x => x.SourceEntity == this) .ToList(); } } /// <summary> /// Returns generated relations for this table /// </summary> public IEnumerable<EntityHasEntities> GetRelationsWhereChild() { return this.nHydrateModel.GetRelationsWhereChild(this); } /// <summary> /// Returns a list of all parent and child relations /// </summary> public IList<EntityHasEntities> AllRelationships { get { var retval = new List<EntityHasEntities>(); foreach (var r in this.Store.ElementDirectory.AllElements.Where(x => x is EntityHasEntities).Cast<EntityHasEntities>()) { if ((r.SourceEntity != null) && (r.TargetEntity != null)) { if ((r.SourceEntity == this) || (r.TargetEntity == this)) { retval.Add(r); } } } return retval; } } /// <summary> /// This gets all columns from this and all base classes /// </summary> /// <returns></returns> public IEnumerable<Field> GetColumnsFullHierarchy() { try { var nameList = new List<string>(); var retval = new List<Field>(); var t = this; while (t != null) { foreach (var c in t.Fields) { if (!nameList.Contains(c.Name.ToLower())) { nameList.Add(c.Name.ToLower()); retval.Add(c); } } //t = t.ParentInheritedEntity; t = null; } return retval; } catch (Exception ex) { throw; } } /// <summary> /// Given a field from this table a search is performed to get the same column from all base tables down the inheritance hierarchy /// </summary> public IEnumerable<Field> GetBasePKColumnList(Field column) { if (column == null) throw new Exception("The column cannot be null."); if (this.PrimaryKeyFields.Count(x => x.Name == column.Name) == 0) throw new Exception("The column does not belong to this table."); var retval = new List<Field>(); var tList = GetTableHierarchy(); foreach (var table in tList) { column = table.PrimaryKeyFields.FirstOrDefault(x => x.Name == column.Name); if (column == null) break; else retval.Add(column); } return retval; } /// <summary> /// Given a field from this table a search is performed to get the same column from the base table if one exists /// </summary> public Field GetBasePKColumn(Field column) { if (column == null) throw new Exception("The column cannot be null."); if (this.PrimaryKeyFields.Count(x => x.Name == column.Name) == 0) throw new Exception("The column does not belong to this table."); var tList = new List<Entity>(GetTableHierarchy()); tList.Add(this); return tList.First().PrimaryKeyFields.FirstOrDefault(x => x.Name == column.Name); } /// <summary> /// Returns all primary keys from the ultimate ancestor in the table hierarchy /// </summary> public IEnumerable<Field> GetBasePKColumnList() { var retval = new List<Field>(); var tList = new List<Entity>(GetTableHierarchy()); tList.Add(this); foreach (var column in this.PrimaryKeyFields) { retval.Add(tList.First().PrimaryKeyFields.First(x => x.Name == column.Name)); } return retval; } public IEnumerable<EntityHasEntities> GetRelationsFullHierarchy() { try { var allRelations = new List<EntityHasEntities>(); var allTables = this.GetTableHierarchy(); foreach (var entity in allTables) { foreach (var relation in entity.AllRelationships) { allRelations.Add(relation); } } return allRelations; } catch (Exception ex) { throw; } } public bool IsValidInheritance { get { var inheritTables = new List<Entity>(this.GetTableHierarchy()); if (inheritTables.Count == 1) return true; var pkList = new Dictionary<string, Field>(); foreach (var c in this.PrimaryKeyFields.OrderBy(x => x.Name)) { if (pkList.ContainsKey(c.Name)) return true; pkList.Add(c.Name, c); } //Ensure that all tables have the same primary keys foreach (var t in inheritTables) { if (t.PrimaryKeyFields.Count != this.PrimaryKeyFields.Count) { //Different number of pk columns so invalid return false; } else { foreach (var c in t.PrimaryKeyFields.OrderBy(x => x.Name)) { if (!pkList.ContainsKey(c.Name)) return false; if (pkList[c.Name].DataType != c.DataType) return false; } } } //Ensure that all tables in inheritance hierarchy //do not have duplicate column names except primary keys var columNames = new List<string>(); foreach (var t in inheritTables) { foreach (var c in t.Fields) { //Make sure this is not a PK if (!pkList.ContainsKey(c.Name)) { //If the column already exists then it is a duplicate if (columNames.Contains(c.Name)) return false; columNames.Add(c.Name); } } } return true; } } public override bool Immutable { get { if (this.TypedEntity != TypedEntityConstants.None) return true; return base.Immutable; } set { base.Immutable = value; } } public override string ToString() { return this.Name; } protected override void OnDeleting() { if (this.nHydrateModel != null) this.nHydrateModel.RemovedTables.Add(this.PascalName); base.OnDeleting(); } #region IFieldContainer Members public IEnumerable<IField> FieldList { get { return this.Fields; } } #endregion } partial class EntityBase { private bool CanMergeStaticData(Microsoft.VisualStudio.Modeling.ProtoElementBase rootElement, Microsoft.VisualStudio.Modeling.ElementGroupPrototype elementGroupPrototype) { return false; } private bool CanMergeSelectCommand(Microsoft.VisualStudio.Modeling.ProtoElementBase rootElement, Microsoft.VisualStudio.Modeling.ElementGroupPrototype elementGroupPrototype) { return false; } private bool CanMergeComposite(Microsoft.VisualStudio.Modeling.ProtoElementBase rootElement, Microsoft.VisualStudio.Modeling.ElementGroupPrototype elementGroupPrototype) { return false; } partial class NamePropertyHandler { protected override void OnValueChanged(EntityBase element, string oldValue, string newValue) { if (element.nHydrateModel != null && !element.nHydrateModel.IsLoading) { if (string.IsNullOrEmpty(newValue)) throw new Exception("The name must have a value."); var count = element.nHydrateModel.Entities.Count(x => x.Name.ToLower() == newValue.ToLower() && x.Id != element.Id); if (count > 0) throw new Exception("There is already an object with the specified name. The change has been cancelled."); } base.OnValueChanged(element, oldValue, newValue); } } private void SetSecurityValue(string v) { } private string _copyStateInfo = ""; private string GetCopyStateInfoValue() { return _copyStateInfo; } private void SetCopyStateInfoValue(string v) { _copyStateInfo = v; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider { internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { return text[characterPosition] == '<'; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, TextSpan span, CompletionTrigger trigger, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>(); if (parentTrivia == null) { return null; } var items = new List<CompletionItem>(); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var attachedToken = parentTrivia.ParentTrivia.Token; if (attachedToken.Kind() == SyntaxKind.None) { return null; } var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false); ISymbol declaredSymbol = null; var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken); } else { var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); } } if (declaredSymbol != null) { items.AddRange(GetTagsForSymbol(declaredSymbol, span, parentTrivia, token)); } if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText || (token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) || (token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement))) { if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement) { items.AddRange(GetNestedTags(span)); } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) & token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement)) { var element = (XmlElementSyntax)token.Parent.Parent.Parent; if (element.StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems(span)); } if (token.Parent.Parent is DocumentationCommentTriviaSyntax) { items.AddRange(GetTopLevelSingleUseNames(parentTrivia, span)); items.AddRange(GetTopLevelRepeatableItems(span)); } } if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag) { var startTag = (XmlElementStartTagSyntax)token.Parent; if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems(span)); } } items.AddRange(GetAlwaysVisibleItems(span)); return items; } private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia, TextSpan span) { var names = new HashSet<string>(new[] { SummaryTagName, RemarksTagName, ExampleTagName, CompletionListTagName }); RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText); return names.Select(n => GetItem(n, span)); } private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector) { if (parentTrivia != null) { foreach (var node in parentTrivia.Content) { var element = node as XmlElementSyntax; if (element != null) { names.Remove(selector(element)); } } } } private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, TextSpan itemSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { if (symbol is IMethodSymbol) { return GetTagsForMethod((IMethodSymbol)symbol, itemSpan, trivia, token); } if (symbol is IPropertySymbol) { return GetTagsForProperty((IPropertySymbol)symbol, itemSpan, trivia, token); } if (symbol is INamedTypeSymbol) { return GetTagsForType((INamedTypeSymbol)symbol, itemSpan, trivia); } return SpecializedCollections.EmptyEnumerable<CompletionItem>(); } private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, TextSpan itemSpan, DocumentationCommentTriviaSyntax trivia) { var items = new List<CompletionItem>(); var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet(); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); items.AddRange(typeParameters.Select(t => CreateCompletionItem(itemSpan, FormatParameter(TypeParamTagName, t)))); return items; } private string AttributeSelector(XmlElementSyntax element, string attribute) { if (!element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == NameAttributeName); if (nameAttribute != null) { if (startTag.Name.LocalName.ValueText == attribute) { return nameAttribute.Identifier.Identifier.ValueText; } } } return null; } private IEnumerable<CompletionItem> GetTagsForProperty(IPropertySymbol symbol, TextSpan itemSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<CompletionItem>(); if (symbol.IsIndexer) { var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref if (parentElementName == ParamRefTagName) { items.AddRange(parameters.Select(p => CreateCompletionItem(itemSpan, p))); } return items; } RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); items.AddRange(parameters.Select(p => CreateCompletionItem(itemSpan, FormatParameter(ParamTagName, p)))); } var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet(); items.AddRange(typeParameters.Select(t => CreateCompletionItem(itemSpan, TypeParamTagName, NameAttributeName, t))); items.Add(CreateCompletionItem(itemSpan, "value")); return items; } private IEnumerable<CompletionItem> GetTagsForMethod(IMethodSymbol symbol, TextSpan itemSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<CompletionItem>(); var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref or typeparamref if (parentElementName == ParamRefTagName) { items.AddRange(parameters.Select(p => CreateCompletionItem(itemSpan, p))); } else if (parentElementName == TypeParamRefTagName) { items.AddRange(typeParameters.Select(t => CreateCompletionItem(itemSpan, t))); } return items; } var returns = true; RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); foreach (var node in trivia.Content) { var element = node as XmlElementSyntax; if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; if (startTag.Name.LocalName.ValueText == ReturnsTagName) { returns = false; break; } } } items.AddRange(parameters.Select(p => CreateCompletionItem(itemSpan, FormatParameter(ParamTagName, p)))); items.AddRange(typeParameters.Select(t => CreateCompletionItem(itemSpan, FormatParameter(TypeParamTagName, t)))); if (returns && !symbol.ReturnsVoid) { items.Add(CreateCompletionItem(itemSpan, ReturnsTagName)); } return items; } private static CompletionItemRules s_defaultRules = CompletionItemRules.Create( filterCharacterRules: FilterRules, commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, '>', '\t')), enterKeyRule: EnterKeyRule.Never); protected override CompletionItemRules GetCompletionItemRules(string displayText) { var commitRules = s_defaultRules.CommitCharacterRules; if (displayText.Contains("\"")) { commitRules = commitRules.Add(WithoutQuoteRule); } if (displayText.Contains(" ")) { commitRules = commitRules.Add(WithoutSpaceRule); } return s_defaultRules.WithCommitCharacterRules(commitRules); } } }
using System.Data; using NUnit.Framework; using System.Threading.Tasks; using System.Collections.Generic; namespace SequelocityDotNet.Tests.SQLite.DatabaseCommandExtensionsTests { [TestFixture] public class ExecuteToMapAsyncTests { public class SuperHero { public long SuperHeroId; public string SuperHeroName; } [Test] public void Should_Call_The_DataRecordCall_Action_For_Each_Record_In_The_Result_Set() { // Arrange const string sql = @" CREATE TABLE IF NOT EXISTS SuperHero ( SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, SuperHeroName NVARCHAR(120) NOT NULL, UNIQUE(SuperHeroName) ); INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' ); INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM SuperHero; "; // Act var superHeroesTask = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString ) .SetCommandText( sql ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ); // Assert Assert.IsInstanceOf<Task<List<SuperHero>>>(superHeroesTask); Assert.That( superHeroesTask.Result.Count == 2 ); } [Test] public void Should_Null_The_DbCommand_By_Default() { // Arrange const string sql = @" CREATE TABLE IF NOT EXISTS SuperHero ( SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, SuperHeroName NVARCHAR(120) NOT NULL, UNIQUE(SuperHeroName) ); INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' ); INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString ) .SetCommandText( sql ); // Act databaseCommand.ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ) .Wait(); // Block until the task completes. // Assert Assert.IsNull( databaseCommand.DbCommand ); } [Test] public void Should_Keep_The_Database_Connection_Open_If_keepConnectionOpen_Parameter_Was_True() { // Arrange const string sql = @" CREATE TABLE IF NOT EXISTS SuperHero ( SuperHeroId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, SuperHeroName NVARCHAR(120) NOT NULL, UNIQUE(SuperHeroName) ); INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Superman' ); INSERT OR IGNORE INTO SuperHero VALUES ( NULL, 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString ) .SetCommandText( sql ); // Act databaseCommand.ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; }, true ) .Wait(); // Block until the task completes. // Assert Assert.That( databaseCommand.DbCommand.Connection.State == ConnectionState.Open ); // Cleanup databaseCommand.Dispose(); } [Test] public void Should_Call_The_DatabaseCommandPreExecuteEventHandler() { // Arrange bool wasPreExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPreExecuteEventHandlers.Add( command => wasPreExecuteEventHandlerCalled = true ); // Act Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString ) .SetCommandText( "SELECT 1 as SuperHeroId, 'Superman' as SuperHeroName" ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ) .Wait(); // Block until the task completes. // Assert Assert.IsTrue( wasPreExecuteEventHandlerCalled ); } [Test] public void Should_Call_The_DatabaseCommandPostExecuteEventHandler() { // Arrange bool wasPostExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPostExecuteEventHandlers.Add( command => wasPostExecuteEventHandlerCalled = true ); // Act Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString ) .SetCommandText( "SELECT 1 as SuperHeroId, 'Superman' as SuperHeroName" ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ) .Wait(); // Block until the task completes. // Assert Assert.IsTrue( wasPostExecuteEventHandlerCalled ); } [Test] public void Should_Call_The_DatabaseCommandUnhandledExceptionEventHandler() { // Arrange bool wasUnhandledExceptionEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandUnhandledExceptionEventHandlers.Add( ( exception, command ) => { wasUnhandledExceptionEventHandlerCalled = true; } ); // Act TestDelegate action = async () => await Sequelocity.GetDatabaseCommandForSQLite( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString ) .SetCommandText( "asdf;lkj" ) .ExecuteToMapAsync( record => { var obj = new SuperHero { SuperHeroId = record.GetValue( 0 ).ToLong(), SuperHeroName = record.GetValue( 1 ).ToString() }; return obj; } ); // Assert Assert.Throws<System.Data.SQLite.SQLiteException>( action ); Assert.IsTrue( wasUnhandledExceptionEventHandlerCalled ); } } }
// CollectSolutions.cs (c) 2004 Kari Laitinen // http://www.naturalprogramming.com // 2004-11-20 File created. // 2004-11-20 Last modification. // Solutions for exercises 14-10, 14-11, 14-12, 14-13, 14-14 // Exercise 14-14 was solved so that the user can select a // collection file via the main menu. This is probably the // best solution to the problem. // Class Collection has a constructor which // automatically loads collection data from file. using System ; using System.IO ; // Classes for file handling. class CollectionItem { string item_name ; string item_maker ; string item_type ; int year_of_making ; public CollectionItem( string given_item_name, string given_item_maker, string given_item_type, int given_year_of_making ) { item_name = given_item_name ; item_maker = given_item_maker ; item_type = given_item_type ; year_of_making = given_year_of_making ; } public CollectionItem( BinaryReader file_containing_collection_data ) { item_name = file_containing_collection_data.ReadString() ; item_maker = file_containing_collection_data.ReadString() ; item_type = file_containing_collection_data.ReadString() ; year_of_making = file_containing_collection_data.ReadInt32() ; } public string get_item_name() { return item_name ; } public string get_item_maker() { return item_maker ; } public string get_item_type() { return item_type ; } public int get_year_of_making() { return year_of_making ; } // The following method is the solution to Exercise 14-13. public override bool Equals( object another_object ) { bool objects_are_equal = false ; if ( another_object != null && another_object is CollectionItem ) { CollectionItem another_collection_item = (CollectionItem) another_object ; if ( item_name == another_collection_item.item_name && item_maker == another_collection_item.item_maker && item_type == another_collection_item.item_type && year_of_making == another_collection_item.year_of_making ) { objects_are_equal = true ; } } return objects_are_equal ; } /***** public bool is_equal_to( CollectionItem another_collection_item ) { return ( item_name == another_collection_item.item_name && item_maker == another_collection_item.item_maker && item_type == another_collection_item.item_type && year_of_making == another_collection_item.year_of_making ) ; } *****/ public string to_line_of_text() { return ( "\n " + item_name.PadRight( 30 ) + item_maker.PadRight( 20 ) + item_type.PadRight( 15 ) + year_of_making.ToString().PadRight( 10 ) ) ; } public void store_to_file( BinaryWriter binary_file ) { binary_file.Write( item_name ) ; binary_file.Write( item_maker ) ; binary_file.Write( item_type ) ; binary_file.Write( year_of_making ) ; } } class Collection { const int MAXIMUM_NUMBER_OF_ITEMS = 100 ; CollectionItem[] items_in_this_collection = new CollectionItem[ MAXIMUM_NUMBER_OF_ITEMS ] ; int number_of_items_in_collection = 0 ; bool collection_data_has_been_modified = false ; string file_of_this_collection = null ; // The default constructor constructs a Collection object // that does not have a file associated with it. These kinds // of Collection objects are returned by some methods of this // class. public Collection() { } public Collection( string given_collection_file ) { file_of_this_collection = given_collection_file ; if ( file_of_this_collection != null && File.Exists( file_of_this_collection ) ) { load_from_file() ; } } public int get_number_of_items() { return number_of_items_in_collection ; } public bool collection_has_been_modified() { return collection_data_has_been_modified ; } public CollectionItem search_item_with_name( string given_item_name ) { bool item_has_been_found = false ; int item_index = 0 ; while ( item_has_been_found == false && item_index < number_of_items_in_collection ) { if ( items_in_this_collection[ item_index ]. get_item_name().IndexOf( given_item_name ) != -1 ) { item_has_been_found = true ; } else { item_index ++ ; } } if ( item_has_been_found == true ) { return items_in_this_collection[ item_index ] ; } else { return null ; } } public void print_all_items() { int item_index = 0 ; while ( item_index < number_of_items_in_collection ) { Console.Write( items_in_this_collection[ item_index ].to_line_of_text() ) ; item_index ++ ; } } public void add_new_item( CollectionItem new_collection_item ) { if ( number_of_items_in_collection >= MAXIMUM_NUMBER_OF_ITEMS ) { Console.Write( "\n Cannot add new collection items!!!! \n" ) ; } else if ( new_collection_item.get_item_name().Length == 0 ) { Console.Write( "\n Invalid collection item data!!!! \n" ) ; } else { items_in_this_collection[ number_of_items_in_collection ] = new_collection_item ; number_of_items_in_collection ++ ; collection_data_has_been_modified = true ; } } public void remove_all_items() { number_of_items_in_collection = 0 ; collection_data_has_been_modified = true ; } public void remove_one_item( CollectionItem item_to_remove ) { bool item_has_been_found = false ; int item_index = 0 ; while ( item_has_been_found == false && item_index < number_of_items_in_collection ) { if ( items_in_this_collection[ item_index ]. Equals( item_to_remove ) ) { item_has_been_found = true ; } else { item_index ++ ; } } if ( item_has_been_found == true ) { // Item will be removed by moving later items one // position upwards in the array of items. while ( item_index < ( number_of_items_in_collection - 1 ) ) { items_in_this_collection[ item_index ] = items_in_this_collection[ item_index + 1 ] ; item_index ++ ; } number_of_items_in_collection -- ; collection_data_has_been_modified = true ; } } public Collection get_items_of_maker( string given_item_maker ) { Collection collection_to_return = new Collection() ; for ( int item_index = 0 ; item_index < number_of_items_in_collection ; item_index ++ ) { if ( items_in_this_collection[ item_index ]. get_item_maker().IndexOf( given_item_maker ) != -1 ) { collection_to_return.add_new_item( items_in_this_collection[ item_index ] ) ; } } return collection_to_return ; } public Collection get_items_of_type( string given_item_type ) { Collection collection_to_return = new Collection() ; for ( int item_index = 0 ; item_index < number_of_items_in_collection ; item_index ++ ) { if ( items_in_this_collection[ item_index ]. get_item_type().IndexOf( given_item_type ) != -1 ) { collection_to_return.add_new_item( items_in_this_collection[ item_index ] ) ; } } return collection_to_return ; } // The following method was constructed to solve Exercise 14-11. public Collection get_items_with_name( string given_item_name ) { Collection collection_to_return = new Collection() ; for ( int item_index = 0 ; item_index < number_of_items_in_collection ; item_index ++ ) { if ( items_in_this_collection[ item_index ]. get_item_name().IndexOf( given_item_name ) != -1 ) { collection_to_return.add_new_item( items_in_this_collection[ item_index ] ) ; } } return collection_to_return ; } public void store_to_file() { try { FileStream file_stream = File.Open( file_of_this_collection, FileMode.Create, FileAccess.Write ) ; BinaryWriter collection_file = new BinaryWriter( file_stream ) ; for ( int item_index = 0 ; item_index < number_of_items_in_collection ; item_index ++ ) { items_in_this_collection[ item_index ]. store_to_file( collection_file ) ; } collection_file.Close() ; Console.Write( "\n Collection items have been stored. \n\n" ) ; } catch ( Exception ) { Console.Write( "\n\n Error in writing file " + file_of_this_collection + "\n Collection items are not stored. \n\n" ) ; } } public void load_from_file() { try { FileStream file_stream = File.OpenRead( file_of_this_collection ) ; BinaryReader collection_file = new BinaryReader( file_stream ) ; int item_index = 0 ; CollectionItem item_from_file ; while ( collection_file.PeekChar() != -1 ) { item_from_file = new CollectionItem( collection_file ) ; items_in_this_collection[ item_index ] = item_from_file ; item_index ++ ; } number_of_items_in_collection = item_index ; collection_file.Close() ; Console.Write( "\n Collection items have been loaded. \n\n" ) ; } catch ( FileNotFoundException ) { Console.Write( "\n File " + file_of_this_collection + " does not exist.\n" ) ; } catch ( Exception ) { Console.Write( "\n Error in reading " + file_of_this_collection + ".\n" ) ; } } } class CollectionMaintainer { Collection this_collection ; string collection_file_in_use ; public CollectionMaintainer() { if ( File.Exists( "collection_file_name.txt" ) ) { collection_file_in_use = read_collection_file_name() ; } else { // This else block is executed only once when this // program is being used for the first time, i.e., when // collection_file_name.txt does not exist yet. collection_file_in_use = "collection_items.data" ; store_collection_file_name() ; } // The constructor of class Collection automatically loads // data from the file that is supplied to it. this_collection = new Collection( collection_file_in_use ) ; } string read_collection_file_name() { string collection_file_name = null ; try { StreamReader file_to_read = new StreamReader( "collection_file_name.txt" ) ; collection_file_name = file_to_read.ReadLine() ; file_to_read.Close() ; } catch ( Exception ) { Console.Write( "\n Cannot read collection_file_name.txt" ) ; } return collection_file_name ; } void store_collection_file_name() { try { StreamWriter file_to_write = new StreamWriter( "collection_file_name.txt" ) ; file_to_write.WriteLine( collection_file_in_use ) ; file_to_write.Close() ; } catch ( Exception ) { Console.Write( "\n Cannot write collection_file_name.txt" ) ; } } bool user_confirms( string text_to_confirm ) { // This method returns true if user types in 'Y' or 'y'. bool user_gave_positive_answer = false ; string user_response = "?????" ; while ( user_response[ 0 ] != 'Y' && user_response[ 0 ] != 'y' && user_response[ 0 ] != 'N' && user_response[ 0 ] != 'n' ) { Console.Write( text_to_confirm ) ; user_response = Console.ReadLine() ; if ( user_response.Length == 0 ) { user_response = "?????" ; } else if ( user_response[ 0 ] == 'Y' || user_response[ 0 ] == 'y' ) { user_gave_positive_answer = true ; } } return user_gave_positive_answer ; } void add_new_collection_items() { bool user_wants_to_add_more_collection_items = true ; while ( user_wants_to_add_more_collection_items == true ) { Console.Write( "\n Give new collection item name or press just" + "\n Enter to stop adding new items: " ) ; string item_name_of_the_new_item = Console.ReadLine() ; if ( item_name_of_the_new_item.Length == 0 ) { user_wants_to_add_more_collection_items = false ; } else { Console.Write( " Give the artist name: " ) ; string item_maker_of_the_new_item = Console.ReadLine() ; Console.Write( " Give collection item type: " ) ; string item_type_of_the_new_item = Console.ReadLine() ; Console.Write( " Give the year of making: " ) ; int year_of_making_of_the_new_item = Convert.ToInt32( Console.ReadLine() ) ; CollectionItem new_collection_item = new CollectionItem( item_name_of_the_new_item, item_maker_of_the_new_item, item_type_of_the_new_item, year_of_making_of_the_new_item ) ; this_collection.add_new_item( new_collection_item ) ; Console.Write( "\n New item has been added to collection. " ) ; } } } void remove_collection_item() { Console.Write( "\n Give the name of the item to remove: " ) ; string item_name_from_user = Console.ReadLine() ; CollectionItem item_to_remove = this_collection.search_item_with_name( item_name_from_user ) ; if ( item_to_remove != null ) { // An item was found in the collection. Console.Write( "\n This collection item was found: " + item_to_remove.to_line_of_text() ) ; if ( user_confirms( "\n Remove this item ( Y/N )?" ) ) { this_collection.remove_one_item( item_to_remove ) ; } else { Console.Write( "\n No item was removed. " ) ; } } else { Console.Write( "\n The item being searched was not found!!!!" ) ; } } void print_data_of_collection_items() { Collection items_to_print = null ; Console.Write( "\n Type in a letter according to menu: \n" + "\n a Print all collection items. " + "\n t Print certain types of items. " + "\n m Print items according to maker's name." + "\n n Print items that have a certain name." + "\n\n " ) ; string user_selection = Console.ReadLine() ; if ( user_selection[ 0 ] == 'a' ) { items_to_print = this_collection ; } else if ( user_selection[ 0 ] == 't' ) { Console.Write( "\n Give the type of the items to be printed: " ) ; string item_type_from_user = Console.ReadLine() ; items_to_print = this_collection. get_items_of_type( item_type_from_user ) ; } else if ( user_selection[ 0 ] == 'm' ) { Console.Write( "\n Give the name of the maker of the item: " ) ; string item_maker_from_user = Console.ReadLine() ; items_to_print = this_collection. get_items_of_maker( item_maker_from_user ) ; } else if ( user_selection[ 0 ] == 'n' ) { Console.Write( "\n Give the name of the item: " ) ; string item_name_from_user = Console.ReadLine() ; items_to_print = this_collection. get_items_with_name( item_name_from_user ) ; } if ( items_to_print != null ) { items_to_print.print_all_items() ; } } void select_new_collection_file() { string[] data_files_in_this_directory = Directory.GetFiles( ".", "*.data" ) ; Console.Write( "\n The following are .data files available: \n" ) ; for ( int file_index = 0 ; file_index < data_files_in_this_directory.Length ; file_index ++ ) { Console.Write( "\n " + ( file_index + 1 ) + " " + data_files_in_this_directory[ file_index ] ) ; } Console.Write( "\n Select one of them with a number of give " + "\n a new file name: " ) ; string user_selection = Console.ReadLine() ; int number_of_selected_file ; string selected_file_name ; try { number_of_selected_file = Convert.ToInt32( user_selection ) ; selected_file_name = data_files_in_this_directory[ number_of_selected_file - 1 ] ; } catch ( Exception ) { selected_file_name = user_selection ; } collection_file_in_use = selected_file_name ; store_collection_file_name() ; // to file collection_file_name.txt this_collection = new Collection( selected_file_name ) ; } void initialize_collection_with_test_data() { this_collection.remove_all_items() ; this_collection.add_new_item( new CollectionItem( "Les Demoiselles d'Avignon","Pablo Picasso", "painting", 1907 ) ); this_collection.add_new_item( new CollectionItem( "The Third of May 1808", "Francisco de Goya", "painting", 1808 ) ); this_collection.add_new_item( new CollectionItem( "Dejeuner sur l'Herbe", "Eduard Manet", "painting", 1863 ) ); this_collection.add_new_item( new CollectionItem( "Mona Lisa", "Leonardo da Vinci", "painting", 1503 ) ); this_collection.add_new_item( new CollectionItem( "David", "Michelangelo", "statue", 1501 ) ); this_collection.add_new_item( new CollectionItem( "The Night Watch", "Rembrandt", "painting", 1642 ) ); this_collection.add_new_item( new CollectionItem( "Guernica", "Pablo Picasso", "painting", 1937 ) ); this_collection.add_new_item( new CollectionItem( "Ulysses", "James Joyce", "manuscript", 1922 )); this_collection.add_new_item( new CollectionItem( "The Egyptian", "Mika Waltari", "manuscript", 1946 )); this_collection.add_new_item( new CollectionItem( "For Whom the Bell Tolls", "Ernest Hemingway","manuscript", 1941 )); } public void run() { string user_selection = "???????" ; Console.Write( "\n This program is a system to help a collector" + "\n to maintain information about his or her" + "\n valuable collection items.\n" ) ; while ( user_selection[ 0 ] != 'q' ) { Console.Write( "\n\n There are currently " + this_collection.get_number_of_items() + " items in the collection. " + "\n Choose what to do by typing in a letter " + "\n according to the following menu: \n" + "\n a Add new collection items. " + "\n r Remove a collection item. " + "\n p Print data of collection items. " + "\n s Store collection data to file. " + "\n l Load collection data from file. " + "\n f Select collection file." + "\n i Initialize collection with test data. " + "\n q Quit the system.\n\n " ) ; user_selection = Console.ReadLine() ; if ( user_selection.Length == 0 ) { Console.Write( "\n Please type in a letter." ) ; user_selection = "?" ; } else if ( user_selection[ 0 ] == 'a' ) { add_new_collection_items() ; } else if ( user_selection[ 0 ] == 'r' ) { remove_collection_item() ; } else if ( user_selection[ 0 ] == 'p' ) { print_data_of_collection_items() ; } else if ( user_selection[ 0 ] == 's' ) { this_collection.store_to_file() ; } else if ( user_selection[ 0 ] == 'l' ) { this_collection.load_from_file() ; } else if ( user_selection[ 0 ] == 'f' ) { // Selecting a new collection file. if ( this_collection.collection_has_been_modified() ) { Console.Write( "\n Current collection has been modified." ) ; if ( user_confirms( "\n Store to file Y/N ? " ) ) { this_collection.store_to_file() ; } } select_new_collection_file() ; } else if ( user_selection[ 0 ] == 'i' ) { initialize_collection_with_test_data() ; } else if ( user_selection[ 0 ] == 'q' ) { if ( this_collection.collection_has_been_modified() ) { Console.Write( "\n Collection has been modified." ) ; if ( user_confirms( "\n Store to file Y/N ? " ) ) { this_collection.store_to_file() ; } } } } } } class Collect { static void Main() { CollectionMaintainer collection_maintainer = new CollectionMaintainer() ; collection_maintainer.run() ; } }
#region Copyright and License Information // Fluent Ribbon Control Suite // http://fluent.codeplex.com/ // Copyright (c) Degtyarev Daniel, Rikker Serg. 2009-2010. All rights reserved. // // Distributed under the terms of the Microsoft Public License (Ms-PL). // The license is available online http://fluent.codeplex.com/license #endregion using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; namespace Fluent { using Fluent.Internal; /// <summary> /// Represent panel with ribbon group. /// It is automatically adjusting size of controls /// </summary> public class RibbonGroupsContainer : Panel, IScrollInfo { #region Reduce Order /// <summary> /// Gets or sets reduce order of group in the ribbon panel. /// It must be enumerated with comma from the first to reduce to /// the last to reduce (use Control.Name as group name in the enum). /// Enclose in parentheses as (Control.Name) to reduce/enlarge /// scalable elements in the given group /// </summary> public string ReduceOrder { get { return (string)this.GetValue(ReduceOrderProperty); } set { this.SetValue(ReduceOrderProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for ReduceOrder. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty ReduceOrderProperty = DependencyProperty.Register("ReduceOrder", typeof(string), typeof(RibbonGroupsContainer), new UIPropertyMetadata(ReduceOrderPropertyChanged)); // handles ReduseOrder property changed static void ReduceOrderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RibbonGroupsContainer ribbonPanel = (RibbonGroupsContainer)d; ribbonPanel.reduceOrder = ((string)e.NewValue).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); ribbonPanel.reduceOrderIndex = ribbonPanel.reduceOrder.Length - 1; ribbonPanel.InvalidateMeasure(); ribbonPanel.InvalidateArrange(); } #endregion #region Fields private string[] reduceOrder = new string[0]; private int reduceOrderIndex; #endregion #region Initialization /// <summary> /// Default constructor /// </summary> public RibbonGroupsContainer() : base() { this.Focusable = false; } #endregion #region Layout Overridings /// <summary> /// Returns a collection of the panel's UIElements. /// </summary> /// <param name="logicalParent">The logical parent of the collection to be created.</param> /// <returns>Returns an ordered collection of elements that have the specified logical parent.</returns> protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent) { return new UIElementCollection(this, /*Parent as FrameworkElement*/this); } /// <summary> /// Measures all of the RibbonGroupBox, and resize them appropriately /// to fit within the available room /// </summary> /// <param name="availableSize">The available size that this element can give to child elements.</param> /// <returns>The size that the groups container determines it needs during /// layout, based on its calculations of child element sizes. /// </returns> protected override Size MeasureOverride(Size availableSize) { var desiredSize = this.GetChildrenDesiredSizeIntermediate(); if (this.reduceOrder.Length == 0) { this.VerifyScrollData(availableSize.Width, desiredSize.Width); return desiredSize; } // If we have more available space - try to expand groups while (desiredSize.Width <= availableSize.Width) { var hasMoreVariants = this.reduceOrderIndex < this.reduceOrder.Length - 1; if (!hasMoreVariants) { break; } // Increase size of another item this.reduceOrderIndex++; this.IncreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]); desiredSize = this.GetChildrenDesiredSizeIntermediate(); } // If not enough space - go to next variant while (desiredSize.Width > availableSize.Width) { var hasMoreVariants = this.reduceOrderIndex >= 0; if (!hasMoreVariants) { break; } // Decrease size of another item this.DecreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]); this.reduceOrderIndex--; desiredSize = this.GetChildrenDesiredSizeIntermediate(); } // Set find values foreach (var item in this.InternalChildren) { var groupBox = item as RibbonGroupBox; if (groupBox == null) { continue; } if ((groupBox.State != groupBox.StateIntermediate) || (groupBox.Scale != groupBox.ScaleIntermediate)) { groupBox.SuppressCacheReseting = true; groupBox.State = groupBox.StateIntermediate; groupBox.Scale = groupBox.ScaleIntermediate; groupBox.InvalidateLayout(); groupBox.Measure(new Size(double.PositiveInfinity, availableSize.Height)); groupBox.SuppressCacheReseting = false; } // Something wrong with cache? if (groupBox.DesiredSizeIntermediate != groupBox.DesiredSize) { // Reset cache and reinvoke masure groupBox.ClearCache(); return this.MeasureOverride(availableSize); } } this.VerifyScrollData(availableSize.Width, desiredSize.Width); return desiredSize; } private Size GetChildrenDesiredSizeIntermediate() { double width = 0; double height = 0; foreach (UIElement child in this.InternalChildren) { var groupBox = child as RibbonGroupBox; if (groupBox == null) { continue; } var desiredSize = groupBox.DesiredSizeIntermediate; width += desiredSize.Width; height = Math.Max(height, desiredSize.Height); } return new Size(width, height); } // Increase size of the item private void IncreaseGroupBoxSize(string name) { var groupBox = this.FindGroup(name); var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase); if (groupBox == null) { return; } if (scale) { groupBox.ScaleIntermediate++; } else { groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Large ? groupBox.StateIntermediate - 1 : RibbonGroupBoxState.Large; } } // Decrease size of the item private void DecreaseGroupBoxSize(string name) { var groupBox = this.FindGroup(name); var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase); if (groupBox == null) { return; } if (scale) { groupBox.ScaleIntermediate--; } else { groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Collapsed ? groupBox.StateIntermediate + 1 : groupBox.StateIntermediate; } } private RibbonGroupBox FindGroup(string name) { if (name.StartsWith("(", StringComparison.OrdinalIgnoreCase)) { name = name.Substring(1, name.Length - 2); } foreach (FrameworkElement child in this.InternalChildren) { if (child.Name == name) { return child as RibbonGroupBox; } } return null; } /// <summary> /// When overridden in a derived class, positions child elements and determines /// a size for a System.Windows.FrameworkElement derived class. /// </summary> /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param> /// <returns>The actual size used.</returns> protected override Size ArrangeOverride(Size finalSize) { var finalRect = new Rect(finalSize) { X = -this.HorizontalOffset }; foreach (UIElement item in this.InternalChildren) { finalRect.Width = item.DesiredSize.Width; finalRect.Height = Math.Max(finalSize.Height, item.DesiredSize.Height); item.Arrange(finalRect); finalRect.X += item.DesiredSize.Width; } return finalSize; } #endregion #region IScrollInfo Members /// <summary> /// Gets or sets a System.Windows.Controls.ScrollViewer element that controls scrolling behavior. /// </summary> public ScrollViewer ScrollOwner { get { return this.ScrollData.ScrollOwner; } set { this.ScrollData.ScrollOwner = value; } } /// <summary> /// Sets the amount of horizontal offset. /// </summary> /// <param name="offset">The degree to which content is horizontally offset from the containing viewport.</param> public void SetHorizontalOffset(double offset) { var newValue = CoerceOffset(ValidateInputOffset(offset, "HorizontalOffset"), this.scrollData.ExtentWidth, this.scrollData.ViewportWidth); if (DoubleUtil.AreClose(this.ScrollData.OffsetX, newValue) == false) { this.scrollData.OffsetX = newValue; this.InvalidateArrange(); } } /// <summary> /// Gets the horizontal size of the extent. /// </summary> public double ExtentWidth { get { return this.ScrollData.ExtentWidth; } } /// <summary> /// Gets the horizontal offset of the scrolled content. /// </summary> public double HorizontalOffset { get { return this.ScrollData.OffsetX; } } /// <summary> /// Gets the horizontal size of the viewport for this content. /// </summary> public double ViewportWidth { get { return this.ScrollData.ViewportWidth; } } /// <summary> /// Scrolls left within content by one logical unit. /// </summary> public void LineLeft() { this.SetHorizontalOffset(this.HorizontalOffset - 16.0); } /// <summary> /// Scrolls right within content by one logical unit. /// </summary> public void LineRight() { this.SetHorizontalOffset(this.HorizontalOffset + 16.0); } /// <summary> /// Forces content to scroll until the coordinate space of a System.Windows.Media.Visual object is visible. /// This is optimized for horizontal scrolling only /// </summary> /// <param name="visual">A System.Windows.Media.Visual that becomes visible.</param> /// <param name="rectangle">A bounding rectangle that identifies the coordinate space to make visible.</param> /// <returns>A System.Windows.Rect that is visible.</returns> public Rect MakeVisible(Visual visual, Rect rectangle) { // We can only work on visuals that are us or children. // An empty rect has no size or position. We can't meaningfully use it. if (rectangle.IsEmpty || visual == null || ReferenceEquals(visual, this) || !this.IsAncestorOf(visual)) { return Rect.Empty; } // Compute the child's rect relative to (0,0) in our coordinate space. GeneralTransform childTransform = visual.TransformToAncestor(this); rectangle = childTransform.TransformBounds(rectangle); // Initialize the viewport Rect viewport = new Rect(this.HorizontalOffset, rectangle.Top, this.ViewportWidth, rectangle.Height); rectangle.X += viewport.X; // Compute the offsets required to minimally scroll the child maximally into view. double minX = ComputeScrollOffsetWithMinimalScroll(viewport.Left, viewport.Right, rectangle.Left, rectangle.Right); // We have computed the scrolling offsets; scroll to them. this.SetHorizontalOffset(minX); // Compute the visible rectangle of the child relative to the viewport. viewport.X = minX; rectangle.Intersect(viewport); rectangle.X -= viewport.X; // Return the rectangle return rectangle; } static double ComputeScrollOffsetWithMinimalScroll( double topView, double bottomView, double topChild, double bottomChild) { // # CHILD POSITION CHILD SIZE SCROLL REMEDY // 1 Above viewport <= viewport Down Align top edge of child & viewport // 2 Above viewport > viewport Down Align bottom edge of child & viewport // 3 Below viewport <= viewport Up Align bottom edge of child & viewport // 4 Below viewport > viewport Up Align top edge of child & viewport // 5 Entirely within viewport NA No scroll. // 6 Spanning viewport NA No scroll. // // Note: "Above viewport" = childTop above viewportTop, childBottom above viewportBottom // "Below viewport" = childTop below viewportTop, childBottom below viewportBottom // These child thus may overlap with the viewport, but will scroll the same direction /*bool fAbove = DoubleUtil.LessThan(topChild, topView) && DoubleUtil.LessThan(bottomChild, bottomView); bool fBelow = DoubleUtil.GreaterThan(bottomChild, bottomView) && DoubleUtil.GreaterThan(topChild, topView);*/ bool fAbove = (topChild < topView) && (bottomChild < bottomView); bool fBelow = (bottomChild > bottomView) && (topChild > topView); bool fLarger = (bottomChild - topChild) > (bottomView - topView); // Handle Cases: 1 & 4 above if ((fAbove && !fLarger) || (fBelow && fLarger)) { return topChild; } // Handle Cases: 2 & 3 above if (fAbove || fBelow) { return bottomChild - (bottomView - topView); } // Handle cases: 5 & 6 above. return topView; } /// <summary> /// Not implemented /// </summary> public void MouseWheelDown() { } /// <summary> /// Not implemented /// </summary> public void MouseWheelLeft() { } /// <summary> /// Not implemented /// </summary> public void MouseWheelRight() { } /// <summary> /// Not implemented /// </summary> public void MouseWheelUp() { } /// <summary> /// Not implemented /// </summary> public void LineDown() { } /// <summary> /// Not implemented /// </summary> public void LineUp() { } /// <summary> /// Not implemented /// </summary> public void PageDown() { } /// <summary> /// Not implemented /// </summary> public void PageLeft() { } /// <summary> /// Not implemented /// </summary> public void PageRight() { } /// <summary> /// Not implemented /// </summary> public void PageUp() { } /// <summary> /// Not implemented /// </summary> /// <param name="offset"></param> public void SetVerticalOffset(double offset) { } /// <summary> /// Gets or sets a value that indicates whether scrolling on the vertical axis is possible. /// </summary> public bool CanVerticallyScroll { get { return false; } set { } } /// <summary> /// Gets or sets a value that indicates whether scrolling on the horizontal axis is possible. /// </summary> public bool CanHorizontallyScroll { get { return true; } set { } } /// <summary> /// Not implemented /// </summary> public double ExtentHeight { get { return 0.0; } }/// <summary> /// Not implemented /// </summary> public double VerticalOffset { get { return 0.0; } } /// <summary> /// Not implemented /// </summary> public double ViewportHeight { get { return 0.0; } } // Gets scroll data info private ScrollData ScrollData { get { return this.scrollData ?? (this.scrollData = new ScrollData()); } } // Scroll data info private ScrollData scrollData; // Validates input offset static double ValidateInputOffset(double offset, string parameterName) { if (double.IsNaN(offset)) { throw new ArgumentOutOfRangeException(parameterName); } return Math.Max(0.0, offset); } // Verifies scrolling data using the passed viewport and extent as newly computed values. // Checks the X/Y offset and coerces them into the range [0, Extent - ViewportSize] // If extent, viewport, or the newly coerced offsets are different than the existing offset, // cachces are updated and InvalidateScrollInfo() is called. private void VerifyScrollData(double viewportWidth, double extentWidth) { bool isValid = true; if (double.IsInfinity(viewportWidth)) { viewportWidth = extentWidth; } double offsetX = CoerceOffset(this.ScrollData.OffsetX, extentWidth, viewportWidth); isValid &= DoubleUtil.AreClose(viewportWidth, this.ScrollData.ViewportWidth); isValid &= DoubleUtil.AreClose(extentWidth, this.ScrollData.ExtentWidth); isValid &= DoubleUtil.AreClose(this.ScrollData.OffsetX, offsetX); this.ScrollData.ViewportWidth = viewportWidth; this.ScrollData.ExtentWidth = extentWidth; this.ScrollData.OffsetX = offsetX; if (!isValid) { if (this.ScrollOwner != null) { this.ScrollOwner.InvalidateScrollInfo(); } } } // Returns an offset coerced into the [0, Extent - Viewport] range. static double CoerceOffset(double offset, double extent, double viewport) { if (offset > extent - viewport) { offset = extent - viewport; } if (offset < 0) { offset = 0; } return offset; } #endregion } }
using System; using System.Drawing; using System.IO; using NUnit.Framework; using Palaso.i18n; using Palaso.IO; namespace Palaso.Tests.i18n { [TestFixture] public class StringCatalogTests { private string _poFile = Path.GetTempFileName(); [SetUp] public void Setup() { //BasilProject.InitializeForTests(); string contents = @"# SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # #, fuzzy msgid '' msgstr '' 'Project-Id-Version: PACKAGE VERSION\n' 'Report-Msgid-Bugs-To: blah balh\n' 'POT-Creation-Date: 2005-09-20 20:52+0200\n' 'PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n' 'Last-Translator: FULL NAME <EMAIL@ADDRESS>\n' 'Language-Team: LANGUAGE <LL@li.org>\n' 'MIME-Version: 1.0\n' 'Content-Type: text/plain; charset=CHARSET\n' 'Content-Transfer-Encoding: 8bit\n' #: string is empty msgid 'justid' msgstr '' #: normal msgid 'red' msgstr 'deng' msgid 'this & that' msgstr 'this or that' #: long strings msgid 'multi1' msgstr '' 'This is a long ' 'sentence.' #: long strings msgid 'multi2' msgstr 'one' 'two' 'three' #: formatted correctly msgid 'oneParam' msgstr 'first={0}' #: missing param msgid 'noParams' msgstr 'first' #: id on multiple lines msgid '' 'Semantic Domains' msgstr 'translated' "; contents = contents.Replace('\'', '"'); File.WriteAllText(_poFile, contents); } [TearDown] public void TearDown() { File.Delete(_poFile); } [Test] public void GetFormatted_FoundCorrectString_Formats() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); Assert.AreEqual("first=one", StringCatalog.GetFormatted("oneParam", "blah blah", "one")); } /* TODO we haven't implemented this detection yet [Test] public void GetFormatted_TooFewParamsInCatalog_ShowsMessageAndReturnRightMessage() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); //todo: when palaso is upgraded to the other branch, we can add something like this //using(new Palaso.Reporting.NonFatalErrorDialog()) var answer = StringCatalog.GetFormatted("noParams", "blah blah","one"); Assert.AreEqual("!!first", answer); } */ [Test] public void GetFormatted_TooManyParamsInCatalog_ShowsMessageAndReturnRightMessage() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); using(new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) { var answer = StringCatalog.GetFormatted("oneParam", "blah blah"); Assert.AreEqual("!!first={0}", answer); } } [Test] public void MultiLines_EmtpyMsgStr_Concatenated() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); Assert.AreEqual("This is a long sentence.", catalog["multi1"]); } [Test] public void LongLines_NonEmtpyMsgStr_Concatenated() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); Assert.AreEqual("onetwothree", catalog["multi2"]); } [Test] public void RequestedHasDoubleAmpersands_MatchesSingle() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); Assert.AreEqual("this or that", catalog["this && that"]); } [Test] public void NotTranslated() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); Assert.AreEqual("justid", catalog["justid"]); } [Test] public void NotListedAtAll() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); Assert.AreEqual("notinthere", catalog["notinthere"]); } [Test] public void Normal() { StringCatalog catalog = new StringCatalog(_poFile,null, 9); Assert.AreEqual("deng", catalog["red"]); } [Test] public void FontsDoNotScaleUp() { StringCatalog catalog = new StringCatalog(_poFile, "Onyx", 30); Font normal = new Font(System.Drawing.FontFamily.GenericSerif, 20); Font localized = StringCatalog.ModifyFontForLocalization(normal); Assert.AreEqual(20,Math.Floor(localized.SizeInPoints)); } [Test] public void FontsDoNotChange() { StringCatalog catalog = new StringCatalog(_poFile, FontFamily.GenericSansSerif.Name, 30); Font normal = new Font(FontFamily.GenericSerif, 20); Font localized = StringCatalog.ModifyFontForLocalization(normal); Assert.AreEqual(FontFamily.GenericSerif.Name, localized.FontFamily.Name); } [Test] public void ModifyFontForLocation_SmallFont_ValidFont() { StringCatalog catalog = new StringCatalog(_poFile, FontFamily.GenericSerif.Name, Single.Epsilon); Font normal = new Font(FontFamily.GenericSerif, Single.Epsilon); Font localized = StringCatalog.ModifyFontForLocalization(normal); Assert.IsNotNull(localized); } [Test] public void ModifyFontForLocation_HugeFont_ValidFont() { StringCatalog catalog = new StringCatalog(_poFile, FontFamily.GenericSerif.Name, Single.MaxValue); Font normal = new Font(FontFamily.GenericSerif, Single.MaxValue); Font localized = StringCatalog.ModifyFontForLocalization(normal); Assert.IsNotNull(localized); } [Test] public void Constructor_MsgIdDiffersOnlyInCase_DoesntThrow() { string poText = @" #: C:\src\sil\wesay-wip\bld\..\src\Addin.Backup\BackupDialog.cs msgid 'Backing Up...' msgstr 'aa' #: C:\src\sil\wesay-wip\bld\..\src\Addin.Transform\LameProgressDialog.Designer.cs msgid 'Backing up...' msgstr 'aa' ".Replace("'", "\""); using (var file = new TempFile(poText)) { StringCatalog catalog = new StringCatalog(file.Path, FontFamily.GenericSansSerif.Name, 12); } } [Test] public void MultiLines_EmtpyMsgId_Concatenated() { StringCatalog catalog = new StringCatalog(_poFile, null, 9); Assert.AreEqual("translated", catalog["Semantic Domains"]); } } }
// 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; namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Xml; using System.Linq; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Security; // The interface is a perf optimization. // Only KeyValuePairAdapter should implement the interface. internal interface IKeyValuePairAdapter { } //Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved [DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")] internal class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter { private K _kvpKey; private T _kvpValue; public KeyValuePairAdapter(KeyValuePair<K, T> kvPair) { _kvpKey = kvPair.Key; _kvpValue = kvPair.Value; } [DataMember(Name = "key")] public K Key { get { return _kvpKey; } set { _kvpKey = value; } } [DataMember(Name = "value")] public T Value { get { return _kvpValue; } set { _kvpValue = value; } } internal KeyValuePair<K, T> GetKeyValuePair() { return new KeyValuePair<K, T>(_kvpKey, _kvpValue); } internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair) { return new KeyValuePairAdapter<K, T>(kvPair); } } #if USE_REFEMIT public interface IKeyValue #else internal interface IKeyValue #endif { object Key { get; set; } object Value { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")] #if USE_REFEMIT public struct KeyValue<K, V> : IKeyValue #else internal struct KeyValue<K, V> : IKeyValue #endif { private K _key; private V _value; internal KeyValue(K key, V value) { _key = key; _value = value; } [DataMember(IsRequired = true)] public K Key { get { return _key; } set { _key = value; } } [DataMember(IsRequired = true)] public V Value { get { return _value; } set { _value = value; } } object IKeyValue.Key { get { return _key; } set { _key = (K)value; } } object IKeyValue.Value { get { return _value; } set { _value = (V)value; } } } #if NET_NATIVE public enum CollectionKind : byte #else internal enum CollectionKind : byte #endif { None, GenericDictionary, Dictionary, GenericList, GenericCollection, List, GenericEnumerable, Collection, Enumerable, Array, } #if USE_REFEMIT || NET_NATIVE public sealed class CollectionDataContract : DataContract #else internal sealed class CollectionDataContract : DataContract #endif { [SecurityCritical] /// <SecurityNote> /// Critical - XmlDictionaryString representing the XML element name for collection items. /// statically cached and used from IL generated code. /// </SecurityNote> private XmlDictionaryString _collectionItemName; [SecurityCritical] /// <SecurityNote> /// Critical - XmlDictionaryString representing the XML namespace for collection items. /// statically cached and used from IL generated code. /// </SecurityNote> private XmlDictionaryString _childElementNamespace; [SecurityCritical] /// <SecurityNote> /// Critical - internal DataContract representing the contract for collection items. /// statically cached and used from IL generated code. /// </SecurityNote> private DataContract _itemContract; [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> private CollectionDataContractCriticalHelper _helper; [SecuritySafeCritical] public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind)) { InitCollectionDataContract(this); } /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type)) { InitCollectionDataContract(this); } [SecuritySafeCritical] /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [SecuritySafeCritical] /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [SecuritySafeCritical] /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [SecurityCritical] /// <SecurityNote> /// Critical - initializes SecurityCritical fields; called from all constructors /// </SecurityNote> private void InitCollectionDataContract(DataContract sharedTypeContract) { _helper = base.Helper as CollectionDataContractCriticalHelper; _collectionItemName = _helper.CollectionItemName; if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary) { _itemContract = _helper.ItemContract; } _helper.SharedTypeContract = sharedTypeContract; } private static Type[] KnownInterfaces { /// <SecurityNote> /// Critical - fetches the critical knownInterfaces property /// Safe - knownInterfaces only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return CollectionDataContractCriticalHelper.KnownInterfaces; } } internal CollectionKind Kind { /// <SecurityNote> /// Critical - fetches the critical kind property /// Safe - kind only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.Kind; } } public Type ItemType { /// <SecurityNote> /// Critical - fetches the critical itemType property /// Safe - itemType only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.ItemType; } set { _helper.ItemType = value; } } public DataContract ItemContract { /// <SecurityNote> /// Critical - fetches the critical itemContract property /// Safe - itemContract only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _itemContract ?? _helper.ItemContract; } /// <SecurityNote> /// Critical - sets the critical itemContract property /// </SecurityNote> [SecurityCritical] set { _itemContract = value; _helper.ItemContract = value; } } internal DataContract SharedTypeContract { /// <SecurityNote> /// Critical - fetches the critical sharedTypeContract property /// Safe - sharedTypeContract only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.SharedTypeContract; } } public string ItemName { /// <SecurityNote> /// Critical - fetches the critical itemName property /// Safe - itemName only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.ItemName; } /// <SecurityNote> /// Critical - sets the critical itemName property /// </SecurityNote> [SecurityCritical] set { _helper.ItemName = value; } } public XmlDictionaryString CollectionItemName { /// <SecurityNote> /// Critical - fetches the critical collectionItemName property /// Safe - collectionItemName only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _collectionItemName; } set { _collectionItemName = value; } } public string KeyName { /// <SecurityNote> /// Critical - fetches the critical keyName property /// Safe - keyName only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.KeyName; } /// <SecurityNote> /// Critical - sets the critical keyName property /// </SecurityNote> [SecurityCritical] set { _helper.KeyName = value; } } public string ValueName { /// <SecurityNote> /// Critical - fetches the critical valueName property /// Safe - valueName only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.ValueName; } /// <SecurityNote> /// Critical - sets the critical valueName property /// </SecurityNote> [SecurityCritical] set { _helper.ValueName = value; } } internal bool IsDictionary { get { return KeyName != null; } } public XmlDictionaryString ChildElementNamespace { /// <SecurityNote> /// Critical - fetches the critical childElementNamespace property /// Safe - childElementNamespace only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_childElementNamespace == null) { lock (this) { if (_childElementNamespace == null) { if (_helper.ChildElementNamespace == null && !IsDictionary) { XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Interlocked.MemoryBarrier(); _helper.ChildElementNamespace = tempChildElementNamespace; } _childElementNamespace = _helper.ChildElementNamespace; } } } return _childElementNamespace; } } internal bool IsConstructorCheckRequired { /// <SecurityNote> /// Critical - fetches the critical isConstructorCheckRequired property /// Safe - isConstructorCheckRequired only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.IsConstructorCheckRequired; } /// <SecurityNote> /// Critical - sets the critical isConstructorCheckRequired property /// </SecurityNote> [SecurityCritical] set { _helper.IsConstructorCheckRequired = value; } } internal MethodInfo GetEnumeratorMethod { /// <SecurityNote> /// Critical - fetches the critical getEnumeratorMethod property /// Safe - getEnumeratorMethod only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.GetEnumeratorMethod; } } internal MethodInfo AddMethod { /// <SecurityNote> /// Critical - fetches the critical addMethod property /// Safe - addMethod only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.AddMethod; } } internal ConstructorInfo Constructor { /// <SecurityNote> /// Critical - fetches the critical constructor property /// Safe - constructor only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.Constructor; } } public override DataContractDictionary KnownDataContracts { /// <SecurityNote> /// Critical - fetches the critical knownDataContracts property /// Safe - knownDataContracts only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.KnownDataContracts; } /// <SecurityNote> /// Critical - sets the critical knownDataContracts property /// </SecurityNote> [SecurityCritical] set { _helper.KnownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage { /// <SecurityNote> /// Critical - fetches the critical invalidCollectionInSharedContractMessage property /// Safe - invalidCollectionInSharedContractMessage only needs to be protected for write /// </SecurityNote> [SecuritySafeCritical] get { return _helper.InvalidCollectionInSharedContractMessage; } } #if NET_NATIVE private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate; public XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate #else internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate #endif { /// <SecurityNote> /// Critical - fetches the critical xmlFormatWriterDelegate property /// Safe - xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { #if NET_NATIVE if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatWriterDelegate != null)) { return _xmlFormatWriterDelegate; } #endif if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatCollectionWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } set { #if NET_NATIVE _xmlFormatWriterDelegate = value; #endif } } #if NET_NATIVE private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate; public XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate #else internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate #endif { /// <SecurityNote> /// Critical - fetches the critical xmlFormatReaderDelegate property /// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { #if NET_NATIVE if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatReaderDelegate != null)) { return _xmlFormatReaderDelegate; } #endif if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { XmlFormatCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } set { #if NET_NATIVE _xmlFormatReaderDelegate = value; #endif } } #if NET_NATIVE private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate; public XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate #else internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate #endif { /// <SecurityNote> /// Critical - fetches the critical xmlFormatReaderDelegate property /// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { #if NET_NATIVE if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatGetOnlyCollectionReaderDelegate != null)) { return _xmlFormatGetOnlyCollectionReaderDelegate; } #endif if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { lock (this) { if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { if (UnderlyingType.GetTypeInfo().IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType)))); } Debug.Assert(AddMethod != null || Kind == CollectionKind.Array, "Add method cannot be null if the collection is being used as a get-only property"); XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this); Interlocked.MemoryBarrier(); _helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate; } } } return _helper.XmlFormatGetOnlyCollectionReaderDelegate; } set { #if NET_NATIVE _xmlFormatGetOnlyCollectionReaderDelegate = value; #endif } } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { _helper.IncrementCollectionCount(xmlWriter, obj, context); } internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType) { return _helper.GetEnumeratorForCollection(obj, out enumeratorReturnType); } [SecurityCritical] /// <SecurityNote> /// Critical - holds all state used for (de)serializing collections. /// since the data is cached statically, we lock down access to it. /// </SecurityNote> private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Type[] s_knownInterfaces; private Type _itemType; private CollectionKind _kind; private readonly MethodInfo _getEnumeratorMethod, _addMethod; private readonly ConstructorInfo _constructor; private DataContract _itemContract; private DataContract _sharedTypeContract; private DataContractDictionary _knownDataContracts; private bool _isKnownTypeAttributeChecked; private string _itemName; private bool _itemNameSetExplicit; private XmlDictionaryString _collectionItemName; private string _keyName; private string _valueName; private XmlDictionaryString _childElementNamespace; private string _invalidCollectionInSharedContractMessage; private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate; private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate; private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate; private bool _isConstructorCheckRequired = false; internal static Type[] KnownInterfaces { get { if (s_knownInterfaces == null) { // Listed in priority order s_knownInterfaces = new Type[] { Globals.TypeOfIDictionaryGeneric, Globals.TypeOfIDictionary, Globals.TypeOfIListGeneric, Globals.TypeOfICollectionGeneric, Globals.TypeOfIList, Globals.TypeOfIEnumerableGeneric, Globals.TypeOfICollection, Globals.TypeOfIEnumerable }; } return s_knownInterfaces; } } private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute) { _kind = kind; if (itemType != null) { _itemType = itemType; bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary); string itemName = null, keyName = null, valueName = null; if (collectionContractAttribute != null) { if (collectionContractAttribute.IsItemNameSetExplicitly) { if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType)))); itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName); _itemNameSetExplicit = true; } if (collectionContractAttribute.IsKeyNameSetExplicitly) { if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName))); keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName); } if (collectionContractAttribute.IsValueNameSetExplicitly) { if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName))); valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName); } } XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3); this.Name = dictionary.Add(this.StableName.Name); this.Namespace = dictionary.Add(this.StableName.Namespace); _itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name; _collectionItemName = dictionary.Add(_itemName); if (isDictionary) { _keyName = keyName ?? Globals.KeyLocalName; _valueName = valueName ?? Globals.ValueLocalName; } } if (collectionContractAttribute != null) { this.IsReference = collectionContractAttribute.IsReference; } } internal CollectionDataContractCriticalHelper(CollectionKind kind) : base() { Init(kind, null, null); } // array internal CollectionDataContractCriticalHelper(Type type) : base(type) { if (type == Globals.TypeOfArray) type = Globals.TypeOfObjectArray; if (type.GetArrayRank() > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SupportForMultidimensionalArraysNotPresent))); this.StableName = DataContract.GetStableName(type); Init(CollectionKind.Array, type.GetElementType(), null); } // collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type)))); if (addMethod == null && !type.GetTypeInfo().IsInterface) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type)))); if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type)))); CollectionDataContractAttribute collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); _getEnumeratorMethod = getEnumeratorMethod; _addMethod = addMethod; _constructor = constructor; } // collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor) { _isConstructorCheckRequired = isConstructorCheckRequired; } internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type) { Init(CollectionKind.Collection, null /*itemType*/, null); _invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage; } internal CollectionKind Kind { get { return _kind; } } internal Type ItemType { get { return _itemType; } set { _itemType = value; } } internal DataContract ItemContract { get { if (_itemContract == null && UnderlyingType != null) { if (IsDictionary) { if (String.CompareOrdinal(KeyName, ValueName) == 0) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName), UnderlyingType); } _itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName }); // Ensure that DataContract gets added to the static DataContract cache for dictionary items DataContract.GetDataContract(ItemType); } else { _itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType); if (_itemContract == null) { _itemContract = DataContract.GetDataContract(ItemType); } } } return _itemContract; } set { _itemContract = value; } } internal DataContract SharedTypeContract { get { return _sharedTypeContract; } set { _sharedTypeContract = value; } } internal string ItemName { get { return _itemName; } set { _itemName = value; } } internal bool IsConstructorCheckRequired { get { return _isConstructorCheckRequired; } set { _isConstructorCheckRequired = value; } } public XmlDictionaryString CollectionItemName { get { return _collectionItemName; } } internal string KeyName { get { return _keyName; } set { _keyName = value; } } internal string ValueName { get { return _valueName; } set { _valueName = value; } } internal bool IsDictionary { get { return KeyName != null; } } public XmlDictionaryString ChildElementNamespace { get { return _childElementNamespace; } set { _childElementNamespace = value; } } internal MethodInfo GetEnumeratorMethod { get { return _getEnumeratorMethod; } } internal MethodInfo AddMethod { get { return _addMethod; } } internal ConstructorInfo Constructor { get { return _constructor; } } internal override DataContractDictionary KnownDataContracts { [SecurityCritical] get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } [SecurityCritical] set { _knownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage { get { return _invalidCollectionInSharedContractMessage; } } internal bool ItemNameSetExplicit { get { return _itemNameSetExplicit; } } internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { get { return _xmlFormatGetOnlyCollectionReaderDelegate; } set { _xmlFormatGetOnlyCollectionReaderDelegate = value; } } private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context); private IncrementCollectionCountDelegate _incrementCollectionCountDelegate = null; private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_incrementCollectionCountDelegate == null) { switch (Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: { _incrementCollectionCountDelegate = (x, o, c) => { context.IncrementCollectionCount(x, (ICollection)o); }; } break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: { var buildIncrementCollectionCountDelegate = s_buildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>()); } break; case CollectionKind.GenericDictionary: { var buildIncrementCollectionCountDelegate = s_buildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments())); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>()); } break; default: // Do nothing. _incrementCollectionCountDelegate = DummyIncrementCollectionCount; break; } } _incrementCollectionCountDelegate(xmlWriter, obj, context); } private static MethodInfo s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers); private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>() { return (xmlwriter, obj, context) => { context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj); }; } private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator); private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate; internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType) { IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator(); if (Kind == CollectionKind.GenericDictionary) { if (_createGenericDictionaryEnumeratorDelegate == null) { var keyValueTypes = ItemType.GetGenericArguments(); var buildCreateGenericDictionaryEnumerator = s_buildCreateGenericDictionaryEnumerator.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]); _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>()); } enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator); } else if (Kind == CollectionKind.Dictionary) { enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator()); } enumeratorReturnType = EnumeratorReturnType; return enumerator; } private Type _enumeratorReturnType; public Type EnumeratorReturnType { get { _enumeratorReturnType = _enumeratorReturnType ?? GetCollectionEnumeratorReturnType(); return _enumeratorReturnType; } } private Type GetCollectionEnumeratorReturnType() { Type enumeratorReturnType; if (Kind == CollectionKind.GenericDictionary) { var keyValueTypes = ItemType.GetGenericArguments(); enumeratorReturnType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes); } else if (Kind == CollectionKind.Dictionary) { enumeratorReturnType = Globals.TypeOfObject; } else if (Kind == CollectionKind.GenericCollection || Kind == CollectionKind.GenericList) { enumeratorReturnType = ItemType; } else { var enumeratorType = GetEnumeratorMethod.ReturnType; if (enumeratorType.GetTypeInfo().IsGenericType) { MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); enumeratorReturnType = getCurrentMethod.ReturnType; } else { enumeratorReturnType = Globals.TypeOfObject; } } return enumeratorReturnType; } private static MethodInfo s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers); private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>() { return (enumerator) => { return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator); }; } } private DataContract GetSharedTypeContract(Type type) { if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { return this; } if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false)) { return new ClassDataContract(type); } return null; } internal static bool IsCollectionInterface(Type type) { if (type.GetTypeInfo().IsGenericType) type = type.GetGenericTypeDefinition(); return ((IList<Type>)KnownInterfaces).Contains(type); } internal static bool IsCollection(Type type) { Type itemType; return IsCollection(type, out itemType); } internal static bool IsCollection(Type type, out Type itemType) { return IsCollectionHelper(type, out itemType, true /*constructorRequired*/); } internal static bool IsCollection(Type type, bool constructorRequired) { Type itemType; return IsCollectionHelper(type, out itemType, constructorRequired); } private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired) { if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) { itemType = type.GetElementType(); return true; } DataContract dataContract; return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired); } internal static bool TryCreate(Type type, out DataContract dataContract) { Type itemType; return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/); } internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) { Type itemType; if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/); } } internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) { dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) { Type itemType; if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/); } } else { if (dataContract is CollectionDataContract) { return true; } else { dataContract = null; return false; } } } internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType) { Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); if (t == null) return null; return t.GetMethod(name); } private static bool IsArraySegment(Type t) { return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired) { dataContract = null; itemType = Globals.TypeOfObject; if (DataContract.GetBuiltInDataContract(type) != null) { return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/, SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract); } MethodInfo addMethod, getEnumeratorMethod; bool hasCollectionDataContract = IsCollectionDataContract(type); Type baseType = type.GetTypeInfo().BaseType; bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false; if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection, SR.CollectionTypeCannotHaveDataContract, null, ref dataContract); } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type)) { return false; } if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (type.GetTypeInfo().IsInterface) { Type interfaceTypeToCheck = type.GetTypeInfo().IsGenericType ? type.GetGenericTypeDefinition() : type; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { addMethod = null; if (type.GetTypeInfo().IsGenericType) { Type[] genericArgs = type.GetGenericArguments(); if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric) { itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs); addMethod = type.GetMethod(Globals.AddMethodName); getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName); } else { itemType = genericArgs[0]; // ICollection<T> has AddMethod var collectionType = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType); if (collectionType.IsAssignableFrom(type)) { addMethod = collectionType.GetMethod(Globals.AddMethodName); } getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName); } } else { if (interfaceTypeToCheck == Globals.TypeOfIDictionary) { itemType = typeof(KeyValue<object, object>); addMethod = type.GetMethod(Globals.AddMethodName); } else { itemType = Globals.TypeOfObject; // IList has AddMethod if (interfaceTypeToCheck == Globals.TypeOfIList) { addMethod = type.GetMethod(Globals.AddMethodName); } } getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName); } if (tryCreate) dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/); return true; } } } ConstructorInfo defaultCtor = null; if (!type.GetTypeInfo().IsValueType) { defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>()); if (defaultCtor == null && constructorRequired) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/, SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract); } } Type knownInterfaceType = null; CollectionKind kind = CollectionKind.None; bool multipleDefinitions = false; Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { Type interfaceTypeToCheck = interfaceType.GetTypeInfo().IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { CollectionKind currentKind = (CollectionKind)(i + 1); if (kind == CollectionKind.None || currentKind < kind) { kind = currentKind; knownInterfaceType = interfaceType; multipleDefinitions = false; } else if ((kind & currentKind) == currentKind) multipleDefinitions = true; break; } } } if (kind == CollectionKind.None) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable) { if (multipleDefinitions) knownInterfaceType = Globals.TypeOfIEnumerable; itemType = knownInterfaceType.GetTypeInfo().IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject; GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType }, false /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); if (addMethod == null) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract); } if (tryCreate) dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } else { if (multipleDefinitions) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/, SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract); } Type[] addMethodTypeArray = null; switch (kind) { case CollectionKind.GenericDictionary: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); bool isOpenGeneric = knownInterfaceType.GetTypeInfo().IsGenericTypeDefinition || (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter); itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.Dictionary: addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); itemType = addMethodTypeArray[0]; break; case CollectionKind.List: itemType = Globals.TypeOfObject; addMethodTypeArray = new Type[] { itemType }; break; } if (tryCreate) { GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray, true /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) { dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } } return true; } internal static bool IsCollectionDataContract(Type type) { return type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false); } private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract) { if (hasCollectionDataContract) { if (tryCreate) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param))); return true; } if (createContractWithException) { if (tryCreate) dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param)); return true; } return false; } private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param) { return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param); } private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod) { Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); if (t != null) { addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod; getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod; } } private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod) { addMethod = getEnumeratorMethod = null; if (addMethodOnInterface) { addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray); if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) { FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { Type[] parentInterfaceTypes = interfaceType.GetInterfaces(); foreach (Type parentInterfaceType in parentInterfaceTypes) { if (IsKnownInterface(parentInterfaceType)) { FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { break; } } } } } } else { // GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray); if (addMethod == null) return; } if (getEnumeratorMethod == null) { getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); if (ienumerableInterface == null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); } } } private static bool IsKnownInterface(Type type) { Type typeToCheck = type.GetTypeInfo().IsGenericType ? type.GetGenericTypeDefinition() : type; foreach (Type knownInterfaceType in KnownInterfaces) { if (typeToCheck == knownInterfaceType) { return true; } } return false; } internal override DataContract GetValidContract(SerializationMode mode) { if (InvalidCollectionInSharedContractMessage != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage)); return this; } internal override DataContract GetValidContract() { if (this.IsConstructorCheckRequired) { CheckConstructor(); } return this; } /// <SecurityNote> /// Critical - sets the critical IsConstructorCheckRequired property on CollectionDataContract /// </SecurityNote> [SecuritySafeCritical] private void CheckConstructor() { if (this.Constructor == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType)))); } else { this.IsConstructorCheckRequired = false; } } internal override bool IsValidContract(SerializationMode mode) { return (InvalidCollectionInSharedContractMessage == null); } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(Constructor)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.AddMethod)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractAddMethodNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.AddMethod.Name), securityException)); } return true; } return false; } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } return false; } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { xmlReader.Read(); object o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; #if NET_NATIVE if (XmlFormatGetOnlyCollectionReaderDelegate == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType.ToString())); } #endif XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } else { o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } xmlReader.ReadEndElement(); return o; } internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>> { private IDictionaryEnumerator _enumerator; public DictionaryEnumerator(IDictionaryEnumerator enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<object, object> Current { get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } internal class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>> { private IEnumerator<KeyValuePair<K, V>> _enumerator; public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<K, V> Current { get { KeyValuePair<K, V> current = _enumerator.Current; return new KeyValue<K, V>(current.Key, current.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } } }
// // System.Web.UI.WebControls.RadioButtonList.cs // // Authors: // Gaurav Vaish (gvaish@iitk.ac.in) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // // (C) Gaurav Vaish (2002) // (C) 2003 Andreas Nahr // // // 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.Specialized; using System.ComponentModel; using System.Globalization; using System.Web; using System.Web.UI; namespace System.Web.UI.WebControls { [ValidationProperty("SelectedItem")] public class RadioButtonList : ListControl, IRepeatInfoUser, INamingContainer, IPostBackDataHandler { private bool selectionIndexChanged; private short tabIndex; public RadioButtonList(): base() { selectionIndexChanged = false; } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (-1), WebCategory ("Layout")] [WebSysDescription ("The border left within a RadioButton.")] public virtual int CellPadding { get { if(ControlStyleCreated) { return (int)(((TableStyle)ControlStyle).CellPadding); } return -1; } set { if (value < -1) throw new ArgumentOutOfRangeException ("value", "CellPadding value has to be -1 for 'not set' or > -1."); ((TableStyle)ControlStyle).CellPadding = value; } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (-1), WebCategory ("Layout")] [WebSysDescription ("The border left between RadioButtons.")] public virtual int CellSpacing { get { if(ControlStyleCreated) { return (int)(((TableStyle)ControlStyle).CellSpacing); } return -1; } set { if (value < -1) throw new ArgumentOutOfRangeException ("value", "CellSpacing value has to be -1 for 'not set' or > -1."); ((TableStyle)ControlStyle).CellSpacing = value; } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (0), WebCategory ("Layout")] [WebSysDescription ("The number of columns that should be used to display the RadioButtons.")] public virtual int RepeatColumns { get { object o = ViewState["RepeatColumns"]; if(o != null) return (int)o; return 0; } set { if (value < 0) throw new ArgumentOutOfRangeException ("value", "RepeatColumns value has to be 0 for 'not set' or > 0."); ViewState["RepeatColumns"] = value; } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (typeof (RepeatDirection), "Vertical"), WebCategory ("Layout")] [WebSysDescription ("The direction that is followed when doing the layout.")] public virtual RepeatDirection RepeatDirection { get { object o = ViewState["RepeatDirection"]; if(o != null) return (RepeatDirection)o; return RepeatDirection.Vertical; } set { if(!Enum.IsDefined(typeof(RepeatDirection), value)) throw new ArgumentOutOfRangeException ("value", "Only valid enumeration members are allowed"); ViewState["RepeatDirection"] = value; } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (typeof (RepeatLayout), "Table"), WebCategory ("Layout")] [WebSysDescription ("The method used to create the layout.")] public virtual RepeatLayout RepeatLayout { get { object o = ViewState["RepeatLayout"]; if(o != null) return (RepeatLayout)o; return RepeatLayout.Table; } set { if(!Enum.IsDefined(typeof(RepeatLayout), value)) throw new ArgumentOutOfRangeException ("value", "Only valid enumeration members are allowed"); ViewState["RepeatLayout"] = value; } } #if !NET_2_0 [Bindable (true)] #endif [DefaultValue (typeof (TextAlign), "Right"), WebCategory ("Appearance")] [WebSysDescription ("The alignment of the RadioButton text.")] public virtual TextAlign TextAlign { get { object o = ViewState["TextAlign"]; if(o != null) return (TextAlign)o; return TextAlign.Right; } set { if(!Enum.IsDefined(typeof(TextAlign), value)) throw new ArgumentOutOfRangeException ("value", "Only valid enumeration members are allowed"); ViewState["TextAlign"] = value; } } protected override Style CreateControlStyle() { return new TableStyle(ViewState); } protected override void Render(HtmlTextWriter writer) { RepeatInfo info = new RepeatInfo(); Style cStyle = (ControlStyleCreated ? ControlStyle : null); bool dirty = false; tabIndex = TabIndex; if(tabIndex != 0) { dirty = !ViewState.IsItemDirty("TabIndex"); TabIndex = 0; } info.RepeatColumns = RepeatColumns; info.RepeatDirection = RepeatDirection; info.RepeatLayout = RepeatLayout; info.RenderRepeater(writer, this, cStyle, this); if(tabIndex != 0) { TabIndex = tabIndex; } if(dirty) { ViewState.SetItemDirty("TabIndex", false); } } #if NET_2_0 bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) { return LoadPostData (postDataKey, postCollection); } protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) #else bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) #endif { string value = postCollection [postDataKey]; int c = Items.Count; for (int i = 0; i < c; i++) { if (Items [i].Value != value) continue; if (i != SelectedIndex) { SelectedIndex = i; selectionIndexChanged = true; } return true; } return false; } #if NET_2_0 void IPostBackDataHandler.RaisePostDataChangedEvent () { RaisePostDataChangedEvent (); } protected virtual void RaisePostDataChangedEvent () { if (CausesValidation) Page.Validate (ValidationGroup); if(selectionIndexChanged) OnSelectedIndexChanged(EventArgs.Empty); } #else void IPostBackDataHandler.RaisePostDataChangedEvent () { if(selectionIndexChanged) OnSelectedIndexChanged(EventArgs.Empty); } #endif #if NET_2_0 Style IRepeatInfoUser.GetItemStyle(System.Web.UI.WebControls.ListItemType itemType, int repeatIndex) { return GetItemStyle (itemType, repeatIndex); } protected virtual Style GetItemStyle(System.Web.UI.WebControls.ListItemType itemType, int repeatIndex) { return null; } #else Style IRepeatInfoUser.GetItemStyle(System.Web.UI.WebControls.ListItemType itemType, int repeatIndex) { return null; } #endif #if NET_2_0 void IRepeatInfoUser.RenderItem (System.Web.UI.WebControls.ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer) { RenderItem (itemType, repeatIndex, repeatInfo, writer); } protected virtual void RenderItem (System.Web.UI.WebControls.ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer) #else void IRepeatInfoUser.RenderItem (System.Web.UI.WebControls.ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer) #endif { /* Create a new RadioButton as if it was defined in the page and render it */ RadioButton button = new RadioButton (); button.Page = Page; button.GroupName = UniqueID; button.TextAlign = TextAlign; button.AutoPostBack = AutoPostBack; button.ID = ClientID + "_" + repeatIndex.ToString (NumberFormatInfo.InvariantInfo);; button.TabIndex = tabIndex; ListItem current = Items [repeatIndex]; button.Text = current.Text; button.Attributes ["value"] = current.Value; button.Checked = current.Selected; button.Enabled = Enabled; button.RenderControl (writer); } #if NET_2_0 bool IRepeatInfoUser.HasFooter { get { return HasFooter; } } protected virtual bool HasFooter { get { return false; } } #else bool IRepeatInfoUser.HasFooter { get { return false; } } #endif #if NET_2_0 bool IRepeatInfoUser.HasHeader { get { return HasHeader; } } protected virtual bool HasHeader { get { return false; } } #else bool IRepeatInfoUser.HasHeader { get { return false; } } #endif #if NET_2_0 bool IRepeatInfoUser.HasSeparators { get { return HasSeparators; } } protected virtual bool HasSeparators { get { return false; } } #else bool IRepeatInfoUser.HasSeparators { get { return false; } } #endif #if NET_2_0 int IRepeatInfoUser.RepeatedItemCount { get { return RepeatedItemCount; } } protected virtual int RepeatedItemCount { get { return Items.Count; } } #else int IRepeatInfoUser.RepeatedItemCount { get { return Items.Count; } } #endif } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Globalization; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) using System.Numerics; #endif using Medivh.Json.Serialization; using Medivh.Json.Utilities; #if NET20 using Medivh.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Medivh.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the reader is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the reader is closed; otherwise false. The default is true. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple pieces of JSON content can /// be read from a continuous stream without erroring. /// </summary> /// <value> /// true to support reading multiple pieces of JSON content; otherwise false. The default is false. /// </value> public bool SupportMultipleContent { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || #if !NET20 value > DateParseHandling.DateTimeOffset #else value > DateParseHandling.DateTime #endif ) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException(nameof(value)); } _floatParseHandling = value; } } /// <summary> /// Get or set how custom date formatted strings are parsed when reading JSON. /// </summary> public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", nameof(value)); } _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType { get { return _tokenType; } } /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current JSON token. /// </summary> public virtual Type ValueType { get { return (_value != null) ? _value.GetType() : null; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = (_stack != null) ? _stack.Count : 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return depth; } else { return depth + 1; } } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; return JsonPosition.BuildPath(_stack, current); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack != null && _stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual int? ReadAsInt32() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is int)) { SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); } return (int)Value; case JsonToken.String: string s = (string)Value; return ReadInt32String(s); } throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadInt32String(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } int i; if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) { SetToken(JsonToken.Integer, i, false); return i; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual string ReadAsString() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; } if (JsonTokenUtils.IsPrimitiveToken(t)) { if (Value != null) { string s; if (Value is IFormattable) { s = ((IFormattable)Value).ToString(null, Culture); } else if (Value is Uri) { s = ((Uri)Value).OriginalString; } else { s = Value.ToString(); } SetToken(JsonToken.String, s, false); return s; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Byte"/>[]. /// </summary> /// <returns>A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public virtual byte[] ReadAsBytes() { JsonToken t = GetContentToken(); if (t == JsonToken.None) { return null; } if (TokenType == JsonToken.StartObject) { ReadIntoWrappedTypeObject(); byte[] data = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, data, false); return data; } switch (t) { case JsonToken.String: { // attempt to convert possible base 64 or GUID string to bytes // GUID has to have format 00000000-0000-0000-0000-000000000000 string s = (string)Value; byte[] data; Guid g; if (s.Length == 0) { data = new byte[0]; } else if (ConvertUtils.TryConvertGuid(s, out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return data; } case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (ValueType == typeof(Guid)) { byte[] data = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, data, false); return data; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal byte[] ReadArrayIntoByteArray() { List<byte> buffer = new List<byte>(); while (true) { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = buffer.ToArray(); SetToken(JsonToken.Bytes, d, false); return d; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual double? ReadAsDouble() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is double)) { SetToken(JsonToken.Float, Convert.ToDouble(Value, CultureInfo.InvariantCulture), false); } return (double) Value; case JsonToken.String: return ReadDoubleString((string) Value); } throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal double? ReadDoubleString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } double d; if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Boolean}"/>. /// </summary> /// <returns>A <see cref="Nullable{Boolean}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual bool? ReadAsBoolean() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: bool b; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (Value is BigInteger) { b = (BigInteger)Value != 0; } else #endif { b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); } SetToken(JsonToken.Boolean, b, false); return b; case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; } throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal bool? ReadBooleanString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } bool b; if (bool.TryParse(s, out b)) { SetToken(JsonToken.Boolean, b, false); return b; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual decimal? ReadAsDecimal() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is decimal)) { SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); } return (decimal)Value; case JsonToken.String: return ReadDecimalString((string)Value); } throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadDecimalString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } decimal d; if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTime}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: #if !NET20 if (Value is DateTimeOffset) { SetToken(JsonToken.Date, ((DateTimeOffset)Value).DateTime, false); } #endif return (DateTime)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeString(s); } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal DateTime? ReadDateTimeString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } DateTime dt; if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime) { SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); } return (DateTimeOffset)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeOffsetString(s); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } DateTimeOffset dt; if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #endif internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.TypePropertyName) { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: SetPostValueState(updateIndex); break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); } if (Peek() != JsonContainerType.None) { _currentState = State.PostValue; } else { SetFinished(); } } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } private void SetFinished() { if (SupportMultipleContent) { _currentState = State.Start; } else { _currentState = State.Finished; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadAndMoveToContent() { return Read() && MoveToContent(); } internal bool MoveToContent() { JsonToken t = TokenType; while (t == JsonToken.None || t == JsonToken.Comment) { if (!Read()) { return false; } t = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken t; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } else { t = TokenType; } } while (t == JsonToken.Comment); return t; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Microsoft.Build.Collections; using System; using Microsoft.Build.Evaluation; using Microsoft.Build.UnitTests; using Microsoft.Build.Framework; using System.Collections; using Microsoft.Build.Execution; using Microsoft.Build.Exceptions; using Microsoft.Build.Shared; using Microsoft.Build.Construction; using Microsoft.Build.UnitTests.BackEnd; using System.Xml; using System.IO; using System.Reflection; using Xunit; using System.Text; namespace Microsoft.Build.UnitTests.Construction { /// <summary> /// Tests for the ElementLocation class /// </summary> public class ElementLocation_Tests { /// <summary> /// Path to the common targets /// </summary> private string _pathToCommonTargets = #if FEATURE_INSTALLED_MSBUILD Path.Combine(FrameworkLocationHelper.PathToDotNetFrameworkV45, "Microsoft.Common.targets"); #else Path.Combine(AppContext.BaseDirectory, "Microsoft.Common.targets"); #endif /// <summary> /// Tests constructor specifying only file. /// </summary> [Fact] public void ConstructorTest1() { IElementLocation location = ElementLocation.Create("file", 65536, 0); Assert.Equal("file", location.File); Assert.Equal(65536, location.Line); Assert.Equal(0, location.Column); Assert.Contains("RegularElementLocation", location.GetType().FullName); } /// <summary> /// Tests constructor specifying only file. /// </summary> [Fact] public void ConstructorTest2() { IElementLocation location = ElementLocation.Create("file", 0, 65536); Assert.Equal("file", location.File); Assert.Equal(0, location.Line); Assert.Equal(65536, location.Column); Assert.Contains("RegularElementLocation", location.GetType().FullName); } /// <summary> /// Tests constructor specifying only file. /// </summary> [Fact] public void ConstructorTest3() { IElementLocation location = ElementLocation.Create("file", 65536, 65537); Assert.Equal("file", location.File); Assert.Equal(65536, location.Line); Assert.Equal(65537, location.Column); Assert.Contains("RegularElementLocation", location.GetType().FullName); } /// <summary> /// Test equality /// </summary> [Fact] public void Equality() { IElementLocation location1 = ElementLocation.Create("file", 65536, 65537); IElementLocation location2 = ElementLocation.Create("file", 0, 1); IElementLocation location3 = ElementLocation.Create("file", 0, 65537); IElementLocation location4 = ElementLocation.Create("file", 65536, 1); IElementLocation location5 = ElementLocation.Create("file", 0, 1); IElementLocation location6 = ElementLocation.Create("file", 65536, 65537); Assert.True(location1.Equals(location6)); Assert.True(location2.Equals(location5)); Assert.False(location3.Equals(location1)); Assert.False(location4.Equals(location2)); Assert.False(location4.Equals(location6)); } /// <summary> /// Check it will use large element location when it should. /// Using file as BIZARRELY XmlTextReader+StringReader crops or trims. /// </summary> [Fact] public void TestLargeElementLocationUsedLargeColumn() { string file = null; try { file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); File.WriteAllText(file, ObjectModelHelpers.CleanupFileContents("<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>\r\n<ItemGroup>") + new string(' ', 70000) + @"<x/></ItemGroup></Project>"); ProjectRootElement.Open(file); } catch (InvalidProjectFileException ex) { Assert.Equal(70012, ex.ColumnNumber); Assert.Equal(2, ex.LineNumber); } finally { File.Delete(file); } } /// <summary> /// Check it will use large element location when it should. /// Using file as BIZARRELY XmlTextReader+StringReader crops or trims. /// </summary> [Fact] public void TestLargeElementLocationUsedLargeLine() { string file = null; try { string longstring = String.Empty; for (int i = 0; i < 7000; i++) { longstring += "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"; } file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); File.WriteAllText(file, ObjectModelHelpers.CleanupFileContents("<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>\r\n<ItemGroup>") + longstring + @" <x/></ItemGroup></Project>"); ProjectRootElement.Open(file); } catch (InvalidProjectFileException ex) { Assert.Equal(70002, ex.LineNumber); Assert.Equal(2, ex.ColumnNumber); } finally { File.Delete(file); } } /// <summary> /// Tests serialization. /// </summary> [Fact] public void SerializationTest() { IElementLocation location = ElementLocation.Create("file", 65536, 65537); TranslationHelpers.GetWriteTranslator().Translate(ref location, ElementLocation.FactoryForDeserialization); IElementLocation deserializedLocation = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedLocation, ElementLocation.FactoryForDeserialization); Assert.Equal(location.File, deserializedLocation.File); Assert.Equal(location.Line, deserializedLocation.Line); Assert.Equal(location.Column, deserializedLocation.Column); Assert.Contains("RegularElementLocation", location.GetType().FullName); } /// <summary> /// Tests serialization of empty location. /// </summary> [Fact] public void SerializationTestForEmptyLocation() { IElementLocation location = ElementLocation.EmptyLocation; TranslationHelpers.GetWriteTranslator().Translate(ref location, ElementLocation.FactoryForDeserialization); IElementLocation deserializedLocation = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedLocation, ElementLocation.FactoryForDeserialization); Assert.Equal(location.File, deserializedLocation.File); Assert.Equal(location.Line, deserializedLocation.Line); Assert.Equal(location.Column, deserializedLocation.Column); Assert.Contains("SmallElementLocation", deserializedLocation.GetType().FullName); } /// <summary> /// Tests constructor specifying file, line and column. /// </summary> [Fact] public void ConstructorWithIndicesTest_SmallElementLocation() { IElementLocation location = ElementLocation.Create("file", 65535, 65534); Assert.Equal("file", location.File); Assert.Equal(65535, location.Line); Assert.Equal(65534, location.Column); Assert.Contains("SmallElementLocation", location.GetType().FullName); } /// <summary> /// Tests constructor specifying file, negative line, column /// </summary> [Fact] public void ConstructorWithNegativeIndicesTest1() { Assert.Throws<InternalErrorException>(() => { ElementLocation.Create("file", -1, 2); } ); } /// <summary> /// Tests constructor specifying file, line, negative column /// </summary> [Fact] public void ConstructorWithNegativeIndicesTest2n() { Assert.Throws<InternalErrorException>(() => { ElementLocation.Create("file", 1, -2); } ); } /// <summary> /// Tests constructor with invalid null file. /// </summary> [Fact] public void ConstructorTestNullFile() { IElementLocation location = ElementLocation.Create(null); Assert.Equal(location.File, String.Empty); } /// <summary> /// Tests constructor specifying only file. /// </summary> [Fact] public void ConstructorTest1_SmallElementLocation() { IElementLocation location = ElementLocation.Create("file", 65535, 0); Assert.Equal("file", location.File); Assert.Equal(65535, location.Line); Assert.Equal(0, location.Column); Assert.Contains("SmallElementLocation", location.GetType().FullName); } /// <summary> /// Tests constructor specifying only file. /// </summary> [Fact] public void ConstructorTest2_SmallElementLocation() { IElementLocation location = ElementLocation.Create("file", 0, 65535); Assert.Equal("file", location.File); Assert.Equal(0, location.Line); Assert.Equal(65535, location.Column); Assert.Contains("SmallElementLocation", location.GetType().FullName); } /// <summary> /// Tests constructor specifying only file. /// </summary> [Fact] public void ConstructorTest3_SmallElementLocation() { IElementLocation location = ElementLocation.Create("file", 65535, 65534); Assert.Equal("file", location.File); Assert.Equal(65535, location.Line); Assert.Equal(65534, location.Column); Assert.Contains("SmallElementLocation", location.GetType().FullName); } /// <summary> /// Tests serialization. /// </summary> [Fact] public void SerializationTest_SmallElementLocation() { IElementLocation location = ElementLocation.Create("file", 65535, 2); TranslationHelpers.GetWriteTranslator().Translate(ref location, ElementLocation.FactoryForDeserialization); IElementLocation deserializedLocation = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedLocation, ElementLocation.FactoryForDeserialization); Assert.Equal(location.File, deserializedLocation.File); Assert.Equal(location.Line, deserializedLocation.Line); Assert.Equal(location.Column, deserializedLocation.Column); Assert.Contains("SmallElementLocation", location.GetType().FullName); } /// <summary> /// Test many of the getters /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void LocationStringsMedleyReadOnlyLoad() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <UsingTask TaskName='t' AssemblyName='a' Condition='true'/> <UsingTask TaskName='t' AssemblyFile='a' Condition='true'/> <ItemDefinitionGroup Condition='true' Label='l'> <m Condition='true'> foo bar </m> </ItemDefinitionGroup> <ItemGroup> <i Include='i' Condition='true' Exclude='r'> <m Condition='true'/> </i> </ItemGroup> <PropertyGroup> <p Condition='true'/> </PropertyGroup> <!-- A comment --> <Target Name='Build' Condition='true' Inputs='i' Outputs='o'> <ItemGroup> <i Include='i' Condition='true' Exclude='r'> <m Condition='true'/> </i> <i Remove='r'/> </ItemGroup> <PropertyGroup xml:space= 'preserve'> <x/> <p Condition='true'/> </PropertyGroup> <Error Text='xyz' ContinueOnError='true' Importance='high'/> </Target> <Import Project='p' Condition='false'/> </Project> "); string readWriteLoadLocations = GetLocations(content, readOnly: false); string readOnlyLoadLocations = GetLocations(content, readOnly: true); Console.WriteLine(readWriteLoadLocations); Helpers.VerifyAssertLineByLine(readWriteLoadLocations, readOnlyLoadLocations); } // Without save to file, this becomes identical to SaveReadOnly4 #if FEATURE_XML_LOADPATH /// <summary> /// Save read only fails /// </summary> [Fact] public void SaveReadOnly1() { Assert.Throws<InvalidOperationException>(() => { var doc = new XmlDocumentWithLocation(loadAsReadOnly: true); doc.Load(_pathToCommonTargets); Assert.True(doc.IsReadOnly); doc.Save(FileUtilities.GetTemporaryFile()); } ); } #endif /// <summary> /// Save read only fails /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void SaveReadOnly2() { var doc = new XmlDocumentWithLocation(loadAsReadOnly: true); #if FEATURE_XML_LOADPATH doc.Load(_pathToCommonTargets); #else using ( XmlReader xmlReader = XmlReader.Create( _pathToCommonTargets, new XmlReaderSettings {DtdProcessing = DtdProcessing.Ignore})) { doc.Load(xmlReader); } #endif Assert.True(doc.IsReadOnly); Assert.Throws<InvalidOperationException>(() => { doc.Save(new MemoryStream()); }); } /// <summary> /// Save read only fails /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void SaveReadOnly3() { var doc = new XmlDocumentWithLocation(loadAsReadOnly: true); #if FEATURE_XML_LOADPATH doc.Load(_pathToCommonTargets); #else using ( XmlReader xmlReader = XmlReader.Create( _pathToCommonTargets, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { doc.Load(xmlReader); } #endif Assert.True(doc.IsReadOnly); Assert.Throws<InvalidOperationException>(() => { doc.Save(new StringWriter()); }); } /// <summary> /// Save read only fails /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] public void SaveReadOnly4() { var doc = new XmlDocumentWithLocation(loadAsReadOnly: true); #if FEATURE_XML_LOADPATH doc.Load(_pathToCommonTargets); #else using ( XmlReader xmlReader = XmlReader.Create( _pathToCommonTargets, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { doc.Load(xmlReader); } #endif Assert.True(doc.IsReadOnly); using (XmlWriter wr = XmlWriter.Create(new FileStream(FileUtilities.GetTemporaryFile(), FileMode.Create))) { Assert.Throws<InvalidOperationException>(() => { doc.Save(wr); }); } } /// <summary> /// Get location strings for the content, loading as readonly if specified /// </summary> private string GetLocations(string content, bool readOnly) { string file = null; try { file = FileUtilities.GetTemporaryFile(); File.WriteAllText(file, content); var doc = new XmlDocumentWithLocation(loadAsReadOnly: readOnly); #if FEATURE_XML_LOADPATH doc.Load(file); #else using ( XmlReader xmlReader = XmlReader.Create( file, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore })) { doc.Load(xmlReader); } #endif Assert.Equal(readOnly, doc.IsReadOnly); var allNodes = doc.SelectNodes("//*|//@*"); string locations = String.Empty; foreach (var node in allNodes) { foreach (var property in node.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { if (property.Name.Equals("Location")) { var value = ((ElementLocation)property.GetValue(node, null)); if (value != null) // null means attribute is not present { locations += ((XmlNode)node).Name + "==" + ((XmlNode)node).Value ?? String.Empty + ": " + value.LocationString + "\r\n"; } } } } locations = locations.Replace(file, "c:\\foo\\bar.csproj"); return locations; } finally { File.Delete(file); } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXNSPI { using System; using System.Collections.Generic; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// This define the base class for a property value node /// </summary> public class PropertyValue : Node { /// <summary> /// Property's value /// </summary> private byte[] value; /// <summary> /// Indicates whether the property's value is an unfixed size or not. /// </summary> private bool isVariableSize = false; /// <summary> /// Gets or sets property's value /// </summary> public byte[] Value { get { return this.value; } set { this.value = value; } } /// <summary> /// Serialize the ROP request buffer. /// </summary> /// <returns>The ROP request buffer serialized.</returns> public virtual byte[] Serialize() { int length = this.Size(); byte[] resultBytes = new byte[length]; if (this.isVariableSize) { // Fill 2 bytes with length resultBytes[0] = (byte)((ushort)this.value.Length & 0x00FF); resultBytes[1] = (byte)(((ushort)this.value.Length & 0xFF00) >> 8); } Array.Copy(this.value, 0, resultBytes, this.isVariableSize == false ? 0 : 2, this.value.Length); return resultBytes; } /// <summary> /// Return the size of this structure. /// </summary> /// <returns>The size of this structure.</returns> public virtual int Size() { return this.isVariableSize == false ? this.value.Length : this.value.Length + 2; } /// <summary> /// Parse bytes in context into a PropertyValueNode /// </summary> /// <param name="context">The value of Context</param> public override void Parse(Context context) { // Current processing property's Type PropertyType type = context.CurProperty.Type; int strBytesLen = 0; bool isFound = false; switch (type) { // 1 Byte case PropertyType.PtypBoolean: if (context.AvailBytes() < sizeof(byte)) { throw new ParseException("Not well formed PtypIBoolean"); } else { this.value = new byte[sizeof(byte)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(byte)); context.CurIndex += sizeof(byte); } break; case PropertyType.PtypInteger16: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypInteger16"); } else { this.value = new byte[sizeof(short)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); } break; case PropertyType.PtypInteger32: case PropertyType.PtypFloating32: case PropertyType.PtypErrorCode: if (context.AvailBytes() < sizeof(int)) { throw new ParseException("Not well formed PtypInteger32"); } else { // Assign value of int to property's value this.value = new byte[sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(int)); context.CurIndex += sizeof(int); } break; case PropertyType.PtypFloating64: case PropertyType.PtypCurrency: case PropertyType.PtypFloatingTime: case PropertyType.PtypInteger64: case PropertyType.PtypTime: if (context.AvailBytes() < sizeof(long)) { throw new ParseException("Not well formed PtypInteger64"); } else { // Assign value of Int64 to property's value this.value = new byte[sizeof(long)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(long)); context.CurIndex += sizeof(long); } break; case PropertyType.PtypGuid: if (context.AvailBytes() < sizeof(byte) * 16) { throw new ParseException("Not well formed 16 PtypGuid"); } else { // Assign value of Int64 to property's value this.value = new byte[sizeof(byte) * 16]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(byte) * 16); context.CurIndex += sizeof(byte) * 16; } break; case PropertyType.PtypBinary: if (context.AvailBytes() < sizeof(uint)) { throw new ParseException("Not well formed PtypBinary"); } else { // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } // First parse the count of the binary bytes int bytesCount = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(int) + bytesCount]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(int)); context.CurIndex += sizeof(int); // Then parse the binary bytes. if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(int), bytesCount); context.CurIndex += bytesCount; } } break; case PropertyType.PtypMultipleInteger16: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * sizeof(short)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * sizeof(short)); context.CurIndex += bytesCount * sizeof(short); } } break; case PropertyType.PtypMultipleInteger32: case PropertyType.PtypMultipleFloating32: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * sizeof(int)); context.CurIndex += bytesCount * sizeof(int); } } break; case PropertyType.PtypMultipleFloating64: case PropertyType.PtypMultipleCurrency: case PropertyType.PtypMultipleFloatingTime: case PropertyType.PtypMultipleInteger64: case PropertyType.PtypMultipleTime: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * sizeof(long)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * sizeof(long)); context.CurIndex += bytesCount * sizeof(long); } } break; case PropertyType.PtypMultipleGuid: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleInterger"); } else { short bytesCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); this.value = new byte[sizeof(short) + bytesCount * 16]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short)); context.CurIndex += sizeof(short); if (bytesCount == 0) { this.value = null; } else { Array.Copy(context.PropertyBytes, context.CurIndex, this.value, sizeof(short), bytesCount * 16); context.CurIndex += bytesCount * 16; } } break; case PropertyType.PtypString8: // The length in bytes of the unicode string to parse strBytesLen = 0; isFound = false; // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } // Find the string with '\0' end for (int i = context.CurIndex; i < context.PropertyBytes.Length; i++) { strBytesLen++; if (context.PropertyBytes[i] == 0) { isFound = true; break; } } if (!isFound) { throw new ParseException("String too long or not found"); } else { this.value = new byte[strBytesLen]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, strBytesLen); context.CurIndex += strBytesLen; } break; case PropertyType.PtypString: // The length in bytes of the unicode string to parse strBytesLen = 0; isFound = false; // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } else { if (context.PropertyBytes[context.CurIndex] == (byte)0x00) { context.CurIndex++; value = new byte[] { 0x00, 0x00 }; break; } } // Find the string with '\0''\0' end for (int i = context.CurIndex; i < context.PropertyBytes.Length; i += 2) { strBytesLen += 2; if ((context.PropertyBytes[i] == 0) && (context.PropertyBytes[i + 1] == 0)) { isFound = true; break; } } if (!isFound) { throw new ParseException("String too long or not found"); } else { this.value = new byte[strBytesLen]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, strBytesLen); context.CurIndex += strBytesLen; } break; case PropertyType.PtypMultipleString: if (context.AvailBytes() < sizeof(short)) { throw new FormatException("Not well formed PtypMultipleString"); } else { strBytesLen = 0; isFound = false; short stringCount = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); context.CurIndex += sizeof(short); if (stringCount == 0) { value = null; break; } for (int i = context.CurIndex; i < context.PropertyBytes.Length; i += 2) { strBytesLen += 2; if ((context.PropertyBytes[i] == 0) && (context.PropertyBytes[i + 1] == 0)) { stringCount--; } if (stringCount == 0) { isFound = true; break; } } if (!isFound) { throw new FormatException("String too long or not found"); } else { value = new byte[strBytesLen]; Array.Copy(context.PropertyBytes, context.CurIndex, value, 0, strBytesLen); context.CurIndex += strBytesLen; } } break; case PropertyType.PtypMultipleString8: if (context.AvailBytes() < sizeof(int)) { throw new FormatException("Not well formed PtypMultipleString8"); } else { List<byte> listOfBytes = new List<byte>(); // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } if (context.PropertyBytes[context.CurIndex] == (byte)0x00) { this.value = null; } int stringCount = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); byte[] countOfArray = new byte[sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, countOfArray, 0, sizeof(int)); listOfBytes.AddRange(countOfArray); context.CurIndex += sizeof(int); if (stringCount == 0) { value = null; break; } for (int i = 0; i < stringCount; i++) { // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } int countOfString8 = 0; for (int j = context.CurIndex; j < context.PropertyBytes.Length; j++) { countOfString8++; if (context.PropertyBytes[j] == 0) { break; } } byte[] bytesOfString8 = new byte[countOfString8]; Array.Copy(context.PropertyBytes, context.CurIndex, bytesOfString8, 0, countOfString8); listOfBytes.AddRange(bytesOfString8); context.CurIndex += countOfString8; } this.value = listOfBytes.ToArray(); } break; case PropertyType.PtypRuleAction: // Length of the property int felength = 0; // Length of the action blocks short actionBolcksLength = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex); felength += 2; short actionBlockLength = 0; for (int i = 0; i < actionBolcksLength; i++) { actionBlockLength = BitConverter.ToInt16(context.PropertyBytes, context.CurIndex + felength); felength += 2 + actionBlockLength; } this.value = new byte[felength]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, felength); context.CurIndex += felength; break; case PropertyType.PtypServerId: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypServerId"); } else { this.value = new byte[sizeof(short) + 21 * sizeof(byte)]; Array.Copy(context.PropertyBytes, context.CurIndex, this.value, 0, sizeof(short) + 21); context.CurIndex += 21 + sizeof(short); } break; case PropertyType.PtypMultipleBinary: if (context.AvailBytes() < sizeof(short)) { throw new ParseException("Not well formed PtypMultipleBinary"); } else { List<byte> listOfBytes = new List<byte>(); // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } int bytesCount = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); byte[] countOfArray = new byte[sizeof(int)]; Array.Copy(context.PropertyBytes, context.CurIndex, countOfArray, 0, sizeof(int)); listOfBytes.AddRange(countOfArray); context.CurIndex += sizeof(int); for (int ibin = 0; ibin < bytesCount; ibin++) { // Property start with "FF" if (context.PropertyBytes[context.CurIndex] == (byte)0xFF) { context.CurIndex++; } int binLength = BitConverter.ToInt32(context.PropertyBytes, context.CurIndex); Array.Copy(context.PropertyBytes, context.CurIndex, countOfArray, 0, sizeof(int)); listOfBytes.AddRange(countOfArray); context.CurIndex += sizeof(int); if (binLength > 0) { byte[] bytesArray = new byte[binLength]; Array.Copy(context.PropertyBytes, context.CurIndex, bytesArray, 0, binLength); listOfBytes.AddRange(bytesArray); context.CurIndex += sizeof(byte) * binLength; } } this.value = listOfBytes.ToArray(); } break; default: throw new FormatException("Type " + type.ToString() + " not found or not support."); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using Timer=System.Timers.Timer; using Nini.Config; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Scene presence tests /// </summary> [TestFixture] public class ScenePresenceTests { public Scene scene, scene2, scene3; public UUID agent1, agent2, agent3; public static Random random; public ulong region1,region2,region3; public AgentCircuitData acd1; public SceneObjectGroup sog1, sog2, sog3; public TestClient testclient; [TestFixtureSetUp] public void Init() { scene = SceneSetupHelpers.SetupScene("Neighbour x", UUID.Random(), 1000, 1000); scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000); scene3 = SceneSetupHelpers.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000); ISharedRegionModule interregionComms = new LocalSimulationConnectorModule(); interregionComms.Initialise(new IniConfigSource()); interregionComms.PostInitialise(); SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms); SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), interregionComms); SceneSetupHelpers.SetupSceneModules(scene3, new IniConfigSource(), interregionComms); agent1 = UUID.Random(); agent2 = UUID.Random(); agent3 = UUID.Random(); random = new Random(); sog1 = NewSOG(UUID.Random(), scene, agent1); sog2 = NewSOG(UUID.Random(), scene, agent1); sog3 = NewSOG(UUID.Random(), scene, agent1); //ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize)); region1 = scene.RegionInfo.RegionHandle; region2 = scene2.RegionInfo.RegionHandle; region3 = scene3.RegionInfo.RegionHandle; } /// <summary> /// Test adding a root agent to a scene. Doesn't yet actually complete crossing the agent into the scene. /// </summary> [Test] public void T010_TestAddRootAgent() { TestHelper.InMethod(); string firstName = "testfirstname"; AgentCircuitData agent = new AgentCircuitData(); agent.AgentID = agent1; agent.firstname = firstName; agent.lastname = "testlastname"; agent.SessionID = UUID.Zero; agent.SecureSessionID = UUID.Zero; agent.circuitcode = 123; agent.BaseFolder = UUID.Zero; agent.InventoryFolder = UUID.Zero; agent.startpos = Vector3.Zero; agent.CapsPath = GetRandomCapsObjectPath(); agent.ChildrenCapSeeds = new Dictionary<ulong, string>(); agent.child = true; string reason; scene.NewUserConnection(agent, (uint)TeleportFlags.ViaLogin, out reason); testclient = new TestClient(agent, scene); scene.AddNewClient(testclient); ScenePresence presence = scene.GetScenePresence(agent1); Assert.That(presence, Is.Not.Null, "presence is null"); Assert.That(presence.Firstname, Is.EqualTo(firstName), "First name not same"); acd1 = agent; } /// <summary> /// Test removing an uncrossed root agent from a scene. /// </summary> [Test] public void T011_TestRemoveRootAgent() { TestHelper.InMethod(); scene.RemoveClient(agent1); ScenePresence presence = scene.GetScenePresence(agent1); Assert.That(presence, Is.Null, "presence is not null"); } [Test] public void T012_TestAddNeighbourRegion() { TestHelper.InMethod(); string reason; if (acd1 == null) fixNullPresence(); scene.NewUserConnection(acd1, 0, out reason); if (testclient == null) testclient = new TestClient(acd1, scene); scene.AddNewClient(testclient); ScenePresence presence = scene.GetScenePresence(agent1); presence.MakeRootAgent(new Vector3(90,90,90),false); string cap = presence.ControllingClient.RequestClientInfo().CapsPath; presence.AddNeighbourRegion(region2, cap); presence.AddNeighbourRegion(region3, cap); List<ulong> neighbours = presence.GetKnownRegionList(); Assert.That(neighbours.Count, Is.EqualTo(2)); } public void fixNullPresence() { string firstName = "testfirstname"; AgentCircuitData agent = new AgentCircuitData(); agent.AgentID = agent1; agent.firstname = firstName; agent.lastname = "testlastname"; agent.SessionID = UUID.Zero; agent.SecureSessionID = UUID.Zero; agent.circuitcode = 123; agent.BaseFolder = UUID.Zero; agent.InventoryFolder = UUID.Zero; agent.startpos = Vector3.Zero; agent.CapsPath = GetRandomCapsObjectPath(); acd1 = agent; } [Test] public void T013_TestRemoveNeighbourRegion() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); presence.RemoveNeighbourRegion(region3); List<ulong> neighbours = presence.GetKnownRegionList(); Assert.That(neighbours.Count,Is.EqualTo(1)); /* presence.MakeChildAgent; presence.MakeRootAgent; CompleteAvatarMovement */ } // I'm commenting this test, because this is not supposed to happen here //[Test] public void T020_TestMakeRootAgent() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); Assert.That(presence.IsChildAgent, Is.False, "Starts out as a root agent"); presence.MakeChildAgent(); Assert.That(presence.IsChildAgent, Is.True, "Did not change to child agent after MakeChildAgent"); // Accepts 0 but rejects Constants.RegionSize Vector3 pos = new Vector3(0,unchecked(Constants.RegionSize-1),0); presence.MakeRootAgent(pos,true); Assert.That(presence.IsChildAgent, Is.False, "Did not go back to root agent"); Assert.That(presence.AbsolutePosition, Is.EqualTo(pos), "Position is not the same one entered"); } // I'm commenting this test because it does not represent // crossings. The Thread.Sleep's in here are not meaningful mocks, // and they sometimes fail in panda. // We need to talk in order to develop a test // that really tests region crossings. There are 3 async components, // but things are synchronous among them. So there should be // 3 threads in here. //[Test] public void T021_TestCrossToNewRegion() { TestHelper.InMethod(); scene.RegisterRegionWithGrid(); scene2.RegisterRegionWithGrid(); // Adding child agent to region 1001 string reason; scene2.NewUserConnection(acd1,0, out reason); scene2.AddNewClient(testclient); ScenePresence presence = scene.GetScenePresence(agent1); presence.MakeRootAgent(new Vector3(0,unchecked(Constants.RegionSize-1),0), true); ScenePresence presence2 = scene2.GetScenePresence(agent1); // Adding neighbour region caps info to presence2 string cap = presence.ControllingClient.RequestClientInfo().CapsPath; presence2.AddNeighbourRegion(region1, cap); Assert.That(presence.IsChildAgent, Is.False, "Did not start root in origin region."); Assert.That(presence2.IsChildAgent, Is.True, "Is not a child on destination region."); // Cross to x+1 presence.AbsolutePosition = new Vector3(Constants.RegionSize+1,3,100); presence.Update(); EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing"); // Mimicking communication between client and server, by waiting OK from client // sent by TestClient.CrossRegion call. Originally, this is network comm. if (!wh.WaitOne(5000,false)) { presence.Update(); if (!wh.WaitOne(8000,false)) throw new ArgumentException("1 - Timeout waiting for signal/variable."); } // This is a TestClient specific method that fires OnCompleteMovementToRegion event, which // would normally be fired after receiving the reply packet from comm. done on the last line. testclient.CompleteMovement(); // Crossings are asynchronous int timer = 10; // Make sure cross hasn't already finished if (!presence.IsInTransit && !presence.IsChildAgent) { // If not and not in transit yet, give it some more time Thread.Sleep(5000); } // Enough time, should at least be in transit by now. while (presence.IsInTransit && timer > 0) { Thread.Sleep(1000); timer-=1; } Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 2->1."); Assert.That(presence.IsChildAgent, Is.True, "Did not complete region cross as expected."); Assert.That(presence2.IsChildAgent, Is.False, "Did not receive root status after receiving agent."); // Cross Back presence2.AbsolutePosition = new Vector3(-10, 3, 100); presence2.Update(); if (!wh.WaitOne(5000,false)) { presence2.Update(); if (!wh.WaitOne(8000,false)) throw new ArgumentException("2 - Timeout waiting for signal/variable."); } testclient.CompleteMovement(); if (!presence2.IsInTransit && !presence2.IsChildAgent) { // If not and not in transit yet, give it some more time Thread.Sleep(5000); } // Enough time, should at least be in transit by now. while (presence2.IsInTransit && timer > 0) { Thread.Sleep(1000); timer-=1; } Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 1->2."); Assert.That(presence2.IsChildAgent, Is.True, "Did not return from region as expected."); Assert.That(presence.IsChildAgent, Is.False, "Presence was not made root in old region again."); } [Test] public void T030_TestAddAttachments() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); presence.AddAttachment(sog1); presence.AddAttachment(sog2); presence.AddAttachment(sog3); Assert.That(presence.HasAttachments(), Is.True); Assert.That(presence.ValidateAttachments(), Is.True); } [Test] public void T031_RemoveAttachments() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); presence.RemoveAttachment(sog1); presence.RemoveAttachment(sog2); presence.RemoveAttachment(sog3); Assert.That(presence.HasAttachments(), Is.False); } // I'm commenting this test because scene setup NEEDS InventoryService to // be non-null //[Test] public void T032_CrossAttachments() { TestHelper.InMethod(); ScenePresence presence = scene.GetScenePresence(agent1); ScenePresence presence2 = scene2.GetScenePresence(agent1); presence2.AddAttachment(sog1); presence2.AddAttachment(sog2); ISharedRegionModule serialiser = new SerialiserModule(); SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), serialiser); SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), serialiser); Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross"); //Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful"); Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted"); Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects"); } [TearDown] public void TearDown() { if (MainServer.Instance != null) MainServer.Instance.Stop(); } public static string GetRandomCapsObjectPath() { TestHelper.InMethod(); UUID caps = UUID.Random(); string capsPath = caps.ToString(); capsPath = capsPath.Remove(capsPath.Length - 4, 4); return capsPath; } private SceneObjectGroup NewSOG(UUID uuid, Scene scene, UUID agent) { SceneObjectPart sop = new SceneObjectPart(); sop.Name = RandomName(); sop.Description = RandomName(); sop.Text = RandomName(); sop.SitName = RandomName(); sop.TouchName = RandomName(); sop.UUID = uuid; sop.Shape = PrimitiveBaseShape.Default; sop.Shape.State = 1; sop.OwnerID = agent; SceneObjectGroup sog = new SceneObjectGroup(sop); sog.SetScene(scene); return sog; } private static string RandomName() { StringBuilder name = new StringBuilder(); int size = random.Next(5,12); char ch ; for (int i=0; i<size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ; name.Append(ch); } return name.ToString(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Formatting.Indentation; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.Formatting.Indentation { internal partial class CSharpIndentationService { internal class Indenter : AbstractIndenter { public Indenter(Document document, IEnumerable<IFormattingRule> rules, OptionSet optionSet, ITextSnapshotLine line, CancellationToken cancellationToken) : base(document, rules, optionSet, line, cancellationToken) { } public override IndentationResult? GetDesiredIndentation() { var indentStyle = OptionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp); if (indentStyle == FormattingOptions.IndentStyle.None) { return null; } // find previous line that is not blank var previousLine = GetPreviousNonBlankOrPreprocessorLine(); // it is beginning of the file, there is no previous line exists. // in that case, indentation 0 is our base indentation. if (previousLine == null) { return IndentFromStartOfLine(0); } // okay, now see whether previous line has anything meaningful var lastNonWhitespacePosition = previousLine.GetLastNonWhitespacePosition(); if (!lastNonWhitespacePosition.HasValue) { return null; } // there is known parameter list "," parse bug. if previous token is "," from parameter list, // FindToken will not be able to find them. var token = Tree.GetRoot(CancellationToken).FindToken(lastNonWhitespacePosition.Value); if (token.IsKind(SyntaxKind.None) || indentStyle == FormattingOptions.IndentStyle.Block) { return GetIndentationOfLine(previousLine); } // okay, now check whether the text we found is trivia or actual token. if (token.Span.Contains(lastNonWhitespacePosition.Value)) { // okay, it is a token case, do special work based on type of last token on previous line return GetIndentationBasedOnToken(token); } else { // there must be trivia that contains or touch this position Contract.Assert(token.FullSpan.Contains(lastNonWhitespacePosition.Value)); // okay, now check whether the trivia is at the beginning of the line var firstNonWhitespacePosition = previousLine.GetFirstNonWhitespacePosition(); if (!firstNonWhitespacePosition.HasValue) { return IndentFromStartOfLine(0); } var trivia = Tree.GetRoot(CancellationToken).FindTrivia(firstNonWhitespacePosition.Value, findInsideTrivia: true); if (trivia.Kind() == SyntaxKind.None || this.LineToBeIndented.LineNumber > previousLine.LineNumber + 1) { // If the token belongs to the next statement and is also the first token of the statement, then it means the user wants // to start type a new statement. So get indentation from the start of the line but not based on the token. // Case: // static void Main(string[] args) // { // // A // // B // // $$ // return; // } var containingStatement = token.GetAncestor<StatementSyntax>(); if (containingStatement != null && containingStatement.GetFirstToken() == token) { var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start); return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } // If the token previous of the base token happens to be a Comma from a separation list then we need to handle it different // Case: // var s = new List<string> // { // """", // """",/*sdfsdfsdfsdf*/ // // dfsdfsdfsdfsdf // // $$ // }; var previousToken = token.GetPreviousToken(); if (previousToken.IsKind(SyntaxKind.CommaToken)) { return GetIndentationFromCommaSeparatedList(previousToken); } // okay, beginning of the line is not trivia, use the last token on the line as base token return GetIndentationBasedOnToken(token); } // this case we will keep the indentation of this trivia line // this trivia can't be preprocessor by the way. return GetIndentationOfLine(previousLine); } } private IndentationResult? GetIndentationBasedOnToken(SyntaxToken token) { Contract.ThrowIfNull(LineToBeIndented); Contract.ThrowIfNull(Tree); Contract.ThrowIfTrue(token.Kind() == SyntaxKind.None); // special cases // case 1: token belongs to verbatim token literal // case 2: $@"$${0}" // case 3: $@"Comment$$ inbetween{0}" // case 4: $@"{0}$$" if (token.IsVerbatimStringLiteral() || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || (token.IsKind(SyntaxKind.CloseBraceToken) && token.Parent.IsKind(SyntaxKind.Interpolation))) { return IndentFromStartOfLine(0); } // if previous statement belong to labeled statement, don't follow label's indentation // but its previous one. if (token.Parent is LabeledStatementSyntax || token.IsLastTokenInLabelStatement()) { token = token.GetAncestor<LabeledStatementSyntax>().GetFirstToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true); } var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start); // first check operation service to see whether we can determine indentation from it var indentation = Finder.FromIndentBlockOperations(Tree, token, position, CancellationToken); if (indentation.HasValue) { return IndentFromStartOfLine(indentation.Value); } var alignmentTokenIndentation = Finder.FromAlignTokensOperations(Tree, token); if (alignmentTokenIndentation.HasValue) { return IndentFromStartOfLine(alignmentTokenIndentation.Value); } // if we couldn't determine indentation from the service, use hueristic to find indentation. var snapshot = LineToBeIndented.Snapshot; // If this is the last token of an embedded statement, walk up to the top-most parenting embedded // statement owner and use its indentation. // // cases: // if (true) // if (false) // Foo(); // // if (true) // { } if (token.IsSemicolonOfEmbeddedStatement() || token.IsCloseBraceOfEmbeddedBlock()) { Contract.Requires( token.Parent != null && (token.Parent.Parent is StatementSyntax || token.Parent.Parent is ElseClauseSyntax)); var embeddedStatementOwner = token.Parent.Parent; while (embeddedStatementOwner.IsEmbeddedStatement()) { embeddedStatementOwner = embeddedStatementOwner.Parent; } return GetIndentationOfLine(snapshot.GetLineFromPosition(embeddedStatementOwner.GetFirstToken(includeZeroWidth: true).SpanStart)); } switch (token.Kind()) { case SyntaxKind.SemicolonToken: { // special cases if (token.IsSemicolonInForStatement()) { return GetDefaultIndentationFromToken(token); } return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } case SyntaxKind.CloseBraceToken: { return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } case SyntaxKind.OpenBraceToken: { return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, CancellationToken)); } case SyntaxKind.ColonToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); if (nonTerminalNode is SwitchLabelSyntax) { return GetIndentationOfLine(snapshot.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart), OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language)); } // default case return GetDefaultIndentationFromToken(token); } case SyntaxKind.CloseBracketToken: { var nonTerminalNode = token.Parent; Contract.ThrowIfNull(nonTerminalNode, @"Malformed code or bug in parser???"); // if this is closing an attribute, we shouldn't indent. if (nonTerminalNode is AttributeListSyntax) { return GetIndentationOfLine(snapshot.GetLineFromPosition(nonTerminalNode.GetFirstToken(includeZeroWidth: true).SpanStart)); } // default case return GetDefaultIndentationFromToken(token); } case SyntaxKind.XmlTextLiteralToken: { return GetIndentationOfLine(snapshot.GetLineFromPosition(token.SpanStart)); } case SyntaxKind.CommaToken: { return GetIndentationFromCommaSeparatedList(token); } default: { return GetDefaultIndentationFromToken(token); } } } private IndentationResult? GetIndentationFromCommaSeparatedList(SyntaxToken token) { var node = token.Parent; var argument = node as BaseArgumentListSyntax; if (argument != null) { return GetIndentationFromCommaSeparatedList(argument.Arguments, token); } var parameter = node as BaseParameterListSyntax; if (parameter != null) { return GetIndentationFromCommaSeparatedList(parameter.Parameters, token); } var typeArgument = node as TypeArgumentListSyntax; if (typeArgument != null) { return GetIndentationFromCommaSeparatedList(typeArgument.Arguments, token); } var typeParameter = node as TypeParameterListSyntax; if (typeParameter != null) { return GetIndentationFromCommaSeparatedList(typeParameter.Parameters, token); } var enumDeclaration = node as EnumDeclarationSyntax; if (enumDeclaration != null) { return GetIndentationFromCommaSeparatedList(enumDeclaration.Members, token); } var initializerSyntax = node as InitializerExpressionSyntax; if (initializerSyntax != null) { return GetIndentationFromCommaSeparatedList(initializerSyntax.Expressions, token); } return GetDefaultIndentationFromToken(token); } private IndentationResult? GetIndentationFromCommaSeparatedList<T>(SeparatedSyntaxList<T> list, SyntaxToken token) where T : SyntaxNode { var index = list.GetWithSeparators().IndexOf(token); if (index < 0) { return GetDefaultIndentationFromToken(token); } // find node that starts at the beginning of a line var snapshot = LineToBeIndented.Snapshot; for (int i = (index - 1) / 2; i >= 0; i--) { var node = list[i]; var firstToken = node.GetFirstToken(includeZeroWidth: true); if (firstToken.IsFirstTokenOnLine(snapshot)) { return GetIndentationOfLine(snapshot.GetLineFromPosition(firstToken.SpanStart)); } } // smart indenter has a special indent block rule for comma separated list, so don't // need to add default additional space for multiline expressions return GetDefaultIndentationFromTokenLine(token, additionalSpace: 0); } private IndentationResult? GetDefaultIndentationFromToken(SyntaxToken token) { if (IsPartOfQueryExpression(token)) { return GetIndentationForQueryExpression(token); } return GetDefaultIndentationFromTokenLine(token); } private IndentationResult? GetIndentationForQueryExpression(SyntaxToken token) { // find containing non terminal node var queryExpressionClause = GetQueryExpressionClause(token); Contract.ThrowIfNull(queryExpressionClause); // find line where first token of the node is var snapshot = LineToBeIndented.Snapshot; var firstToken = queryExpressionClause.GetFirstToken(includeZeroWidth: true); var firstTokenLine = snapshot.GetLineFromPosition(firstToken.SpanStart); // find line where given token is var givenTokenLine = snapshot.GetLineFromPosition(token.SpanStart); if (firstTokenLine.LineNumber != givenTokenLine.LineNumber) { // do default behavior return GetDefaultIndentationFromTokenLine(token); } // okay, we are right under the query expression. // align caret to query expression if (firstToken.IsFirstTokenOnLine(snapshot)) { return GetIndentationOfToken(firstToken); } // find query body that has a token that is a first token on the line var queryBody = queryExpressionClause.Parent as QueryBodySyntax; if (queryBody == null) { return GetIndentationOfToken(firstToken); } // find preceding clause that starts on its own. var clauses = queryBody.Clauses; for (int i = clauses.Count - 1; i >= 0; i--) { var clause = clauses[i]; if (firstToken.SpanStart <= clause.SpanStart) { continue; } var clauseToken = clause.GetFirstToken(includeZeroWidth: true); if (clauseToken.IsFirstTokenOnLine(snapshot)) { var tokenSpan = clauseToken.Span.ToSnapshotSpan(snapshot); return GetIndentationOfToken(clauseToken); } } // no query clause start a line. use the first token of the query expression return GetIndentationOfToken(queryBody.Parent.GetFirstToken(includeZeroWidth: true)); } private SyntaxNode GetQueryExpressionClause(SyntaxToken token) { var clause = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is QueryClauseSyntax || n is SelectOrGroupClauseSyntax); if (clause != null) { return clause; } // If this is a query continuation, use the last clause of its parenting query. var body = token.GetAncestor<QueryBodySyntax>(); if (body != null) { if (body.SelectOrGroup.IsMissing) { return body.Clauses.LastOrDefault(); } else { return body.SelectOrGroup; } } return null; } private bool IsPartOfQueryExpression(SyntaxToken token) { var queryExpression = token.GetAncestor<QueryExpressionSyntax>(); return queryExpression != null; } private IndentationResult? GetDefaultIndentationFromTokenLine(SyntaxToken token, int? additionalSpace = null) { var spaceToAdd = additionalSpace ?? this.OptionSet.GetOption(FormattingOptions.IndentationSize, token.Language); var snapshot = LineToBeIndented.Snapshot; // find line where given token is var givenTokenLine = snapshot.GetLineFromPosition(token.SpanStart); // find right position var position = GetCurrentPositionNotBelongToEndOfFileToken(LineToBeIndented.Start); // find containing non expression node var nonExpressionNode = token.GetAncestors<SyntaxNode>().FirstOrDefault(n => n is StatementSyntax); if (nonExpressionNode == null) { // well, I can't find any non expression node. use default behavior return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken)); } // find line where first token of the node is var firstTokenLine = snapshot.GetLineFromPosition(nonExpressionNode.GetFirstToken(includeZeroWidth: true).SpanStart); // single line expression if (firstTokenLine.LineNumber == givenTokenLine.LineNumber) { return IndentFromStartOfLine(Finder.GetIndentationOfCurrentPosition(Tree, token, position, spaceToAdd, CancellationToken)); } // okay, looks like containing node is written over multiple lines, in that case, give same indentation as given token return GetIndentationOfLine(givenTokenLine); } protected override bool HasPreprocessorCharacter(ITextSnapshotLine currentLine) { if (currentLine == null) { throw new ArgumentNullException("currentLine"); } var text = currentLine.GetText(); Contract.Requires(!string.IsNullOrWhiteSpace(text)); var trimedText = text.Trim(); Contract.Assert(SyntaxFacts.GetText(SyntaxKind.HashToken).Length == 1); return trimedText[0] == SyntaxFacts.GetText(SyntaxKind.HashToken)[0]; } private int GetCurrentPositionNotBelongToEndOfFileToken(int position) { var compilationUnit = Tree.GetRoot(CancellationToken) as CompilationUnitSyntax; if (compilationUnit == null) { return position; } return Math.Min(compilationUnit.EndOfFileToken.FullSpan.Start, position); } } } }
/* * Bason the Article http://www.codeproject.com/Articles/19781/A-data-bound-multi-column-combobox * To report bug-fixes or to send in suggestions, you * can email me at nish@voidnish.com * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.ComponentModel; using System.Drawing; using System.Globalization; namespace WinFormsMvvm { public class MultiColumnComboBox : ComboBox { public MultiColumnComboBox() { DrawMode = DrawMode.OwnerDrawVariable; } public new DrawMode DrawMode { get { return base.DrawMode; } set { if (value != DrawMode.OwnerDrawVariable) { throw new NotSupportedException("Needs to be DrawMode.OwnerDrawVariable"); } base.DrawMode = value; } } public new ComboBoxStyle DropDownStyle { get { return base.DropDownStyle; } set { if (value == ComboBoxStyle.Simple) { throw new NotSupportedException("ComboBoxStyle.Simple not supported"); } base.DropDownStyle = value; } } // private List<string> memberListToShow = new List<string>(); private List<string> MemberListToShow { get; set; } protected override void OnDataSourceChanged(EventArgs e) { base.OnDataSourceChanged(e); InitializeColumns(); } protected override void OnValueMemberChanged(EventArgs e) { base.OnValueMemberChanged(e); InitializeValueMemberColumn(); } protected override void OnDropDown(EventArgs e) { base.OnDropDown(e); this.DropDownWidth = (int)CalculateTotalWidth(); } const int columnPadding = 5; private float[] columnWidths = new float[0]; private String[] columnNames = new String[0]; private int valueMemberColumnIndex = 0; public void SetMemberList(List<string> memberList) { MemberListToShow = new List<string>(memberList); } private void InitializeColumns() { if (DataManager == null) return; PropertyDescriptorCollection propertyDescriptorCollection = DataManager.GetItemProperties(); int columnCount = propertyDescriptorCollection.Count; if (MemberListToShow != null) { if (columnCount > MemberListToShow.Count) { columnCount = MemberListToShow.Count; } } if (columnWidths.Length != columnCount) { columnWidths = new float[columnCount]; columnNames = new String[columnCount]; } int saveIndex = 0; for (int colIndex = 0; colIndex < propertyDescriptorCollection.Count; colIndex++) { String name = propertyDescriptorCollection[colIndex].Name; if (MemberListToShow == null || MemberListToShow.Contains(name)) { columnNames[saveIndex] = name; saveIndex++; } } if (columnNames.Length != saveIndex) { string colMissing = ""; for (int i = 0; i < columnNames.Length; i++) { if (!MemberListToShow.Contains(columnNames[i])) { if (colMissing != "") { colMissing = "," + columnNames[i]; } else { colMissing = columnNames[i]; } } } throw new ArgumentException("Memberlist contains unknown Membername(s)",colMissing); } } private void InitializeValueMemberColumn() { int colIndex = 0; foreach (String columnName in columnNames) { if (String.Compare(columnName, ValueMember, true, CultureInfo.CurrentUICulture) == 0) { valueMemberColumnIndex = colIndex; break; } colIndex++; } } private float CalculateTotalWidth() { float totWidth = 0; foreach (int width in columnWidths) { totWidth += (width + columnPadding); } return totWidth + SystemInformation.VerticalScrollBarWidth; } protected override void OnMeasureItem(MeasureItemEventArgs e) { base.OnMeasureItem(e); if (DesignMode) return; for (int colIndex = 0; colIndex < columnNames.Length; colIndex++) { string item = Convert.ToString(FilterItemOnProperty(Items[e.Index], columnNames[colIndex])); SizeF sizeF = e.Graphics.MeasureString(item, Font); columnWidths[colIndex] = Math.Max(columnWidths[colIndex], sizeF.Width); } float totWidth = CalculateTotalWidth(); e.ItemWidth = (int)totWidth; } protected override void OnDrawItem(DrawItemEventArgs e) { base.OnDrawItem(e); if (DesignMode) return; e.DrawBackground(); if (e.Index < 0) { return; } Rectangle boundsRect = e.Bounds; int lastRight = 0; using (Pen linePen = new Pen(SystemColors.GrayText)) { using (SolidBrush brush = new SolidBrush(ForeColor)) { if (columnNames.Length == 0) { e.Graphics.DrawString(Convert.ToString(Items[e.Index]), Font, brush, boundsRect); } else { for (int colIndex = 0; colIndex < columnNames.Length; colIndex++) { string item = Convert.ToString(FilterItemOnProperty(Items[e.Index], columnNames[colIndex])); boundsRect.X = lastRight; boundsRect.Width = (int)columnWidths[colIndex] + columnPadding; lastRight = boundsRect.Right; if (colIndex == valueMemberColumnIndex) { using (Font boldFont = new Font(Font, FontStyle.Bold)) { e.Graphics.DrawString(item, boldFont, brush, boundsRect); } } else { e.Graphics.DrawString(item, Font, brush, boundsRect); } if (colIndex < columnNames.Length - 1) { e.Graphics.DrawLine(linePen, boundsRect.Right, boundsRect.Top, boundsRect.Right, boundsRect.Bottom); } } } } } e.DrawFocusRectangle(); } } }
using System; using System.Collections; using System.IO; using System.Globalization; using BigMath; using Raksha.Asn1.Cms; using Raksha.Asn1; using Raksha.Asn1.CryptoPro; using Raksha.Asn1.Pkcs; using Raksha.Asn1.X509; using Raksha.Asn1.X9; using Raksha.Crypto; using Raksha.Crypto.Parameters; using Raksha.Math; using Raksha.Pkcs; using Raksha.Security; using Raksha.Security.Certificates; using Raksha.Utilities; using Raksha.Utilities.Encoders; using Raksha.Utilities.IO.Pem; using Raksha.X509; namespace Raksha.OpenSsl { /** * PEM generator for the original set of PEM objects used in Open SSL. */ public class MiscPemGenerator : PemObjectGenerator { private object obj; private string algorithm; private char[] password; private SecureRandom random; public MiscPemGenerator(object obj) { this.obj = obj; } public MiscPemGenerator( object obj, string algorithm, char[] password, SecureRandom random) { this.obj = obj; this.algorithm = algorithm; this.password = password; this.random = random; } private PemObject CreatePemObject(object o) { if (obj == null) throw new ArgumentNullException("obj"); if (obj is AsymmetricCipherKeyPair) { return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private); } string type; byte[] encoding; if (o is PemObject) return (PemObject)o; if (o is PemObjectGenerator) return ((PemObjectGenerator)o).Generate(); if (obj is X509Certificate) { // TODO Should we prefer "X509 CERTIFICATE" here? type = "CERTIFICATE"; try { encoding = ((X509Certificate)obj).GetEncoded(); } catch (CertificateEncodingException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } else if (obj is X509Crl) { type = "X509 CRL"; try { encoding = ((X509Crl)obj).GetEncoded(); } catch (CrlException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } else if (obj is AsymmetricKeyParameter) { AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj; if (akp.IsPrivate) { string keyType; encoding = EncodePrivateKey(akp, out keyType); type = keyType + " PRIVATE KEY"; } else { type = "PUBLIC KEY"; encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded(); } } else if (obj is IX509AttributeCertificate) { type = "ATTRIBUTE CERTIFICATE"; encoding = ((X509V2AttributeCertificate)obj).GetEncoded(); } else if (obj is Pkcs10CertificationRequest) { type = "CERTIFICATE REQUEST"; encoding = ((Pkcs10CertificationRequest)obj).GetEncoded(); } else if (obj is Asn1.Cms.ContentInfo) { type = "PKCS7"; encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded(); } else { throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName); } return new PemObject(type, encoding); } // private string GetHexEncoded(byte[] bytes) // { // bytes = Hex.Encode(bytes); // // char[] chars = new char[bytes.Length]; // // for (int i = 0; i != bytes.Length; i++) // { // chars[i] = (char)bytes[i]; // } // // return new string(chars); // } private PemObject CreatePemObject( object obj, string algorithm, char[] password, SecureRandom random) { if (obj == null) throw new ArgumentNullException("obj"); if (algorithm == null) throw new ArgumentNullException("algorithm"); if (password == null) throw new ArgumentNullException("password"); if (random == null) throw new ArgumentNullException("random"); if (obj is AsymmetricCipherKeyPair) { return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random); } string type = null; byte[] keyData = null; if (obj is AsymmetricKeyParameter) { AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj; if (akp.IsPrivate) { string keyType; keyData = EncodePrivateKey(akp, out keyType); type = keyType + " PRIVATE KEY"; } } if (type == null || keyData == null) { // TODO Support other types? throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName); } string dekAlgName = algorithm.ToUpperInvariant(); // Note: For backward compatibility if (dekAlgName == "DESEDE") { dekAlgName = "DES-EDE3-CBC"; } int ivLength = dekAlgName.StartsWith("AES-") ? 16 : 8; byte[] iv = new byte[ivLength]; random.NextBytes(iv); byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv); IList headers = Platform.CreateArrayList(2); headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED")); headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv))); return new PemObject(type, headers, encData); } private byte[] EncodePrivateKey( AsymmetricKeyParameter akp, out string keyType) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp); DerObjectIdentifier oid = info.AlgorithmID.ObjectID; if (oid.Equals(X9ObjectIdentifiers.IdDsa)) { keyType = "DSA"; DsaParameter p = DsaParameter.GetInstance(info.AlgorithmID.Parameters); BigInteger x = ((DsaPrivateKeyParameters) akp).X; BigInteger y = p.G.ModPow(x, p.P); // TODO Create an ASN1 object somewhere for this? return new DerSequence( new DerInteger(0), new DerInteger(p.P), new DerInteger(p.Q), new DerInteger(p.G), new DerInteger(y), new DerInteger(x)).GetEncoded(); } if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption)) { keyType = "RSA"; } else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001) || oid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { keyType = "EC"; } else { throw new ArgumentException("Cannot handle private key of type: " + akp.GetType().FullName, "akp"); } return info.PrivateKey.GetEncoded(); } public PemObject Generate() { try { if (algorithm != null) { return CreatePemObject(obj, algorithm, password, random); } return CreatePemObject(obj); } catch (IOException e) { throw new PemGenerationException("encoding exception", e); } } } }
using Mono.Cecil; using Neo.IO.Json; using Neo.SmartContract.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Neo.Compiler { public class FuncExport { public static readonly TypeReference Void = new TypeReference("System", "Void", ModuleDefinition.ReadModule(typeof(object).Assembly.Location, new ReaderParameters(ReadingMode.Immediate)), null); public static readonly TypeReference Boolean = new TypeReference("System", "Boolean", ModuleDefinition.ReadModule(typeof(object).Assembly.Location, new ReaderParameters(ReadingMode.Immediate)), null); internal static string ConvType(TypeReference t) { if (t is null) return "Null"; var type = t.FullName; TypeDefinition definition = t.Resolve(); if (definition != null) foreach (var i in definition.Interfaces) { if (i.InterfaceType.Name == nameof(IApiInterface)) { return "IInteropInterface"; } } switch (type) { case "System.Boolean": return "Boolean"; case "System.Char": case "System.Byte": case "System.SByte": case "System.Int16": case "System.UInt16": case "System.Int32": case "System.UInt32": case "System.Int64": case "System.UInt64": case "System.Numerics.BigInteger": return "Integer"; case "System.Byte[]": return "ByteArray"; case "System.String": return "String"; case "IInteropInterface": return "InteropInterface"; case "System.Void": return "Void"; case "System.Object": return "Any"; } if (t.IsArray) return "Array"; if (type.StartsWith("System.Action") || type.StartsWith("System.Func") || type.StartsWith("System.Delegate")) return $"Unknown:Pointers are not allowed to be public '{type}'"; if (type.StartsWith("System.ValueTuple`") || type.StartsWith("System.Tuple`")) return "Array"; return "Unknown:" + type; } public static string ComputeHash(byte[] script) { var sha256 = System.Security.Cryptography.SHA256.Create(); byte[] hash256 = sha256.ComputeHash(script); var ripemd160 = new Neo.Cryptography.RIPEMD160Managed(); var hash = ripemd160.ComputeHash(hash256); StringBuilder sb = new StringBuilder(); sb.Append("0x"); for (int i = hash.Length - 1; i >= 0; i--) { sb.Append(hash[i].ToString("x02")); } return sb.ToString(); } public static JObject Export(NeoModule module, byte[] script, Dictionary<int, int> addrConvTable) { var outjson = new JObject(); //hash outjson["hash"] = ComputeHash(script); //functions var methods = new JArray(); outjson["methods"] = methods; HashSet<string> names = new HashSet<string>(); foreach (var function in module.mapMethods) { var mm = function.Value; if (mm.inSmartContract == false) continue; if (mm.isPublic == false) continue; if (!names.Add(function.Value.displayName)) { throw new Exception("abi not allow same name functions"); } var funcsign = new JObject(); methods.Add(funcsign); funcsign["name"] = function.Value.displayName; var offset = addrConvTable?[function.Value.funcaddr] ?? function.Value.funcaddr; funcsign["offset"] = offset.ToString(); JArray funcparams = new JArray(); funcsign["parameters"] = funcparams; if (mm.paramtypes != null) { foreach (var v in mm.paramtypes) { var item = new JObject(); funcparams.Add(item); item["name"] = v.name; item["type"] = ConvType(v.type); } } var rtype = ConvType(mm.returntype); if (rtype.StartsWith("Unknown:")) { throw new Exception($"Unknown return type '{mm.returntype}' for method '{function.Value.name}'"); } funcsign["returntype"] = rtype; } //events var eventsigns = new JArray(); outjson["events"] = eventsigns; foreach (var events in module.mapEvents) { var mm = events.Value; var funcsign = new JObject(); eventsigns.Add(funcsign); funcsign["name"] = events.Value.displayName; JArray funcparams = new JArray(); funcsign["parameters"] = funcparams; if (mm.paramtypes != null) { foreach (var v in mm.paramtypes) { var item = new JObject(); funcparams.Add(item); item["name"] = v.name; item["type"] = ConvType(v.type); } } //event do not have returntype in nep3 //var rtype = ConvType(mm.returntype); //funcsign["returntype", rtype); } return outjson; } private static object BuildSupportedStandards(Mono.Collections.Generic.Collection<CustomAttributeArgument> supportedStandardsAttribute) { if (supportedStandardsAttribute == null || supportedStandardsAttribute.Count == 0) { return "[]"; } var entry = supportedStandardsAttribute.First(); string extra = "["; foreach (var item in entry.Value as CustomAttributeArgument[]) { extra += ($"\"{ScapeJson(item.Value.ToString())}\","); } extra = extra[0..^1]; extra += "]"; return extra; } private static string BuildExtraAttributes(ICollection<Mono.Collections.Generic.Collection<CustomAttributeArgument>> extraAttributes) { if (extraAttributes == null || extraAttributes.Count == 0) { return "null"; } string extra = "{"; foreach (var extraAttribute in extraAttributes) { var key = ScapeJson(extraAttribute[0].Value.ToString()); var value = ScapeJson(extraAttribute[1].Value.ToString()); extra += ($"\"{key}\":\"{value}\","); } extra = extra[0..^1]; extra += "}"; return extra; } private static string ScapeJson(string value) { return value.Replace("\"", ""); } public static string GenerateManifest(JObject abi, NeoModule module) { var sbABI = abi.ToString(false); var features = module == null ? ContractFeatures.NoProperty : module.attributes .Where(u => u.AttributeType.FullName == "Neo.SmartContract.Framework.FeaturesAttribute") .Select(u => (ContractFeatures)u.ConstructorArguments.FirstOrDefault().Value) .FirstOrDefault(); var extraAttributes = module == null ? Array.Empty<Mono.Collections.Generic.Collection<CustomAttributeArgument>>() : module.attributes.Where(u => u.AttributeType.FullName == "Neo.SmartContract.Framework.ManifestExtraAttribute").Select(attribute => attribute.ConstructorArguments).ToArray(); var supportedStandardsAttribute = module?.attributes.Where(u => u.AttributeType.FullName == "Neo.SmartContract.Framework.SupportedStandardsAttribute").Select(attribute => attribute.ConstructorArguments).FirstOrDefault(); var extra = BuildExtraAttributes(extraAttributes); var supportedStandards = BuildSupportedStandards(supportedStandardsAttribute); var storage = features.HasFlag(ContractFeatures.HasStorage).ToString().ToLowerInvariant(); var payable = features.HasFlag(ContractFeatures.Payable).ToString().ToLowerInvariant(); return @"{""groups"":[],""features"":{""storage"":" + storage + @",""payable"":" + payable + @"},""abi"":" + sbABI + @",""permissions"":[{""contract"":""*"",""methods"":""*""}],""trusts"":[],""safemethods"":[],""supportedstandards"":" + supportedStandards + @",""extra"":" + extra + "}"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.IO; namespace System.Data.ProviderBase { internal class DbMetaDataFactory { private DataSet _metaDataCollectionsDataSet; private string _normalizedServerVersion; private string _serverVersionString; // well known column names private const string _collectionName = "CollectionName"; private const string _populationMechanism = "PopulationMechanism"; private const string _populationString = "PopulationString"; private const string _maximumVersion = "MaximumVersion"; private const string _minimumVersion = "MinimumVersion"; private const string _dataSourceProductVersionNormalized = "DataSourceProductVersionNormalized"; private const string _dataSourceProductVersion = "DataSourceProductVersion"; private const string _restrictionNumber = "RestrictionNumber"; private const string _numberOfRestrictions = "NumberOfRestrictions"; private const string _restrictionName = "RestrictionName"; private const string _parameterName = "ParameterName"; // population mechanisms private const string _dataTable = "DataTable"; private const string _sqlCommand = "SQLCommand"; private const string _prepareCollection = "PrepareCollection"; public DbMetaDataFactory(Stream xmlStream, string serverVersion, string normalizedServerVersion) { ADP.CheckArgumentNull(xmlStream, nameof(xmlStream)); ADP.CheckArgumentNull(serverVersion, nameof(serverVersion)); ADP.CheckArgumentNull(normalizedServerVersion, nameof(normalizedServerVersion)); LoadDataSetFromXml(xmlStream); _serverVersionString = serverVersion; _normalizedServerVersion = normalizedServerVersion; } protected DataSet CollectionDataSet => _metaDataCollectionsDataSet; protected string ServerVersion => _serverVersionString; protected string ServerVersionNormalized => _normalizedServerVersion; protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames) { DataTable destinationTable; DataColumn[] filteredSourceColumns; DataColumnCollection destinationColumns; DataRow newRow; DataTable sourceTable = _metaDataCollectionsDataSet.Tables[collectionName]; if ((sourceTable == null) || (collectionName != sourceTable.TableName)) { throw ADP.DataTableDoesNotExist(collectionName); } destinationTable = new DataTable(collectionName) { Locale = CultureInfo.InvariantCulture }; destinationColumns = destinationTable.Columns; filteredSourceColumns = FilterColumns(sourceTable, hiddenColumnNames, destinationColumns); foreach (DataRow row in sourceTable.Rows) { if (SupportedByCurrentVersion(row) == true) { newRow = destinationTable.NewRow(); for (int i = 0; i < destinationColumns.Count; i++) { newRow[destinationColumns[i]] = row[filteredSourceColumns[i], DataRowVersion.Current]; } destinationTable.Rows.Add(newRow); newRow.AcceptChanges(); } } return destinationTable; } public void Dispose() => Dispose(true); protected virtual void Dispose(bool disposing) { if (disposing) { _normalizedServerVersion = null; _serverVersionString = null; _metaDataCollectionsDataSet.Dispose(); } } private DataTable ExecuteCommand(DataRow requestedCollectionRow, string[] restrictions, DbConnection connection) { DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString]; DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions]; DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName]; DataTable resultTable = null; DbCommand command = null; DataTable schemaTable = null; Debug.Assert(requestedCollectionRow != null); string sqlCommand = requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string; int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn, DataRowVersion.Current]; string collectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string; if ((restrictions != null) && (restrictions.Length > numberOfRestrictions)) { throw ADP.TooManyRestrictions(collectionName); } command = connection.CreateCommand(); command.CommandText = sqlCommand; command.CommandTimeout = Math.Max(command.CommandTimeout, 180); for (int i = 0; i < numberOfRestrictions; i++) { DbParameter restrictionParameter = command.CreateParameter(); if ((restrictions != null) && (restrictions.Length > i) && (restrictions[i] != null)) { restrictionParameter.Value = restrictions[i]; } else { // This is where we have to assign null to the value of the parameter. restrictionParameter.Value = DBNull.Value; } restrictionParameter.ParameterName = GetParameterName(collectionName, i + 1); restrictionParameter.Direction = ParameterDirection.Input; command.Parameters.Add(restrictionParameter); } DbDataReader reader = null; try { try { reader = command.ExecuteReader(); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } throw ADP.QueryFailed(collectionName, e); } // Build a DataTable from the reader resultTable = new DataTable(collectionName) { Locale = CultureInfo.InvariantCulture }; schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"]); } object[] values = new object[resultTable.Columns.Count]; while (reader.Read()) { reader.GetValues(values); resultTable.Rows.Add(values); } } finally { if (reader != null) { reader.Dispose(); reader = null; } } return resultTable; } private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns) { int columnCount = 0; foreach (DataColumn sourceColumn in sourceTable.Columns) { if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true) { columnCount++; } } if (columnCount == 0) { throw ADP.NoColumns(); } int currentColumn = 0; DataColumn[] filteredSourceColumns = new DataColumn[columnCount]; foreach (DataColumn sourceColumn in sourceTable.Columns) { if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true) { DataColumn newDestinationColumn = new DataColumn(sourceColumn.ColumnName, sourceColumn.DataType); destinationColumns.Add(newDestinationColumn); filteredSourceColumns[currentColumn] = sourceColumn; currentColumn++; } } return filteredSourceColumns; } internal DataRow FindMetaDataCollectionRow(string collectionName) { bool versionFailure; bool haveExactMatch; bool haveMultipleInexactMatches; string candidateCollectionName; DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; if (metaDataCollectionsTable == null) { throw ADP.InvalidXml(); } DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; if ((null == collectionNameColumn) || (typeof(string) != collectionNameColumn.DataType)) { throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName); } DataRow requestedCollectionRow = null; string exactCollectionName = null; // find the requested collection versionFailure = false; haveExactMatch = false; haveMultipleInexactMatches = false; foreach (DataRow row in metaDataCollectionsTable.Rows) { candidateCollectionName = row[collectionNameColumn, DataRowVersion.Current] as string; if (string.IsNullOrEmpty(candidateCollectionName)) { throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName); } if (ADP.CompareInsensitiveInvariant(candidateCollectionName, collectionName)) { if (SupportedByCurrentVersion(row) == false) { versionFailure = true; } else { if (collectionName == candidateCollectionName) { if (haveExactMatch == true) { throw ADP.CollectionNameIsNotUnique(collectionName); } requestedCollectionRow = row; exactCollectionName = candidateCollectionName; haveExactMatch = true; } else { // have an inexact match - ok only if it is the only one if (exactCollectionName != null) { // can't fail here becasue we may still find an exact match haveMultipleInexactMatches = true; } requestedCollectionRow = row; exactCollectionName = candidateCollectionName; } } } } if (requestedCollectionRow == null) { if (versionFailure == false) { throw ADP.UndefinedCollection(collectionName); } else { throw ADP.UnsupportedVersion(collectionName); } } if ((haveExactMatch == false) && (haveMultipleInexactMatches == true)) { throw ADP.AmbigousCollectionName(collectionName); } return requestedCollectionRow; } private void FixUpVersion(DataTable dataSourceInfoTable) { Debug.Assert(dataSourceInfoTable.TableName == DbMetaDataCollectionNames.DataSourceInformation); DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion]; DataColumn normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized]; if ((versionColumn == null) || (normalizedVersionColumn == null)) { throw ADP.MissingDataSourceInformationColumn(); } if (dataSourceInfoTable.Rows.Count != 1) { throw ADP.IncorrectNumberOfDataSourceInformationRows(); } DataRow dataSourceInfoRow = dataSourceInfoTable.Rows[0]; dataSourceInfoRow[versionColumn] = _serverVersionString; dataSourceInfoRow[normalizedVersionColumn] = _normalizedServerVersion; dataSourceInfoRow.AcceptChanges(); } private string GetParameterName(string neededCollectionName, int neededRestrictionNumber) { DataTable restrictionsTable = null; DataColumnCollection restrictionColumns = null; DataColumn collectionName = null; DataColumn parameterName = null; DataColumn restrictionName = null; DataColumn restrictionNumber = null; string result = null; restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; if (restrictionsTable != null) { restrictionColumns = restrictionsTable.Columns; if (restrictionColumns != null) { collectionName = restrictionColumns[_collectionName]; parameterName = restrictionColumns[_parameterName]; restrictionName = restrictionColumns[_restrictionName]; restrictionNumber = restrictionColumns[_restrictionNumber]; } } if ((parameterName == null) || (collectionName == null) || (restrictionName == null) || (restrictionNumber == null)) { throw ADP.MissingRestrictionColumn(); } foreach (DataRow restriction in restrictionsTable.Rows) { if (((string)restriction[collectionName] == neededCollectionName) && ((int)restriction[restrictionNumber] == neededRestrictionNumber) && (SupportedByCurrentVersion(restriction))) { result = (string)restriction[parameterName]; break; } } if (result == null) { throw ADP.MissingRestrictionRow(); } return result; } public virtual DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions) { Debug.Assert(_metaDataCollectionsDataSet != null); DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]; DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]; DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]; DataRow requestedCollectionRow = null; DataTable requestedSchema = null; string[] hiddenColumns; string exactCollectionName = null; requestedCollectionRow = FindMetaDataCollectionRow(collectionName); exactCollectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string; if (ADP.IsEmptyArray(restrictions) == false) { for (int i = 0; i < restrictions.Length; i++) { if ((restrictions[i] != null) && (restrictions[i].Length > 4096)) { // use a non-specific error because no new beta 2 error messages are allowed // TODO: will add a more descriptive error in RTM throw ADP.NotSupported(); } } } string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string; switch (populationMechanism) { case _dataTable: if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections) { hiddenColumns = new string[2]; hiddenColumns[0] = _populationMechanism; hiddenColumns[1] = _populationString; } else { hiddenColumns = null; } // none of the datatable collections support restrictions if (ADP.IsEmptyArray(restrictions) == false) { throw ADP.TooManyRestrictions(exactCollectionName); } requestedSchema = CloneAndFilterCollection(exactCollectionName, hiddenColumns); // TODO: Consider an alternate method that doesn't involve special casing -- perhaps _prepareCollection // for the data source infomation table we need to fix up the version columns at run time // since the version is determined at run time if (exactCollectionName == DbMetaDataCollectionNames.DataSourceInformation) { FixUpVersion(requestedSchema); } break; case _sqlCommand: requestedSchema = ExecuteCommand(requestedCollectionRow, restrictions, connection); break; case _prepareCollection: requestedSchema = PrepareCollection(exactCollectionName, restrictions, connection); break; default: throw ADP.UndefinedPopulationMechanism(populationMechanism); } return requestedSchema; } private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames) { bool result = true; string sourceColumnName = sourceColumn.ColumnName; switch (sourceColumnName) { case _minimumVersion: case _maximumVersion: result = false; break; default: if (hiddenColumnNames == null) { break; } for (int i = 0; i < hiddenColumnNames.Length; i++) { if (hiddenColumnNames[i] == sourceColumnName) { result = false; break; } } break; } return result; } private void LoadDataSetFromXml(Stream XmlStream) { _metaDataCollectionsDataSet = new DataSet(); _metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture; _metaDataCollectionsDataSet.ReadXml(XmlStream); } protected virtual DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection) { throw ADP.NotSupported(); } private bool SupportedByCurrentVersion(DataRow requestedCollectionRow) { bool result = true; DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns; DataColumn versionColumn; object version; // check the minimum version first versionColumn = tableColumns[_minimumVersion]; if (versionColumn != null) { version = requestedCollectionRow[versionColumn]; if (version != null) { if (version != DBNull.Value) { if (0 > string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase)) { result = false; } } } } // if the minmum version was ok what about the maximum version if (result == true) { versionColumn = tableColumns[_maximumVersion]; if (versionColumn != null) { version = requestedCollectionRow[versionColumn]; if (version != null) { if (version != DBNull.Value) { if (0 < string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase)) { result = false; } } } } } return result; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays.Settings; using osu.Game.Rulesets; using osu.Game.Tournament.Components; using osu.Game.Tournament.Models; using osuTK; namespace osu.Game.Tournament.Screens.Editors { public class SeedingEditorScreen : TournamentEditorScreen<SeedingEditorScreen.SeedingResultRow, SeedingResult> { private readonly TournamentTeam team; protected override BindableList<SeedingResult> Storage => team.SeedingResults; [Resolved(canBeNull: true)] private TournamentSceneManager sceneManager { get; set; } public SeedingEditorScreen(TournamentTeam team, TournamentScreen parentScreen) : base(parentScreen) { this.team = team; } public class SeedingResultRow : CompositeDrawable, IModelBacked<SeedingResult> { public SeedingResult Model { get; } [Resolved] private LadderInfo ladderInfo { get; set; } public SeedingResultRow(TournamentTeam team, SeedingResult round) { Model = round; Masking = true; CornerRadius = 10; SeedingBeatmapEditor beatmapEditor = new SeedingBeatmapEditor(round) { Width = 0.95f }; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.1f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Full, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SettingsTextBox { LabelText = "Mod", Width = 0.33f, Current = Model.Mod }, new SettingsSlider<int> { LabelText = "Seed", Width = 0.33f, Current = Model.Seed }, new SettingsButton { Width = 0.2f, Margin = new MarginPadding(10), Text = "Add beatmap", Action = () => beatmapEditor.CreateNew() }, beatmapEditor } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete result", Action = () => { Expire(); team.SeedingResults.Remove(Model); }, } }; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } public class SeedingBeatmapEditor : CompositeDrawable { private readonly SeedingResult round; private readonly FillFlowContainer flow; public SeedingBeatmapEditor(SeedingResult round) { this.round = round; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = flow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, ChildrenEnumerable = round.Beatmaps.Select(p => new SeedingBeatmapRow(round, p)) }; } public void CreateNew() { var user = new SeedingBeatmap(); round.Beatmaps.Add(user); flow.Add(new SeedingBeatmapRow(round, user)); } public class SeedingBeatmapRow : CompositeDrawable { private readonly SeedingResult result; public SeedingBeatmap Model { get; } [Resolved] protected IAPIProvider API { get; private set; } private readonly Bindable<int?> beatmapId = new Bindable<int?>(); private readonly Bindable<string> score = new Bindable<string>(string.Empty); private readonly Container drawableContainer; public SeedingBeatmapRow(SeedingResult result, SeedingBeatmap beatmap) { this.result = result; Model = beatmap; Margin = new MarginPadding(10); RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.2f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsNumberBox { LabelText = "Beatmap ID", RelativeSizeAxes = Axes.None, Width = 200, Current = beatmapId, }, new SettingsSlider<int> { LabelText = "Seed", RelativeSizeAxes = Axes.None, Width = 200, Current = beatmap.Seed }, new SettingsTextBox { LabelText = "Score", RelativeSizeAxes = Axes.None, Width = 200, Current = score, }, drawableContainer = new Container { Size = new Vector2(100, 70), }, } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Beatmap", Action = () => { Expire(); result.Beatmaps.Remove(beatmap); }, } }; } [BackgroundDependencyLoader] private void load(RulesetStore rulesets) { beatmapId.Value = Model.ID; beatmapId.BindValueChanged(id => { Model.ID = id.NewValue ?? 0; if (id.NewValue != id.OldValue) Model.Beatmap = null; if (Model.Beatmap != null) { updatePanel(); return; } var req = new GetBeatmapRequest(new APIBeatmap { OnlineID = Model.ID }); req.Success += res => { Model.Beatmap = res; updatePanel(); }; req.Failure += _ => { Model.Beatmap = null; updatePanel(); }; API.Queue(req); }, true); score.Value = Model.Score.ToString(); score.BindValueChanged(str => long.TryParse(str.NewValue, out Model.Score)); } private void updatePanel() { drawableContainer.Clear(); if (Model.Beatmap != null) { drawableContainer.Child = new TournamentBeatmapPanel(Model.Beatmap, result.Mod.Value) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 300 }; } } } } } protected override SeedingResultRow CreateDrawable(SeedingResult model) => new SeedingResultRow(team, model); } }
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; using SharpMath.LinearAlgebra; namespace SharpMath.Optimization.DualNumbers { /// <summary> /// Provides the same static methods as the <see cref="LUDecomposition"/> class but in <see cref="DualNumber "/> versions, /// i.e. the inverse and the determinant may be computed with gradients and Hessians. Direct computation is used for low /// dimensions (less than three). /// </summary> public static class DualLUDecomposition { public static DualMatrix Inverse(DualMatrix matrix) { int m = matrix.Rows; if (matrix.Columns != m) { throw new ArgumentException("The matrix isn't a square matrix."); } if (m <= 3) { DualNumber determinant = DeterminantDirect(m, matrix); return InverseDirect(m, matrix, determinant); } int n = GradientLength(m, matrix); return Inverse(matrix, m, n, LUDecomposition.Inverse(matrix.GetValues())); } public static DualNumber Determinant(DualMatrix matrix) { int m = matrix.Rows; if (matrix.Columns != m) { throw new ArgumentException("The matrix isn't a square matrix."); } if (m <= 3) { return DeterminantDirect(m, matrix); } int n = GradientLength(m, matrix); LUDecomposition lu = LUDecomposition.Decompose(matrix.GetValues()); return Determinant(matrix, m, n, lu.Inverse(), lu.Determinant()); } /// <summary> /// This method saves some time if both the inverse and the determinant is needed by only having to compute /// the inverse once. /// </summary> public static void InverseDeterminant(DualMatrix matrix, out DualMatrix inverse, out DualNumber determinant) { int m = matrix.Rows; if (matrix.Columns != m) { throw new ArgumentException("The matrix isn't a square matrix."); } if (m <= 3) { // The naive implementation seems to be faster (for all values of n). Maybe it's // faster to perform the LU decomposition directly on the DualNumbers? determinant = DeterminantDirect(m, matrix); inverse = InverseDirect(m, matrix, determinant); return; } int n = GradientLength(m, matrix); LUDecomposition lu = LUDecomposition.Decompose(matrix.GetValues()); Matrix inverse0 = lu.Inverse(); double determinant0 = lu.Determinant(); inverse = Inverse(matrix, m, n, inverse0); determinant = Determinant(matrix, m, n, inverse0, determinant0); } private static DualMatrix Inverse(DualMatrix matrix, int m, int n, Matrix inverse) { if (n < 0) { // Return a matrix without derivatives information (using the implicit matrix conversion). return inverse; } double[,][] gradientArrays = new double[m, m][]; // Compute all gradients in the first loop. These are used to compute the Hessian. for (int i0 = 0; i0 < m; i0++) { for (int j0 = 0; j0 < m; j0++) { double[] gradientArray = new double[n]; for (int i = 0; i < n; i++) { // Formula (36) in The Matrix Cookbook. double s = 0.0; for (int k = 0; k < m; k++) { for (int l = 0; l < m; l++) { s += inverse[i0, k] * matrix[k, l].Gradient[i] * inverse[l, j0]; } } gradientArray[i] = -s; } gradientArrays[i0, j0] = gradientArray; } } // Compute Hessians and DualNumber instances. DualNumber[,] a = new DualNumber[m, m]; for (int i0 = 0; i0 < m; i0++) { for (int j0 = 0; j0 < m; j0++) { double[] hessianArray = new double[n * (n + 1) / 2]; for (int i = 0, h = 0; i < n; i++) { for (int j = i; j < n; j++, h++) { double s = 0.0; for (int k = 0; k < m; k++) { for (int l = 0; l < m; l++) { s += gradientArrays[i0, k][i] * matrix[k, l].Gradient[j] * inverse[l, j0] + inverse[i0, k] * matrix[k, l].Gradient[h] * inverse[l, j0] + inverse[i0, k] * matrix[k, l].Gradient[j] * gradientArrays[l, j0][i]; } } hessianArray[h] = -s; } } a[i0, j0] = new DualNumber(inverse[i0, j0], gradientArrays[i0, j0], hessianArray); } } return new DualMatrix(a); } private static DualNumber Determinant(DualMatrix matrix, int m, int n, Matrix inverse, double determinant) { if (n < 0) { return determinant; } // Compute the gradient in the first loop (not scaled by the determinant yet). // These are used to compute the Hessian. double[] gradientArray = new double[n]; for (int i = 0; i < n; i++) { // Formula (41) in The Matrix Cookbook. double s = 0.0; for (int k = 0; k < m; k++) { for (int l = 0; l < m; l++) { s += inverse[k, l] * matrix[l, k].Gradient[i]; } } gradientArray[i] = s; } // Compute the Hessian. double[] hessianArray = new double[n * (n + 1) / 2]; for (int i = 0, h = 0; i < n; i++) { for (int j = i; j < n; j++, h++) { // Formula (42) in The Matrix Cookbook. Also works when taking partial derivatives // with respect to two different variables. double s = 0.0; for (int k = 0; k < m; k++) { for (int l = 0; l < m; l++) { double si = 0.0; double sj = 0.0; for (int q = 0; q < m; q++) { si += inverse[k, q] * matrix[q, l].Gradient[i]; sj += inverse[l, q] * matrix[q, k].Gradient[j]; } s += inverse[k, l] * matrix[l, k].Hessian[i, j] - si * sj; } } hessianArray[h] = determinant * (gradientArray[i] * gradientArray[j] + s); } // Final scaling of the gradient. This index is not used anymore in the loop. gradientArray[i] *= determinant; } // Finally create the DualNumber instance. return new DualNumber(determinant, gradientArray, hessianArray); } private static DualNumber DeterminantDirect(int m, DualMatrix matrix) { if (m == 1) { DualNumber a11 = matrix[0, 0]; return a11; } else if (m == 2) { DualNumber a11 = matrix[0, 0]; DualNumber a12 = matrix[0, 1]; DualNumber a21 = matrix[1, 0]; DualNumber a22 = matrix[1, 1]; return a11 * a22 - a12 * a21; } else if (m == 3) { DualNumber a11 = matrix[0, 0]; DualNumber a12 = matrix[0, 1]; DualNumber a13 = matrix[0, 2]; DualNumber a21 = matrix[1, 0]; DualNumber a22 = matrix[1, 1]; DualNumber a23 = matrix[1, 2]; DualNumber a31 = matrix[2, 0]; DualNumber a32 = matrix[2, 1]; DualNumber a33 = matrix[2, 2]; return a11 * a22 * a33 + a12 * a23 * a31 + a13 * a21 * a32 - a11 * a23 * a32 - a12 * a21 * a33 - a13 * a22 * a31; } else { throw new NotImplementedException(); } } private static DualMatrix InverseDirect(int m, DualMatrix matrix, DualNumber determinant) { if (m == 1) { DualNumber a11 = matrix[0, 0]; return new DualMatrix(new DualNumber[,] { { 1.0 / a11 } }); } else if (m == 2) { DualNumber a11 = matrix[0, 0]; DualNumber a12 = matrix[0, 1]; DualNumber a21 = matrix[1, 0]; DualNumber a22 = matrix[1, 1]; return new DualMatrix(new DualNumber[,] { { a22 / determinant, -a12 / determinant }, { -a21 / determinant, a11 / determinant } }); } else if (m == 3) { DualNumber a11 = matrix[0, 0]; DualNumber a12 = matrix[0, 1]; DualNumber a13 = matrix[0, 2]; DualNumber a21 = matrix[1, 0]; DualNumber a22 = matrix[1, 1]; DualNumber a23 = matrix[1, 2]; DualNumber a31 = matrix[2, 0]; DualNumber a32 = matrix[2, 1]; DualNumber a33 = matrix[2, 2]; // Using http://mathworld.wolfram.com/MatrixInverse.html. return new DualMatrix(new DualNumber[,] { { (a22 * a33 - a23 * a32) / determinant, (a13 * a32 - a12 * a33) / determinant, (a12 * a23 - a13 * a22) / determinant }, { (a23 * a31 - a21 * a33) / determinant, (a11 * a33 - a13 * a31) / determinant, (a13 * a21 - a11 * a23) / determinant }, { (a21 * a32 - a22 * a31) / determinant, (a12 * a31 - a11 * a32) / determinant, (a11 * a22 - a12 * a21) / determinant } }); } else { throw new NotImplementedException(); } } private static int GradientLength(int m, DualMatrix matrix) { int n = -1; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { Vector gradient = matrix[i, j].Gradient; if (gradient != null) { if (n != -1 && gradient.Length != n) { throw new ArgumentException("Inconsistent number of derivatives."); } n = gradient.Length; } } } return n; } } }
// 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.Diagnostics.CodeAnalysis; using System.Runtime.ConstrainedExecution; using System.Threading; namespace System.Runtime.InteropServices { // This implementation does not employ critical execution regions and thus cannot // reliably guarantee handle release in the face of thread aborts. /// <summary>Represents a wrapper class for operating system handles.</summary> public abstract partial class SafeHandle : CriticalFinalizerObject, IDisposable { // IMPORTANT: // - Do not add or rearrange fields as the EE depends on this layout, // as well as on the values of the StateBits flags. // - The EE may also perform the same operations using equivalent native // code, so this managed code must not assume it is the only code // manipulating _state. /// <summary>Specifies the handle to be wrapped.</summary> [SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] protected IntPtr handle; /// <summary>Combined ref count and closed/disposed flags (so we can atomically modify them).</summary> private volatile int _state; /// <summary>Whether we can release this handle.</summary> private readonly bool _ownsHandle; /// <summary>Whether constructor completed.</summary> private volatile bool _fullyInitialized; /// <summary>Bitmasks for the <see cref="_state"/> field.</summary> /// <remarks> /// The state field ends up looking like this: /// /// 31 2 1 0 /// +-----------------------------------------------------------+---+---+ /// | Ref count | D | C | /// +-----------------------------------------------------------+---+---+ /// /// Where D = 1 means a Dispose has been performed and C = 1 means the /// underlying handle has been (or will be shortly) released. /// </remarks> private static class StateBits { public const int Closed = 0b01; public const int Disposed = 0b10; public const int RefCount = unchecked(~0b11); // 2 bits reserved for closed/disposed; ref count gets 30 bits public const int RefCountOne = 1 << 2; }; /// <summary>Creates a SafeHandle class.</summary> protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle) { handle = invalidHandleValue; _state = StateBits.RefCountOne; // Ref count 1 and not closed or disposed. _ownsHandle = ownsHandle; if (!ownsHandle) { GC.SuppressFinalize(this); } _fullyInitialized = true; } #if !CORERT // CoreRT doesn't correctly support CriticalFinalizerObject ~SafeHandle() { if (_fullyInitialized) { Dispose(disposing: false); } } #endif protected void SetHandle(IntPtr handle) => this.handle = handle; public IntPtr DangerousGetHandle() => handle; public bool IsClosed => (_state & StateBits.Closed) == StateBits.Closed; public abstract bool IsInvalid { get; } public void Close() => Dispose(); public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Debug.Assert(_fullyInitialized); InternalRelease(disposeOrFinalizeOperation: true); } public void SetHandleAsInvalid() { Debug.Assert(_fullyInitialized); // Attempt to set closed state (low order bit of the _state field). // Might have to attempt these repeatedly, if the operation suffers // interference from an AddRef or Release. int oldState, newState; do { oldState = _state; newState = oldState | StateBits.Closed; } while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState); GC.SuppressFinalize(this); } protected abstract bool ReleaseHandle(); public void DangerousAddRef(ref bool success) { // To prevent handle recycling security attacks we must enforce the // following invariant: we cannot successfully AddRef a handle on which // we've committed to the process of releasing. // We ensure this by never AddRef'ing a handle that is marked closed and // never marking a handle as closed while the ref count is non-zero. For // this to be thread safe we must perform inspection/updates of the two // values as a single atomic operation. We achieve this by storing them both // in a single aligned int and modifying the entire state via interlocked // compare exchange operations. // Additionally we have to deal with the problem of the Dispose operation. // We must assume that this operation is directly exposed to untrusted // callers and that malicious callers will try and use what is basically a // Release call to decrement the ref count to zero and free the handle while // it's still in use (the other way a handle recycling attack can be // mounted). We combat this by allowing only one Dispose to operate against // a given safe handle (which balances the creation operation given that // Dispose suppresses finalization). We record the fact that a Dispose has // been requested in the same state field as the ref count and closed state. Debug.Assert(_fullyInitialized); // Might have to perform the following steps multiple times due to // interference from other AddRef's and Release's. int oldState, newState; do { // First step is to read the current handle state. We use this as a // basis to decide whether an AddRef is legal and, if so, to propose an // update predicated on the initial state (a conditional write). // Check for closed state. oldState = _state; if ((oldState & StateBits.Closed) != 0) { throw new ObjectDisposedException(nameof(SafeHandle), SR.ObjectDisposed_SafeHandleClosed); } // Not closed, let's propose an update (to the ref count, just add // StateBits.RefCountOne to the state to effectively add 1 to the ref count). // Continue doing this until the update succeeds (because nobody // modifies the state field between the read and write operations) or // the state moves to closed. newState = oldState + StateBits.RefCountOne; } while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState); // If we got here we managed to update the ref count while the state // remained non closed. So we're done. success = true; } public void DangerousRelease() => InternalRelease(disposeOrFinalizeOperation: false); private void InternalRelease(bool disposeOrFinalizeOperation) { Debug.Assert(_fullyInitialized || disposeOrFinalizeOperation); // See AddRef above for the design of the synchronization here. Basically we // will try to decrement the current ref count and, if that would take us to // zero refs, set the closed state on the handle as well. bool performRelease = false; // Might have to perform the following steps multiple times due to // interference from other AddRef's and Release's. int oldState, newState; do { // First step is to read the current handle state. We use this cached // value to predicate any modification we might decide to make to the // state). oldState = _state; // If this is a Dispose operation we have additional requirements (to // ensure that Dispose happens at most once as the comments in AddRef // detail). We must check that the dispose bit is not set in the old // state and, in the case of successful state update, leave the disposed // bit set. Silently do nothing if Dispose has already been called. if (disposeOrFinalizeOperation && ((oldState & StateBits.Disposed) != 0)) { return; } // We should never see a ref count of zero (that would imply we have // unbalanced AddRef and Releases). (We might see a closed state before // hitting zero though -- that can happen if SetHandleAsInvalid is // used). if ((oldState & StateBits.RefCount) == 0) { throw new ObjectDisposedException(nameof(SafeHandle), SR.ObjectDisposed_SafeHandleClosed); } // If we're proposing a decrement to zero and the handle is not closed // and we own the handle then we need to release the handle upon a // successful state update. If so we need to check whether the handle is // currently invalid by asking the SafeHandle subclass. We must do this before // transitioning the handle to closed, however, since setting the closed // state will cause IsInvalid to always return true. performRelease = ((oldState & (StateBits.RefCount | StateBits.Closed)) == StateBits.RefCountOne) && _ownsHandle && !IsInvalid; // Attempt the update to the new state, fail and retry if the initial // state has been modified in the meantime. Decrement the ref count by // substracting StateBits.RefCountOne from the state then OR in the bits for // Dispose (if that's the reason for the Release) and closed (if the // initial ref count was 1). newState = oldState - StateBits.RefCountOne; if ((oldState & StateBits.RefCount) == StateBits.RefCountOne) { newState |= StateBits.Closed; } if (disposeOrFinalizeOperation) { newState |= StateBits.Disposed; } } while (Interlocked.CompareExchange(ref _state, newState, oldState) != oldState); // If we get here we successfully decremented the ref count. Additionally we // may have decremented it to zero and set the handle state as closed. In // this case (providng we own the handle) we will call the ReleaseHandle // method on the SafeHandle subclass. if (performRelease) { // Save last error from P/Invoke in case the implementation of ReleaseHandle // trashes it (important because this ReleaseHandle could occur implicitly // as part of unmarshaling another P/Invoke). int lastError = Marshal.GetLastWin32Error(); ReleaseHandle(); Marshal.SetLastWin32Error(lastError); } } } }
using System; using System.Reflection; using System.Web; using System.Web.UI; using Umbraco.Core; namespace umbraco.BusinessLogic { /// <summary> /// The StateHelper class provides general helper methods for handling sessions, context, viewstate and cookies. /// </summary> [Obsolete("DO NOT USE THIS ANYMORE! REPLACE ALL CALLS WITH NEW EXTENSION METHODS")] public class StateHelper { private static HttpContextBase _customHttpContext; /// <summary> /// Gets/sets the HttpContext object, this is generally used for unit testing. By default this will /// use the HttpContext.Current /// </summary> internal static HttpContextBase HttpContext { get { if (_customHttpContext == null && System.Web.HttpContext.Current != null) { //return the current HttpContxt, do NOT store this in the _customHttpContext field //as it will persist across reqeusts! return new HttpContextWrapper(System.Web.HttpContext.Current); } if (_customHttpContext == null && System.Web.HttpContext.Current == null) { throw new NullReferenceException("The HttpContext property has not been set or the object execution is not running inside of an HttpContext"); } return _customHttpContext; } set { _customHttpContext = value; } } #region Session Helpers /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetSessionValue<T>(string key) { return GetSessionValue<T>(HttpContext, key); } /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> [Obsolete("Use the GetSessionValue accepting an HttpContextBase instead")] public static T GetSessionValue<T>(HttpContext context, string key) { return GetSessionValue<T>(new HttpContextWrapper(context), key); } /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetSessionValue<T>(HttpContextBase context, string key) { if (context == null) return default(T); object o = context.Session[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets a session value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetSessionValue(string key, object value) { SetSessionValue(HttpContext, key, value); } /// <summary> /// Sets the session value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [Obsolete("Use the SetSessionValue accepting an HttpContextBase instead")] public static void SetSessionValue(HttpContext context, string key, object value) { SetSessionValue(new HttpContextWrapper(context), key, value); } /// <summary> /// Sets the session value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetSessionValue(HttpContextBase context, string key, object value) { if (context == null) return; context.Session[key] = value; } #endregion #region Context Helpers /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetContextValue<T>(string key) { return GetContextValue<T>(HttpContext, key); } /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> [Obsolete("Use the GetContextValue accepting an HttpContextBase instead")] public static T GetContextValue<T>(HttpContext context, string key) { return GetContextValue<T>(new HttpContextWrapper(context), key); } /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetContextValue<T>(HttpContextBase context, string key) { if (context == null) return default(T); object o = context.Items[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets the context value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetContextValue(string key, object value) { SetContextValue(HttpContext, key, value); } /// <summary> /// Sets the context value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [Obsolete("Use the SetContextValue accepting an HttpContextBase instead")] public static void SetContextValue(HttpContext context, string key, object value) { SetContextValue(new HttpContextWrapper(context), key, value); } /// <summary> /// Sets the context value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetContextValue(HttpContextBase context, string key, object value) { if (context == null) return; context.Items[key] = value; } #endregion #region ViewState Helpers /// <summary> /// Gets the state bag. /// </summary> /// <returns></returns> private static StateBag GetStateBag() { //if (HttpContext.Current == null) // return null; var page = HttpContext.CurrentHandler as Page; if (page == null) return null; var pageType = typeof(Page); var viewState = pageType.GetProperty("ViewState", BindingFlags.GetProperty | BindingFlags.Instance); if (viewState == null) return null; return viewState.GetValue(page, null) as StateBag; } /// <summary> /// Gets the view state value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetViewStateValue<T>(string key) { return GetViewStateValue<T>(GetStateBag(), key); } /// <summary> /// Gets a view-state value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bag">The bag.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetViewStateValue<T>(StateBag bag, string key) { if (bag == null) return default(T); object o = bag[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets the view state value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetViewStateValue(string key, object value) { SetViewStateValue(GetStateBag(), key, value); } /// <summary> /// Sets the view state value. /// </summary> /// <param name="bag">The bag.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetViewStateValue(StateBag bag, string key, object value) { if (bag != null) bag[key] = value; } #endregion #region Cookie Helpers /// <summary> /// Determines whether a cookie has a value with a specified key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the cookie has a value with the specified key; otherwise, <c>false</c>. /// </returns> [Obsolete("Use !string.IsNullOrEmpty(GetCookieValue(key))", false)] public static bool HasCookieValue(string key) { return !string.IsNullOrEmpty(GetCookieValue(key)); } /// <summary> /// Gets the cookie value. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public static string GetCookieValue(string key) { if (!Cookies.HasCookies) return null; var cookie = HttpContext.Request.Cookies[key]; return cookie == null ? null : cookie.Value; } /// <summary> /// Sets the cookie value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetCookieValue(string key, string value) { SetCookieValue(key, value, 30d); // default Umbraco expires is 30 days } /// <summary> /// Sets the cookie value including the number of days to persist the cookie /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="daysToPersist">How long the cookie should be present in the browser</param> public static void SetCookieValue(string key, string value, double daysToPersist) { if (!Cookies.HasCookies) return; var context = HttpContext; HttpCookie cookie = new HttpCookie(key, value); cookie.Expires = DateTime.Now.AddDays(daysToPersist); context.Response.Cookies.Set(cookie); cookie = context.Request.Cookies[key]; if (cookie != null) cookie.Value = value; } // zb-00004 #29956 : refactor cookies names & handling public static class Cookies { /* * helper class to manage cookies * * beware! SetValue(string value) does _not_ set expires, unless the cookie has been * configured to have one. This allows us to have cookies w/out an expires timespan. * However, default behavior in Umbraco was to set expires to 30days by default. This * must now be managed in the Cookie constructor or by using an overriden SetValue(...). * * we currently reproduce this by configuring each cookie with a 30d expires, but does * that actually make sense? shouldn't some cookie have _no_ expires? */ static readonly Cookie _preview = new Cookie(Constants.Web.PreviewCookieName, TimeSpan.Zero); // was "PreviewSet" static readonly Cookie _userContext = new Cookie(Constants.Web.AuthCookieName, 30d); // was "UserContext" static readonly Cookie _member = new Cookie("UMB_MEMBER", 30d); // was "umbracoMember" public static Cookie Preview { get { return _preview; } } public static Cookie UserContext { get { return _userContext; } } public static Cookie Member { get { return _member; } } public static bool HasCookies { get { var context = HttpContext; // although just checking context should be enough?! // but in some (replaced) umbraco code, everything is checked... return context != null && context.Request != null & context.Request.Cookies != null && context.Response != null && context.Response.Cookies != null; } } public static void ClearAll() { HttpContext.Response.Cookies.Clear(); } public class Cookie { const string cookiesExtensionConfigKey = "umbracoCookiesExtension"; static readonly string _ext; TimeSpan _expires; string _key; static Cookie() { var appSettings = System.Configuration.ConfigurationManager.AppSettings; _ext = appSettings[cookiesExtensionConfigKey] == null ? "" : "_" + (string)appSettings[cookiesExtensionConfigKey]; } public Cookie(string key) : this(key, TimeSpan.Zero, true) { } public Cookie(string key, double days) : this(key, TimeSpan.FromDays(days), true) { } public Cookie(string key, TimeSpan expires) : this(key, expires, true) { } public Cookie(string key, bool appendExtension) : this(key, TimeSpan.Zero, appendExtension) { } public Cookie(string key, double days, bool appendExtension) : this(key, TimeSpan.FromDays(days), appendExtension) { } public Cookie(string key, TimeSpan expires, bool appendExtension) { _key = appendExtension ? key + _ext : key; _expires = expires; } public string Key { get { return _key; } } public bool HasValue { get { return RequestCookie != null; } } public string GetValue() { return RequestCookie == null ? null : RequestCookie.Value; } public void SetValue(string value) { SetValueWithDate(value, _expires == TimeSpan.Zero ? DateTime.MinValue : DateTime.Now + _expires); } public void SetValue(string value, double days) { SetValue(value, DateTime.Now.AddDays(days)); } public void SetValue(string value, TimeSpan expires) { SetValue(value, expires == TimeSpan.Zero ? DateTime.MinValue : DateTime.Now + expires); } public void SetValue(string value, DateTime expires) { SetValueWithDate(value, expires); } private void SetValueWithDate(string value, DateTime expires) { var cookie = new HttpCookie(_key, value); if (GlobalSettings.UseSSL) cookie.Secure = true; //ensure http only, this should only be able to be accessed via the server cookie.HttpOnly = true; //set an expiry date if not min value, otherwise leave it as a session cookie. if (expires != DateTime.MinValue) { cookie.Expires = expires; } ResponseCookie = cookie; // original Umbraco code also does this // so we can GetValue() back what we previously set cookie = RequestCookie; if (cookie != null) cookie.Value = value; } public void Clear() { if (RequestCookie != null || ResponseCookie != null) { var cookie = new HttpCookie(_key); cookie.Expires = DateTime.Now.AddDays(-1); ResponseCookie = cookie; } } public void Remove() { // beware! will not clear browser's cookie // you probably want to use .Clear() HttpContext.Response.Cookies.Remove(_key); } public HttpCookie RequestCookie { get { return HttpContext.Request.Cookies[_key]; } } public HttpCookie ResponseCookie { get { return HttpContext.Response.Cookies[_key]; } set { // .Set() ensures the uniqueness of cookies in the cookie collection // ie it is the same as .Remove() + .Add() -- .Add() allows duplicates HttpContext.Response.Cookies.Set(value); } } } } #endregion } }
using System.Collections.Generic; using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.PublishedCache; using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; using Umbraco.Cms.Infrastructure.Serialization; using Umbraco.Cms.Tests.Common.Builders; using Umbraco.Cms.Tests.Common.Builders.Extensions; using Umbraco.Cms.Tests.UnitTests.TestHelpers; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.PublishedCache { /// <summary> /// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore /// </summary> [TestFixture] public class PublishedMediaTests : PublishedSnapshotServiceTestBase { [SetUp] public override void Setup() { base.Setup(); var dataTypes = GetDefaultDataTypes().ToList(); var serializer = new ConfigurationEditorJsonSerializer(); var rteDataType = new DataType(new VoidEditor("RTE", Mock.Of<IDataValueEditorFactory>()), serializer) { Id = 4 }; dataTypes.Add(rteDataType); _dataTypes = dataTypes.ToArray(); _propertyDataTypes = new() { // defaults will just use the first one [string.Empty] = _dataTypes[0], // content uses the RTE ["content"] = _dataTypes[1] }; } private Dictionary<string, IDataType> _propertyDataTypes; private DataType[] _dataTypes; private ContentNodeKit CreateRoot(out MediaType mediaType) { mediaType = new MediaType(ShortStringHelper, -1); ContentData item1Data = new ContentDataBuilder() .WithName("Content 1") .WithProperties(new PropertyDataBuilder() .WithPropertyData("content", "<div>This is some content</div>") .Build()) // build with a dynamically created media type .Build(ShortStringHelper, _propertyDataTypes, mediaType, "image2"); ContentNodeKit item1 = ContentNodeKitBuilder.CreateWithContent( mediaType.Id, 1, "-1,1", draftData: item1Data, publishedData: item1Data); return item1; } private IEnumerable<ContentNodeKit> CreateChildren( int startId, ContentNodeKit parent, IMediaType mediaType, int count) { for (int i = 0; i < count; i++) { var id = startId + i + 1; ContentData item1Data = new ContentDataBuilder() .WithName("Child " + id) .WithProperties(new PropertyDataBuilder() .WithPropertyData("content", "<div>This is some content</div>") .Build()) .Build(); var parentPath = parent.Node.Path; ContentNodeKit item1 = ContentNodeKitBuilder.CreateWithContent( mediaType.Id, id, $"{parentPath},{id}", draftData: item1Data, publishedData: item1Data); yield return item1; } } private void InitializeWithHierarchy( out int rootId, out IReadOnlyList<ContentNodeKit> firstLevelChildren, out IReadOnlyList<ContentNodeKit> secondLevelChildren) { var cache = new List<ContentNodeKit>(); var root = CreateRoot(out MediaType mediaType); firstLevelChildren = CreateChildren(10, root, mediaType, 3).ToList(); secondLevelChildren = CreateChildren(20, firstLevelChildren[0], mediaType, 3).ToList(); cache.Add(root); cache.AddRange(firstLevelChildren); cache.AddRange(secondLevelChildren); InitializedCache(null, null, _dataTypes, cache, new[] { mediaType }); rootId = root.Node.Id; } [Test] public void Get_Property_Value_Uses_Converter() { var cache = CreateRoot(out MediaType mediaType); InitializedCache(null, null, _dataTypes.ToArray(), new[] { cache }, new[] { mediaType }); var publishedMedia = GetMedia(1); var propVal = publishedMedia.Value(PublishedValueFallback, "content"); Assert.IsInstanceOf<IHtmlEncodedString>(propVal); Assert.AreEqual("<div>This is some content</div>", propVal.ToString()); var propVal2 = publishedMedia.Value<IHtmlEncodedString>(PublishedValueFallback, "content"); Assert.IsInstanceOf<IHtmlEncodedString>(propVal2); Assert.AreEqual("<div>This is some content</div>", propVal2.ToString()); var propVal3 = publishedMedia.Value(PublishedValueFallback, "Content"); Assert.IsInstanceOf<IHtmlEncodedString>(propVal3); Assert.AreEqual("<div>This is some content</div>", propVal3.ToString()); } [Test] public void Children() { InitializeWithHierarchy( out var rootId, out IReadOnlyList<ContentNodeKit> firstLevelChildren, out IReadOnlyList<ContentNodeKit> secondLevelChildren); var publishedMedia = GetMedia(rootId); var rootChildren = publishedMedia.Children(VariationContextAccessor); Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(firstLevelChildren.Select(x => x.Node.Id))); var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); var subChildren = publishedChild1.Children(VariationContextAccessor); Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(secondLevelChildren.Select(x => x.Node.Id))); } [Test] public void Descendants() { InitializeWithHierarchy( out var rootId, out IReadOnlyList<ContentNodeKit> firstLevelChildren, out IReadOnlyList<ContentNodeKit> secondLevelChildren); var publishedMedia = GetMedia(rootId); var rootDescendants = publishedMedia.Descendants(VariationContextAccessor); var descendentIds = firstLevelChildren.Select(x => x.Node.Id).Concat(secondLevelChildren.Select(x => x.Node.Id)); Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(descendentIds)); var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); var subDescendants = publishedChild1.Descendants(VariationContextAccessor); Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(secondLevelChildren.Select(x => x.Node.Id))); } [Test] public void DescendantsOrSelf() { InitializeWithHierarchy( out var rootId, out IReadOnlyList<ContentNodeKit> firstLevelChildren, out IReadOnlyList<ContentNodeKit> secondLevelChildren); var publishedMedia = GetMedia(rootId); var rootDescendantsOrSelf = publishedMedia.DescendantsOrSelf(VariationContextAccessor); var descendentAndSelfIds = firstLevelChildren.Select(x => x.Node.Id) .Concat(secondLevelChildren.Select(x => x.Node.Id)) .Append(rootId); Assert.IsTrue(rootDescendantsOrSelf.Select(x => x.Id).ContainsAll(descendentAndSelfIds)); var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); var subDescendantsOrSelf = publishedChild1.DescendantsOrSelf(VariationContextAccessor); Assert.IsTrue(subDescendantsOrSelf.Select(x => x.Id).ContainsAll( secondLevelChildren.Select(x => x.Node.Id).Append(firstLevelChildren[0].Node.Id))); } [Test] public void Parent() { InitializeWithHierarchy( out var rootId, out IReadOnlyList<ContentNodeKit> firstLevelChildren, out IReadOnlyList<ContentNodeKit> secondLevelChildren); var publishedMedia = GetMedia(rootId); Assert.AreEqual(null, publishedMedia.Parent); var publishedChild1 = GetMedia(firstLevelChildren[0].Node.Id); Assert.AreEqual(publishedMedia.Id, publishedChild1.Parent.Id); var publishedSubChild1 = GetMedia(secondLevelChildren[0].Node.Id); Assert.AreEqual(firstLevelChildren[0].Node.Id, publishedSubChild1.Parent.Id); } [Test] public void Ancestors() { InitializeWithHierarchy( out var rootId, out IReadOnlyList<ContentNodeKit> firstLevelChildren, out IReadOnlyList<ContentNodeKit> secondLevelChildren); var publishedSubChild1 = GetMedia(secondLevelChildren[0].Node.Id); Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id) .ContainsAll(new[] { firstLevelChildren[0].Node.Id, rootId })); } [Test] public void AncestorsOrSelf() { InitializeWithHierarchy( out var rootId, out IReadOnlyList<ContentNodeKit> firstLevelChildren, out IReadOnlyList<ContentNodeKit> secondLevelChildren); var publishedSubChild1 = GetMedia(secondLevelChildren[0].Node.Id); Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id) .ContainsAll(new[] { secondLevelChildren[0].Node.Id, firstLevelChildren[0].Node.Id, rootId })); } } }
// 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.Text; using System.Diagnostics; using System.Globalization; using System.Threading; namespace System.Xml { /// <devdoc> /// <para>Returns detailed information about the last parse error, including the error /// number, line number, character position, and a text description.</para> /// </devdoc> public class XmlException : Exception { private string _res; private string[] _args; // this field is not used, it's here just V1.1 serialization compatibility private int _lineNumber; private int _linePosition; private string _sourceUri; private const int HResults_Xml = unchecked((int)0x80131940); //provided to meet the ECMA standards public XmlException() : this(null) { } //provided to meet the ECMA standards public XmlException(String message) : this(message, ((Exception)null), 0, 0) { } //provided to meet ECMA standards public XmlException(String message, Exception innerException) : this(message, innerException, 0, 0) { } //provided to meet ECMA standards public XmlException(String message, Exception innerException, int lineNumber, int linePosition) : this(message, innerException, lineNumber, linePosition, null) { } internal XmlException(String message, Exception innerException, int lineNumber, int linePosition, string sourceUri) : base(FormatUserMessage(message, lineNumber, linePosition), innerException) { HResult = HResults_Xml; _res = (message == null ? SR.Xml_DefaultException : SR.Xml_UserException); _args = new string[] { message }; _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; } internal XmlException(string res, string[] args) : this(res, args, null, 0, 0, null) { } internal XmlException(string res, string[] args, string sourceUri) : this(res, args, null, 0, 0, sourceUri) { } internal XmlException(string res, string arg) : this(res, new string[] { arg }, null, 0, 0, null) { } internal XmlException(string res, string arg, string sourceUri) : this(res, new string[] { arg }, null, 0, 0, sourceUri) { } internal XmlException(string res, String arg, IXmlLineInfo lineInfo) : this(res, new string[] { arg }, lineInfo, null) { } internal XmlException(string res, String arg, Exception innerException, IXmlLineInfo lineInfo) : this(res, new string[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null) { } internal XmlException(string res, String arg, IXmlLineInfo lineInfo, string sourceUri) : this(res, new string[] { arg }, lineInfo, sourceUri) { } internal XmlException(string res, string[] args, IXmlLineInfo lineInfo) : this(res, args, lineInfo, null) { } internal XmlException(string res, string[] args, IXmlLineInfo lineInfo, string sourceUri) : this(res, args, null, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), sourceUri) { } internal XmlException(string res, int lineNumber, int linePosition) : this(res, (string[])null, null, lineNumber, linePosition) { } internal XmlException(string res, string arg, int lineNumber, int linePosition) : this(res, new string[] { arg }, null, lineNumber, linePosition, null) { } internal XmlException(string res, string arg, int lineNumber, int linePosition, string sourceUri) : this(res, new string[] { arg }, null, lineNumber, linePosition, sourceUri) { } internal XmlException(string res, string[] args, int lineNumber, int linePosition) : this(res, args, null, lineNumber, linePosition, null) { } internal XmlException(string res, string[] args, int lineNumber, int linePosition, string sourceUri) : this(res, args, null, lineNumber, linePosition, sourceUri) { } internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition) : this(res, args, innerException, lineNumber, linePosition, null) { } internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition, string sourceUri) : base(CreateMessage(res, args, lineNumber, linePosition), innerException) { HResult = HResults_Xml; _res = res; _args = args; _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; } private static string FormatUserMessage(string message, int lineNumber, int linePosition) { if (message == null) { return CreateMessage(SR.Xml_DefaultException, null, lineNumber, linePosition); } else { if (lineNumber == 0 && linePosition == 0) { // do not reformat the message when not needed return message; } else { // add line information return CreateMessage(SR.Xml_UserException, new string[] { message }, lineNumber, linePosition); } } } private static string CreateMessage(string res, string[] args, int lineNumber, int linePosition) { string message; // No line information -> get resource string and return if (lineNumber == 0) { message = SR.Format(res, args); } // Line information is available -> we need to append it to the error message else { string lineNumberStr = lineNumber.ToString(CultureInfo.InvariantCulture); string linePositionStr = linePosition.ToString(CultureInfo.InvariantCulture); message = SR.Format(res, args); message = SR.Format(SR.Xml_MessageWithErrorPosition, message, lineNumberStr, linePositionStr); } return message; } 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] = invChar.ToString(); } aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar); } return aStringList; } public int LineNumber { get { return _lineNumber; } } public int LinePosition { get { return _linePosition; } } internal string ResString { get { return _res; } } }; } // namespace System.Xml
using System; using NBitcoin.BouncyCastle.Crypto.Engines; using NBitcoin.BouncyCastle.Crypto.Parameters; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * implementation of GOST R 34.11-94 */ public class Gost3411Digest : IDigest, IMemoable { private const int DIGEST_LENGTH = 32; private byte[] H = new byte[32], L = new byte[32], M = new byte[32], Sum = new byte[32]; private byte[][] C = MakeC(); private byte[] xBuf = new byte[32]; private int xBufOff; private ulong byteCount; private readonly IBlockCipher cipher = new Gost28147Engine(); private byte[] sBox; private static byte[][] MakeC() { byte[][] c = new byte[4][]; for (int i = 0; i < 4; ++i) { c[i] = new byte[32]; } return c; } /** * Standard constructor */ public Gost3411Digest() { sBox = Gost28147Engine.GetSBox("D-A"); cipher.Init(true, new ParametersWithSBox(null, sBox)); Reset(); } /** * Constructor to allow use of a particular sbox with GOST28147 * @see GOST28147Engine#getSBox(String) */ public Gost3411Digest(byte[] sBoxParam) { sBox = Arrays.Clone(sBoxParam); cipher.Init(true, new ParametersWithSBox(null, sBox)); Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Gost3411Digest(Gost3411Digest t) { Reset(t); } public string AlgorithmName { get { return "Gost3411"; } } public int GetDigestSize() { return DIGEST_LENGTH; } public void Update( byte input) { xBuf[xBufOff++] = input; if (xBufOff == xBuf.Length) { sumByteArray(xBuf); // calc sum M processBlock(xBuf, 0); xBufOff = 0; } byteCount++; } public void BlockUpdate( byte[] input, int inOff, int length) { while ((xBufOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } while (length > xBuf.Length) { Array.Copy(input, inOff, xBuf, 0, xBuf.Length); sumByteArray(xBuf); // calc sum M processBlock(xBuf, 0); inOff += xBuf.Length; length -= xBuf.Length; byteCount += (uint)xBuf.Length; } // load in the remainder. while (length > 0) { Update(input[inOff]); inOff++; length--; } } // (i + 1 + 4(k - 1)) = 8i + k i = 0-3, k = 1-8 private byte[] K = new byte[32]; private byte[] P(byte[] input) { int fourK = 0; for(int k = 0; k < 8; k++) { K[fourK++] = input[k]; K[fourK++] = input[8 + k]; K[fourK++] = input[16 + k]; K[fourK++] = input[24 + k]; } return K; } //A (x) = (x0 ^ x1) || x3 || x2 || x1 byte[] a = new byte[8]; private byte[] A(byte[] input) { for(int j=0; j<8; j++) { a[j]=(byte)(input[j] ^ input[j+8]); } Array.Copy(input, 8, input, 0, 24); Array.Copy(a, 0, input, 24, 8); return input; } //Encrypt function, ECB mode private void E(byte[] key, byte[] s, int sOff, byte[] input, int inOff) { cipher.Init(true, new KeyParameter(key)); cipher.ProcessBlock(input, inOff, s, sOff); } // (in:) n16||..||n1 ==> (out:) n1^n2^n3^n4^n13^n16||n16||..||n2 internal short[] wS = new short[16], w_S = new short[16]; private void fw(byte[] input) { cpyBytesToShort(input, wS); w_S[15] = (short)(wS[0] ^ wS[1] ^ wS[2] ^ wS[3] ^ wS[12] ^ wS[15]); Array.Copy(wS, 1, w_S, 0, 15); cpyShortToBytes(w_S, input); } // block processing internal byte[] S = new byte[32], U = new byte[32], V = new byte[32], W = new byte[32]; private void processBlock(byte[] input, int inOff) { Array.Copy(input, inOff, M, 0, 32); //key step 1 // H = h3 || h2 || h1 || h0 // S = s3 || s2 || s1 || s0 H.CopyTo(U, 0); M.CopyTo(V, 0); for (int j=0; j<32; j++) { W[j] = (byte)(U[j]^V[j]); } // Encrypt gost28147-ECB E(P(W), S, 0, H, 0); // s0 = EK0 [h0] //keys step 2,3,4 for (int i=1; i<4; i++) { byte[] tmpA = A(U); for (int j=0; j<32; j++) { U[j] = (byte)(tmpA[j] ^ C[i][j]); } V = A(A(V)); for (int j=0; j<32; j++) { W[j] = (byte)(U[j]^V[j]); } // Encrypt gost28147-ECB E(P(W), S, i * 8, H, i * 8); // si = EKi [hi] } // x(M, H) = y61(H^y(M^y12(S))) for(int n = 0; n < 12; n++) { fw(S); } for(int n = 0; n < 32; n++) { S[n] = (byte)(S[n] ^ M[n]); } fw(S); for(int n = 0; n < 32; n++) { S[n] = (byte)(H[n] ^ S[n]); } for(int n = 0; n < 61; n++) { fw(S); } Array.Copy(S, 0, H, 0, H.Length); } private void finish() { ulong bitCount = byteCount * 8; Pack.UInt64_To_LE(bitCount, L); while (xBufOff != 0) { Update((byte)0); } processBlock(L, 0); processBlock(Sum, 0); } public int DoFinal( byte[] output, int outOff) { finish(); H.CopyTo(output, outOff); Reset(); return DIGEST_LENGTH; } /** * reset the chaining variables to the IV values. */ private static readonly byte[] C2 = { 0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF, (byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00,(byte)0xFF,0x00, 0x00,(byte)0xFF,(byte)0xFF,0x00,(byte)0xFF,0x00,0x00,(byte)0xFF, (byte)0xFF,0x00,0x00,0x00,(byte)0xFF,(byte)0xFF,0x00,(byte)0xFF }; public void Reset() { byteCount = 0; xBufOff = 0; Array.Clear(H, 0, H.Length); Array.Clear(L, 0, L.Length); Array.Clear(M, 0, M.Length); Array.Clear(C[1], 0, C[1].Length); // real index C = +1 because index array with 0. Array.Clear(C[3], 0, C[3].Length); Array.Clear(Sum, 0, Sum.Length); Array.Clear(xBuf, 0, xBuf.Length); C2.CopyTo(C[2], 0); } // 256 bitsblock modul -> (Sum + a mod (2^256)) private void sumByteArray( byte[] input) { int carry = 0; for (int i = 0; i != Sum.Length; i++) { int sum = (Sum[i] & 0xff) + (input[i] & 0xff) + carry; Sum[i] = (byte)sum; carry = sum >> 8; } } private static void cpyBytesToShort(byte[] S, short[] wS) { for(int i = 0; i < S.Length / 2; i++) { wS[i] = (short)(((S[i*2+1]<<8)&0xFF00)|(S[i*2]&0xFF)); } } private static void cpyShortToBytes(short[] wS, byte[] S) { for(int i=0; i<S.Length/2; i++) { S[i*2 + 1] = (byte)(wS[i] >> 8); S[i*2] = (byte)wS[i]; } } public int GetByteLength() { return 32; } public IMemoable Copy() { return new Gost3411Digest(this); } public void Reset(IMemoable other) { Gost3411Digest t = (Gost3411Digest)other; this.sBox = t.sBox; cipher.Init(true, new ParametersWithSBox(null, sBox)); Reset(); Array.Copy(t.H, 0, this.H, 0, t.H.Length); Array.Copy(t.L, 0, this.L, 0, t.L.Length); Array.Copy(t.M, 0, this.M, 0, t.M.Length); Array.Copy(t.Sum, 0, this.Sum, 0, t.Sum.Length); Array.Copy(t.C[1], 0, this.C[1], 0, t.C[1].Length); Array.Copy(t.C[2], 0, this.C[2], 0, t.C[2].Length); Array.Copy(t.C[3], 0, this.C[3], 0, t.C[3].Length); Array.Copy(t.xBuf, 0, this.xBuf, 0, t.xBuf.Length); this.xBufOff = t.xBufOff; this.byteCount = t.byteCount; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using Aurora.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Aurora.Framework.Capabilities; using Aurora.Simulation.Base; namespace OpenSim.Services.RobustCompat { public class RobustCaps : INonSharedRegionModule { #region Declares private IScene m_scene; private bool m_enabled = false; #endregion #region IRegionModuleBase Members public void Initialise(Nini.Config.IConfigSource source) { m_enabled = source.Configs["Handlers"].GetBoolean("RobustCompatibility", m_enabled); } public void AddRegion (IScene scene) { if (!m_enabled) return; m_scene = scene; scene.EventManager.OnClosingClient += OnClosingClient; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnSetAgentLeaving += OnSetAgentLeaving; scene.AuroraEventManager.RegisterEventHandler ("NewUserConnection", OnGenericEvent); scene.AuroraEventManager.RegisterEventHandler ("UserStatusChange", OnGenericEvent); scene.AuroraEventManager.RegisterEventHandler ("SendingAttachments", SendAttachments); } void OnSetAgentLeaving(IScenePresence presence, Interfaces.GridRegion destination) { IAttachmentsModule attModule = presence.Scene.RequestModuleInterface<IAttachmentsModule>(); if(attModule != null) m_userAttachments[presence.UUID] = attModule.GetAttachmentsForAvatar(presence.UUID); } private readonly Dictionary<UUID, ISceneEntity[]> m_userAttachments = new Dictionary<UUID, ISceneEntity[]>(); public object SendAttachments (string funct, object param) { object[] parameters = (object[])param; IScenePresence sp = (IScenePresence)parameters[1]; Interfaces.GridRegion dest = (Interfaces.GridRegion)parameters[0]; // this is never used.. IAttachmentsModule att = sp.Scene.RequestModuleInterface<IAttachmentsModule> (); if (m_userAttachments.ContainsKey(sp.UUID)) { Util.FireAndForget (delegate { foreach (ISceneEntity attachment in m_userAttachments[sp.UUID]) { Connectors.Simulation.SimulationServiceConnector ssc = new Connectors.Simulation.SimulationServiceConnector (); attachment.IsDeleted = false;//Fix this, we 'did' get removed from the sim already //Now send it to them ssc.CreateObject (dest, (ISceneObject)attachment); attachment.IsDeleted = true; } }); } return null; } void OnMakeRootAgent (IScenePresence presence) { ICapsService service = m_scene.RequestModuleInterface<ICapsService> (); if (service != null) { IClientCapsService clientCaps = service.GetClientCapsService (presence.UUID); if (clientCaps != null) { IRegionClientCapsService regionCaps = clientCaps.GetCapsService (m_scene.RegionInfo.RegionHandle); if (regionCaps != null) { regionCaps.RootAgent = true; foreach (IRegionClientCapsService regionClientCaps in clientCaps.GetCapsServices ()) { if (regionCaps.RegionHandle != regionClientCaps.RegionHandle) regionClientCaps.RootAgent = false; //Reset any other agents that we might have } } } } if ((presence.CallbackURI != null) && !presence.CallbackURI.Equals ("")) { WebUtils.ServiceOSDRequest (presence.CallbackURI, null, "DELETE", 10000, false, false, false); presence.CallbackURI = null; } #if (!ISWIN) Util.FireAndForget(delegate(object o) { DoPresenceUpdate(presence); }); #else Util.FireAndForget(o => DoPresenceUpdate(presence)); #endif } private void DoPresenceUpdate(IScenePresence presence) { ReportAgent(presence); IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>(); IAgentInfoService aservice = m_scene.RequestModuleInterface<IAgentInfoService>(); if (friendsModule != null) { Interfaces.FriendInfo[] friends = friendsModule.GetFriends(presence.UUID); List<string> s = new List<string>(); for (int i = 0; i < friends.Length; i++) { s.Add(friends[i].Friend); } List<UserInfo> infos = aservice.GetUserInfos(s); foreach (UserInfo u in infos) { if (u != null && u.IsOnline) friendsModule.SendFriendsStatusMessage(presence.UUID, UUID.Parse(u.UserID), true); } foreach (UserInfo u in infos) { if (u != null && u.IsOnline) { if (!IsLocal(u, presence)) DoNonLocalPresenceUpdateCall(u, presence); else friendsModule.SendFriendsStatusMessage(UUID.Parse(u.UserID), presence.UUID, true); } } } } private void DoNonLocalPresenceUpdateCall(UserInfo u, IScenePresence presence) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); //sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "status"; sendData["FromID"] = presence.UUID.ToString(); sendData["ToID"] = u.UserID; sendData["Online"] = u.IsOnline.ToString(); Call(m_scene.GridService.GetRegionByUUID(UUID.Zero, u.CurrentRegionID), sendData); } private void Call(OpenSim.Services.Interfaces.GridRegion region, Dictionary<string, object> sendData) { Util.FireAndForget(delegate(object o) { string reqString = WebUtils.BuildQueryString(sendData); //MainConsole.Instance.DebugFormat("[FRIENDS CONNECTOR]: queryString = {0}", reqString); if (region == null) return; try { string url = "http://" + region.ExternalHostName + ":" + region.HttpPort; string a = SynchronousRestFormsRequester.MakeRequest("POST", url + "/friends", reqString); } catch (Exception) { } }); } private bool IsLocal(UserInfo u, IScenePresence presence) { #if (!ISWIN) foreach (IScene scene in presence.Scene.RequestModuleInterface<SceneManager>().Scenes) { if (scene.GetScenePresence(UUID.Parse(u.UserID)) != null) return true; } return false; #else return presence.Scene.RequestModuleInterface<SceneManager>().Scenes.Any(scene => scene.GetScenePresence(UUID.Parse(u.UserID)) != null); #endif } private void ReportAgent(IScenePresence presence) { IAgentInfoService aservice = m_scene.RequestModuleInterface<IAgentInfoService>(); if (aservice != null) aservice.SetLoggedIn(presence.UUID.ToString(), true, false, presence.Scene.RegionInfo.RegionID); Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "login"; sendData["UserID"] = presence.UUID.ToString(); sendData["SessionID"] = presence.ControllingClient.SessionId.ToString(); sendData["SecureSessionID"] = presence.ControllingClient.SecureSessionId.ToString(); string reqString = WebUtils.BuildQueryString(sendData); List<string> urls = m_scene.RequestModuleInterface<IConfigurationService>().FindValueOf("PresenceServerURI"); foreach (string url in urls) { SynchronousRestFormsRequester.MakeRequest("POST", url, reqString); } sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "report"; sendData["SessionID"] = presence.ControllingClient.SessionId.ToString(); sendData["RegionID"] = presence.Scene.RegionInfo.RegionID.ToString(); reqString = WebUtils.BuildQueryString(sendData); // MainConsole.Instance.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); foreach (string url in urls) { string resp = SynchronousRestFormsRequester.MakeRequest("POST", url, reqString); } if (aservice != null) aservice.SetLastPosition(presence.UUID.ToString(), presence.Scene.RegionInfo.RegionID, presence.AbsolutePosition, Vector3.Zero); } void OnClosingClient(IClientAPI client) { ICapsService service = m_scene.RequestModuleInterface<ICapsService>(); if (service != null) { IClientCapsService clientCaps = service.GetClientCapsService(client.AgentId); if (clientCaps != null) { IRegionClientCapsService regionCaps = clientCaps.GetCapsService(m_scene.RegionInfo.RegionHandle); if (regionCaps != null) { regionCaps.Close(); clientCaps.RemoveCAPS(m_scene.RegionInfo.RegionHandle); } if (client.IsLoggingOut) { clientCaps.Close (); } } } } protected object OnGenericEvent(string FunctionName, object parameters) { if (FunctionName == "NewUserConnection") { ICapsService service = m_scene.RequestModuleInterface<ICapsService>(); if (service != null) { object[] obj = (object[])parameters; OSDMap param = (OSDMap)obj[0]; AgentCircuitData circuit = (AgentCircuitData)obj[1]; if (circuit.reallyischild)//If Aurora is sending this, it'll show that it really is a child agent return null; AvatarAppearance appearance = m_scene.AvatarService.GetAppearance(circuit.AgentID); if (appearance != null) circuit.Appearance = appearance; else m_scene.AvatarService.SetAppearance(circuit.AgentID, circuit.Appearance); //circuit.Appearance.Texture = new Primitive.TextureEntry(UUID.Zero); circuit.child = false;//ONLY USE ROOT AGENTS, SINCE OPENSIM SENDS CHILD == TRUE ALL THE TIME if (circuit.ServiceURLs != null && circuit.ServiceURLs.ContainsKey ("IncomingCAPSHandler")) { AddCapsHandler(circuit); } else { IClientCapsService clientService = service.GetOrCreateClientCapsService (circuit.AgentID); clientService.RemoveCAPS (m_scene.RegionInfo.RegionHandle); service.CreateCAPS (circuit.AgentID, CapsUtil.GetCapsSeedPath (circuit.CapsPath), m_scene.RegionInfo.RegionHandle, true, circuit, MainServer.Instance.Port); //We ONLY use root agents because of OpenSim's inability to send the correct data MainConsole.Instance.Output ("setting up on " + clientService.HostUri + CapsUtil.GetCapsSeedPath (circuit.CapsPath)); IClientCapsService clientCaps = service.GetClientCapsService (circuit.AgentID); if (clientCaps != null) { IRegionClientCapsService regionCaps = clientCaps.GetCapsService (m_scene.RegionInfo.RegionHandle); if (regionCaps != null) { regionCaps.AddCAPS ((OSDMap)param["CapsUrls"]); } } } } } else if (FunctionName == "UserStatusChange") { object[] info = (object[])parameters; if (!bool.Parse(info[1].ToString())) //Logging out { ICapsService service = m_scene.RequestModuleInterface<ICapsService>(); if (service != null) { service.RemoveCAPS (UUID.Parse (info[0].ToString ())); } } } return null; } private void AddCapsHandler(AgentCircuitData circuit) { //Used by incoming (home) agents from HG #if (!ISWIN) MainServer.Instance.AddStreamHandler(new RestStreamHandler("POST", CapsUtil.GetCapsSeedPath(circuit.CapsPath), delegate(string request, string path, string param2, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return CapsRequest(request, path, param2, httpRequest, httpResponse, circuit.ServiceURLs["IncomingCAPSHandler"].ToString()); })); #else MainServer.Instance.AddStreamHandler(new RestStreamHandler("POST", CapsUtil.GetCapsSeedPath(circuit.CapsPath), (request, path, param2, httpRequest, httpResponse) => CapsRequest(request, path, param2, httpRequest, httpResponse, circuit.ServiceURLs[ "IncomingCAPSHandler"].ToString()))); #endif } public void RegionLoaded (IScene scene) { } public void RemoveRegion (IScene scene) { } public void Close() { } public string Name { get { return "RobustCaps"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region Virtual caps handler public virtual string CapsRequest (string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse, string url) { OSDMap response = WebUtils.PostToService (url, new OSDMap (), true, false, true); return OSDParser.SerializeLLSDXmlString (response); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Xml; using System.Collections.Specialized; using System.Collections; using System.Security.Cryptography; using System.Web; using System.Web.UI.WebControls; using System.Web.Script.Serialization; namespace Rmb.Core { /// <summary> /// /// </summary> public abstract class ServiceAdapter { /// <summary> /// The following consts are for creating the various API urls /// </summary> public const string ACCOUNTS = "accounts/"; public const string DROPS = "drops/"; public const string EMPTY_DROP = "/empty"; public const string ASSETS = "/assets/"; public const string SUBSCRIPTIONS = "/subscriptions/"; public const string DOWNLOAD_ORIGINAL = "/download/original"; public const string COPY = "/copy"; public const string MOVE = "/move"; public const string JOBS = "jobs/"; /// <summary> /// /// </summary> public const string VERSION = "3.0"; /// <summary> /// getters for the base API urls /// </summary> public abstract string BaseUrl { get; } public abstract string ApiBaseUrl { get; } public abstract string UploadUrl { get; } /// <summary> /// getters for API key(s) /// </summary> public string ApiKey { get; set; } public string ApiSecret { get; set; } delegate void GetResponse(HttpWebResponse response); delegate void ReadDocument(XmlDocument doc); /// <summary> /// Delegate /// </summary> public delegate void TransferProgressHandler(object sender, TransferProgressEventArgs e); /// <summary> /// UploadProgressHandler is fired during a synchronous transfer process to signify that /// a segment of transfer has been completed. The total transfered is recorded in the /// <see cref="TransferProgressEventArgs"/> class. /// </summary> public event TransferProgressHandler OnTransferProgress; #region Implementation /// <summary> /// Completes the request. /// </summary> /// <param name="request">The request.</param> /// <param name="respond">The respond action.</param> private void CompleteRequest(HttpWebRequest request, GetResponse respond) { HttpWebResponse response = null; try { // get the request response response = request.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) { // request response returned status code OK, procede if a delagate was specified if (respond != null) { respond(response); } } else { // status code was anything but OK throw new ServiceException(ServiceError.BadRequest, "There was a problem with your request."); } } catch (WebException exc) { this.HandleException(exc); } finally { // close the connection (if we had a respose to read) if (response != null) { response.Close(); } response = null; } } /// <summary> /// Reads a <see cref="HttpWebResponse"/> response. /// </summary> /// <param name="response"> /// The <see cref="HttpWebResponse"/> object being read. /// </param> /// <param name="read"> /// A <see cref="ReadDocument"/> delagate that can be used to put the response into a <see cref="XmlDocument"/> /// object. /// </param> private void ReadResponse(HttpWebResponse response, ReadDocument read) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { // create new XmlDocument, load the XML response into it, then run the delagate if one is specified XmlDocument doc = new XmlDocument(); doc.Load(reader); if (read != null) { read(doc); } } } /// <summary> /// Gets an original file download url. /// </summary> /// <param name="asset">An <see cref="Asset"/> object</param> /// <returns></returns> public string GenerateOriginalFileUrl (Asset asset ) { // create the API call StringBuilder sb = new StringBuilder (); sb.Append (this.ApiBaseUrl + DROPS + asset.Drop.Name + ASSETS + asset.Id + DOWNLOAD_ORIGINAL); // we just need the "common" parameters for this request, and sign if secret was provided Hashtable parameters = new Hashtable (); AddCommonParameters( ref parameters ); SignIfNeeded( ref parameters ); // add the parameters to the end of the url sb.Append("?"); sb.Append( BuildParameterString( parameters )); // return as a string return sb.ToString(); } /// <summary> /// Generates a SHA1 hash signature for the specified string /// </summary> /// <param name="StringToSign"> /// The <see cref="string"/> of parameters to sign. /// </param> /// <returns> /// /// </returns> protected string GenerateSignature( string StringToSign ) { SHA1 sha1 = new SHA1CryptoServiceProvider(); // the string must be converted to an array of byte's before it can be encoded byte[] input = Encoding.UTF8.GetBytes( StringToSign ); byte[] result = sha1.ComputeHash(input); // value returned from ComputeHash() has a dash between each byte, remove and convert to lowercase return BitConverter.ToString(result).Replace( "-", "" ).ToLower(); } /// <summary> /// Generates a unix timestamp 10 minutes in the future /// </summary> /// <returns></returns> protected long GenerateUnixTimestamp() { // now + 10 minutes TimeSpan ts = (DateTime.UtcNow.AddMinutes(10) - new DateTime(1970, 1, 1, 0, 0, 0)); // return the time span as just the total seconds (since that's what we mean by unix time) return (long) ts.TotalSeconds; } /// <summary> /// Creates a Drop. /// </summary> /// <param name="dropAttributes">The name.</param> /// <returns> /// /// </returns> public Drop CreateDrop( Hashtable dropAttributes ) { // drop object that will be returned Drop d = null; // add any specified parameters to a Hashtable. All parameters are optional, so only add if they've been specified // Hashtable parameters = new Hashtable(); // if( name != string.Empty) // parameters.Add("name", name); // if( description != string.Empty) // parameters.Add("description", description); // if( emailKey != string.Empty) // parameters.Add("email_key", emailKey); // if( maxSize > 0 ) // parameters.Add("max_size", maxSize.ToString() ); // if( chatPassword != string.Empty) // parameters.Add("chat_password", chatPassword); // do the request and load to response into the Drop object HttpWebRequest request = this.CreatePostRequest(this.CreateDropUrl(string.Empty), dropAttributes ); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, (XmlDocument doc) => d = this.CreateAndMapDrop(doc.SelectSingleNode("drop"))); }); return d; } /// <summary> /// Find a drop by name. /// </summary> /// <param name="name">A <see cref="string"/> specifying the name of the drop to find.</param> /// <returns></returns> public Drop FindDrop(string name) { // can't find a drop if we don't have a name... if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name", "The given name can't be blank."); // drop object to be returned Drop d = null; // do the request, load response into Drop object HttpWebRequest request = this.CreateUrlEncodedRequest("GET", this.CreateDropUrl(name)); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, (XmlDocument doc) => d = this.CreateAndMapDrop(doc.SelectSingleNode("drop"))); }); return d; } /// <summary> /// Gets a paginated list of drops associated with the ApiKey /// </summary> /// <param name="page">An <see cref="int"/> specifying the page of results to get.</param> /// <returns></returns> public List<Drop> FindAll(int page) { // List<Drop> object to return List<Drop> drops = new List<Drop>(); // add the page parameter Hashtable parameters = new Hashtable(); parameters.Add( "page", page.ToString() ); // do the request and load the response into the drop list HttpWebRequest request = this.CreateUrlEncodedRequest("GET", this.CreateAllDropsUrl(), parameters); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, delegate(XmlDocument doc) { XmlNodeList nodes = doc.SelectNodes("/drops/drop"); // go through each returned drop XML node. load into Drop object and Add() to List foreach (XmlNode node in nodes) { Drop d = this.CreateAndMapDrop(node); drops.Add(d); } }); }); return drops; } /// <summary> /// Empties a drop of all assets /// </summary> /// <param name="drop">The <see cref="Drop"/> to be emptied</param> /// <returns></returns> public bool EmptyDrop(Drop drop) { // can't do much if we don't have a drop to act on... if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); // bool to return bool emptied = false; // do request and change "emptied" to true if request succeeds HttpWebRequest request = this.CreatePutRequest(this.CreateEmptyDropUrl(drop.Name), new Hashtable() ); CompleteRequest(request, (HttpWebResponse response) => { emptied = true; }); if( emptied == true ) drop.AssetCount = 0; return emptied; } /// <summary> /// Deletes the drop. /// </summary> /// <param name="drop">The drop.</param> /// <returns></returns> public bool DestroyDrop (Drop drop) { // can't do much if we don't have a drop to act on... if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); // bool to return bool destroyed = false; // do request and change "destroyed" to true if request succeeds HttpWebRequest request = this.CreateUrlEncodedRequest("DELETE",this.CreateDropUrl(drop.Name), new Hashtable() ); CompleteRequest(request, (HttpWebResponse response) => { destroyed = true; }); if( destroyed == true ) { // empty the drop *object* so that actions cannot be performed on it (since the drop it represents no // longer exists). Just setting it to null doesn't work (it doesn't overwrite the object being passed // in, so once we return we are back to the object that we orginially passed in. drop.AssetCount = 0; drop.ChatPassword = string.Empty; drop.CurrentBytes = 0; drop.Description = string.Empty; drop.Email = string.Empty; drop.MaxBytes = 0; drop.Name = string.Empty; } return destroyed; } /// <summary> /// Updates the drop. /// </summary> /// <param name="drop">The drop.</param> /// <param name="name"></param> /// <param name="chatPassword"></param> /// <returns></returns> //public bool UpdateDrop (Drop drop, string newName, string newDescription, string newChatPassword, int newMaxSize) public bool UpdateDrop (Drop drop, string newName ) { // can't do much if we don't have a drop to act on... if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); Hashtable parameters = new Hashtable(); if ( !string.IsNullOrEmpty( newName )) { // we are updating just the name parameters.Add( "name", newName ); } else { // we are updating anything but name parameters.Add( "description", drop.Description ); parameters.Add( "chat_password", drop.ChatPassword ); parameters.Add( "max_size", drop.MaxBytes.ToString() ); } // bool to return bool updated = false; // do the request and change updated to "true" if request succeeded HttpWebRequest request = this.CreatePutRequest(this.CreateDropUrl(drop.Name), parameters); CompleteRequest(request, delegate(HttpWebResponse response) { // the response includes the updated drop information, load it into the drop object we passed ReadResponse(response, (XmlDocument doc) => this.MapDrop(drop, doc.SelectSingleNode("drop"))); updated = true; }); return updated; } /// <summary> /// Finds an asset. /// </summary> /// <param name="drop"></param> /// <param name="name">The asset name.</param> /// <returns></returns> public Asset FindAsset(Drop drop, string assetId) { // we can't do much without a drop or asset ID... if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); if (assetId == null) throw new ArgumentNullException("assetId", "The given asset ID can't be null"); // asset object to return Asset a = null; // do the request HttpWebRequest request = this.CreateUrlEncodedRequest("GET", this.CreateAssetUrl(drop.Name, assetId, string.Empty)); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, delegate(XmlDocument doc) { // read the XML response into the Asset object XmlNode node = doc.SelectSingleNode( "/asset"); a = this.CreateAndMapAsset(drop, node); }); }); return a; } /// <summary> /// Finds the assets for a given drop. /// </summary> /// <param name="drop">The drop.</param> /// <param name="page">The page.</param> /// <param name="order">The order.</param> /// <returns></returns> public List<Asset> FindAssets(Drop drop, int page, Order order) { // can't do much without a drop to act on if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); // the Asset list to return List<Asset> assets = new List<Asset>(); // create a new hashtable and add the passed in parameters Hashtable parameters = new Hashtable(); parameters.Add( "page", page.ToString() ); parameters.Add( "order", (order == Order.Newest ) ? "latest" : "oldest" ); // do the request HttpWebRequest request = this.CreateUrlEncodedRequest("GET", this.CreateAssetUrl(drop.Name, string.Empty, string.Empty), parameters); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, delegate(XmlDocument doc) { // get all the asset XML nodes, load each one into an Asset object and load into the Asset list XmlNodeList nodes = doc.SelectNodes("//assets/asset"); foreach (XmlNode node in nodes) { Asset a = this.CreateAndMapAsset(drop, node); assets.Add(a); } }); }); return assets; } /// <summary> /// Finds the subscriptions. /// </summary> /// <param name="drop">The drop.</param> /// <param name="page">The page.</param> /// <returns></returns> public List<Subscription> FindSubscriptions(Drop drop, int page) { if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); List<Subscription> subscriptions = new List<Subscription>(); Hashtable parameters = new Hashtable(); parameters.Add( "page", page.ToString() ); HttpWebRequest request = this.CreateUrlEncodedRequest("GET", this.CreateSubscriptionsUrl(drop.Name), parameters ); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, delegate(XmlDocument doc) { XmlNodeList nodes = doc.SelectNodes("/subscriptions/subscription"); foreach (XmlNode node in nodes) { Subscription s = this.CreateAndMapSubscription(drop, node); subscriptions.Add(s); } }); }); return subscriptions; } /// <summary> /// Creates a pingback subscription. When the events happen, the url will be sent a POST request with the pertinent data. /// </summary> /// <param name="drop">The drop.</param> /// <param name="url">The url.</param> /// <param name="events"> The events. </param> /// <returns></returns> public Subscription CreatePingbackSubscription(Drop drop, string url, AssetEvents events) { if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); Subscription s = null; Hashtable parameters = new Hashtable(); parameters.Add("type", "pingback"); parameters.Add("url", url); parameters.Add("asset_created", ((events & AssetEvents.AssetCreated) == AssetEvents.AssetCreated).ToString().ToLower()); parameters.Add("asset_udpated", ((events & AssetEvents.AssetUpdated) == AssetEvents.AssetUpdated).ToString().ToLower()); parameters.Add("asset_deleted", ((events & AssetEvents.AssetDeleted) == AssetEvents.AssetDeleted).ToString().ToLower()); parameters.Add("job_started", ((events & AssetEvents.JobStarted) == AssetEvents.JobStarted).ToString().ToLower()); parameters.Add("job_complete", ((events & AssetEvents.JobComplete) == AssetEvents.JobComplete).ToString().ToLower()); parameters.Add("job_progress", ((events & AssetEvents.JobProgress) == AssetEvents.JobProgress).ToString().ToLower()); HttpWebRequest request = this.CreatePostRequest(this.CreateSubscriptionsUrl(drop.Name), parameters); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, delegate(XmlDocument doc) { XmlNode node = doc.SelectSingleNode("/subscription"); s = this.CreateAndMapSubscription(drop, node); }); }); return s; } /// <summary> /// Deletes the subscription. /// </summary> /// <param name="subscription">The subscription.</param> /// <returns></returns> public bool DeleteSubscription(Subscription subscription) { bool destroyed = false; Drop drop = subscription.Drop; Hashtable parameters = new Hashtable(); HttpWebRequest request = this.CreateUrlEncodedRequest("DELETE",this.CreateSubscriptionUrl(drop.Name, subscription.Id), parameters); CompleteRequest(request, (HttpWebResponse response) => { destroyed = true; }); return destroyed; } /// <summary> /// Deletes the asset. /// </summary> /// <param name="asset">The asset.</param> /// <returns></returns> public bool DeleteAsset(Asset asset) { if (asset == null) throw new ArgumentNullException("asset", "The given asset can't be null"); bool destroyed = false; Drop drop = asset.Drop; Hashtable parameters = new Hashtable(); HttpWebRequest request = this.CreateUrlEncodedRequest("DELETE",this.CreateAssetUrl(drop.Name, asset.Id, string.Empty), parameters); CompleteRequest(request, (HttpWebResponse response) => { destroyed = true; }); if( destroyed == true) { // empty the Asset object asset.CreatedAt = new DateTime(); asset.Description = string.Empty; asset.Drop = null; asset.DropName = string.Empty; asset.Filesize = 0; asset.Id = string.Empty; asset.Name = string.Empty; asset.Roles = new List<AssetRoleAndLocations>(); asset.Title = string.Empty; } return destroyed; } /// <summary> /// Updates the asset. /// </summary> /// <param name="asset">The asset.</param> /// <param name="newTitle"></param> /// <param name="newDescription"></param> /// <returns></returns> public bool UpdateAsset(Asset asset) { if (asset == null) throw new ArgumentNullException("asset", "The given asset can't be null"); bool updated = false; Drop drop = asset.Drop; Hashtable parameters = new Hashtable(); parameters.Add( "title", asset.Title ); parameters.Add( "description", asset.Description ); // if( !string.IsNullOrEmpty( newTitle )) // parameters.Add("name", newTitle); // if( !string.IsNullOrEmpty( newDescription )) // parameters.Add("description", newDescription ); //if( !string.IsNullOrEmpty( asset.)) HttpWebRequest request = this.CreatePutRequest(this.CreateAssetUrl(drop.Name, asset.Id, string.Empty), parameters); CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, delegate(XmlDocument doc) { XmlNode node = doc.SelectSingleNode("/asset"); MapAsset( asset, drop, node ); updated = true; }); }); return updated; } /// <summary> /// /// </summary> /// <param name="asset"> /// A <see cref="Asset"/> /// </param> /// <param name="dropName"> /// A <see cref="System.String"/> /// </param> /// <returns> /// A <see cref="System.Boolean"/> /// </returns> public bool CopyAsset(Asset asset, Drop drop, bool keepOriginal) { if (asset == null) throw new ArgumentNullException("asset", "The given asset can't be null"); if (drop == null) throw new ArgumentNullException("drop", "The given drop can't be null"); bool copied = false; Hashtable parameters = new Hashtable(); parameters.Add("drop_name", drop.Name); HttpWebRequest request = this.CreatePostRequest(this.CreateAssetUrl(asset.Drop.Name, asset.Id, keepOriginal == true ? COPY : MOVE ), parameters); CompleteRequest(request, (HttpWebResponse response) => { copied = true; }); if( copied == true ) { // increase asset count by 1 if the asset was copied sucessfully Console.WriteLine( "yo..."); drop.AssetCount++; } if( keepOriginal == false ) { // we moved (not copied) so decrease assets count on drop that asset was moved from asset.Drop.AssetCount--; } return copied; } public Asset AddFileInit (Drop drop, string file, string description, string conversion, string pingbackUrl, string outputLocations ) { // get the name of the file string fileName = Path.GetFileName (file); // length of file in bytes long fileLength = new FileInfo (file).Length; // create Stream object for file access Stream fs = new FileStream (file, FileMode.Open, FileAccess.Read); return this.AddFile (drop, fileName, description, fileLength, fs, conversion, pingbackUrl, outputLocations); } public Asset AddFileInit (Drop drop, HttpPostedFile file, string description, string conversion, string pingbackUrl, string outputLocations ) { // get the name of the file string fileName = file.FileName; // length of file in bytes long fileLength = (long)file.ContentLength; // create Stream object for file access Stream fs = file.InputStream; return this.AddFile (drop, fileName, description, fileLength, fs, conversion, pingbackUrl, outputLocations); } /// <summary> /// Adds the file. /// </summary> /// <param name="drop">The drop.</param> /// <param name="fileName">The file.</param> /// <param name="description">The description.</param> /// <param name="fileLength"></param> /// <param name="fs"></param> /// <returns></returns> //public Asset AddFile (Drop drop, string file, string description) public Asset AddFile (Drop drop, string fileName, string description, long fileLength, Stream fs, string conversion, string pingbackUrl, string outputLoations ) { string requestUrl = this.UploadUrl; Hashtable parameters = new Hashtable(); HttpWebRequest request = HttpWebRequest.Create(requestUrl) as HttpWebRequest; string boundary = "DROPIO_MIME_" + DateTime.Now.ToString("yyyyMMddhhmmss"); request.Method = "POST"; request.KeepAlive = true; request.Timeout = 30000000; request.ContentType = "multipart/form-data; boundary=" + boundary + ""; request.Expect = ""; parameters.Add( "drop_name", drop.Name ); if( !String.IsNullOrEmpty(description)) parameters.Add( "description", description ); if( !String.IsNullOrEmpty(conversion) ) parameters.Add( "conversion", conversion ); if( !String.IsNullOrEmpty(pingbackUrl)) parameters.Add( "pingback_url", pingbackUrl ); if( !String.IsNullOrEmpty( outputLoations )) parameters.Add( "output_locations", outputLoations ); AddCommonParameters( ref parameters ); SignIfNeeded( ref parameters ); StringBuilder sb = new StringBuilder(); //string fileName = Path.GetFileName(file); //string fileName = file.FileName; foreach (DictionaryEntry parameter in parameters) { sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"" + parameter.Key + "\"\r\n"); sb.Append("\r\n"); sb.Append(parameter.Value + "\r\n"); } // File sb.Append("--" + boundary + "\r\n"); sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n"); sb.Append("\r\n"); UTF8Encoding encoding = new UTF8Encoding(); byte[] postContents = encoding.GetBytes(sb.ToString()); byte[] postFooter = encoding.GetBytes("\r\n--" + boundary + "--\r\n"); //request.ContentLength = postContents.Length + new FileInfo(file).Length + postFooter.Length; //request.ContentLength = postContents.Length + file.PostedFile.ContentLength + postFooter.Length; request.ContentLength = postContents.Length + fileLength + postFooter.Length; request.AllowWriteStreamBuffering = false; Stream resStream = request.GetRequestStream(); resStream.Write(postContents, 0, postContents.Length); if (OnTransferProgress != null) { OnTransferProgress(this, new TransferProgressEventArgs(postContents.LongLength, request.ContentLength, false)); } //FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); //Stream fs = file.PostedFile.InputStream; long size = Math.Min(Math.Max(request.ContentLength / 100, 50 * 1024), 1024 * 1024); byte[] buffer = new byte[size]; int bytesOut = 0; int bytesSoFar = 0; while ((bytesOut = fs.Read(buffer, 0, buffer.Length)) != 0) { resStream.Write(buffer, 0, bytesOut); bytesSoFar += bytesOut; if (OnTransferProgress != null) { OnTransferProgress(this, new TransferProgressEventArgs(bytesSoFar, request.ContentLength, false)); } } resStream.Write(postFooter, 0, postFooter.Length); if (OnTransferProgress != null) { OnTransferProgress(this, new TransferProgressEventArgs(request.ContentLength, request.ContentLength, true)); } resStream.Close(); fs.Close(); Asset a = null; CompleteRequest(request, delegate(HttpWebResponse response) { ReadResponse(response, delegate(XmlDocument doc) { XmlNode node = doc.SelectSingleNode("/asset"); a = this.CreateAndMapAsset(drop, node); // incease asset count by one drop.AssetCount++; }); }); return a; } /// <summary> /// Handles the exception. /// </summary> /// <param name="exc">The exc.</param> protected void HandleException(WebException exc) { if (exc.Response != null) { if (exc.Response.Headers["Status"].StartsWith("404")) { throw new ServiceException(ServiceError.NotFound, this.ExtractErrorMessage(exc.Response)); } if (exc.Response.Headers["Status"].StartsWith("403")) { throw new ServiceException(ServiceError.NotAuthorized, this.ExtractErrorMessage(exc.Response)); } if (exc.Response.Headers["Status"].StartsWith("400")) { throw new ServiceException(ServiceError.BadRequest, this.ExtractErrorMessage(exc.Response)); } if (exc.Response.Headers["Status"].StartsWith("500")) { throw new ServiceException(ServiceError.ServerError, "There was a problem connecting to Drop.io."); } } throw exc; } public bool ConvertAsset ( Asset asset, List<Hashtable> outputs, string plugin, string pingbackUrl) { // can't do much if we don't have an asset to act on... if (asset == null) throw new ArgumentNullException("asset", "The given asset can't be null"); // get the job type by using the asset's type string type = asset.Type.ToString().ToUpper(); // create the input hash List<Hashtable> inputs = new List<Hashtable>(); Hashtable input = new Hashtable(); input.Add( "asset_id", asset.Id ); input.Add( "role", "original_content"); input.Add( "name", "source"); inputs.Add( input ); // add the "asset_id" param to the outputs hash is it isn't already there foreach( Hashtable hash in outputs) { if( !hash.Contains( "asset_id")) { hash.Add( "asset_id", asset.Id ); } } return this.Convert( type, inputs, outputs, plugin, pingbackUrl ); } public bool Convert (string type, List<Hashtable> inputs, List<Hashtable> outputs, string plugin, string pingbackUrl) { bool success = false; Hashtable parameters = new Hashtable(); // add required parameters for api call parameters.Add ("job_type", type); parameters.Add ("using", plugin); parameters.Add ("inputs", inputs); parameters.Add ("outputs", outputs); // optional parameters for api call if( !string.IsNullOrEmpty( pingbackUrl )) { parameters.Add( "pingback_url", pingbackUrl ); } // do the request HttpWebRequest request = this.CreatePostRequest (this.ApiBaseUrl + JOBS, parameters); CompleteRequest(request, (HttpWebResponse response) => { success = true; }); return success; } public string GetUploadifyForm (Drop drop, Hashtable uploadifyOptions) { Hashtable parameters = new Hashtable (); AddCommonParameters (ref parameters); parameters.Add ("drop_name", drop.Name); StringBuilder sb = new StringBuilder (); sb.AppendLine ("<script type=\"text/javascript\" src=\"uploadify/jquery-1.3.2.min.js\"></script>"); sb.AppendLine ("<script type=\"text/javascript\" src=\"uploadify/swfobject.js\"></script>"); sb.AppendLine ("<script type=\"text/javascript\" src=\"uploadify/jquery.uploadify.v2.1.0.min.js\"></script>"); sb.AppendLine ("<link rel=\"stylesheet\" type=\"text/css\" media=\"screen, projection\" href=\"uploadify/uploadify.css\" />"); sb.AppendLine ("<script type=\"text/javascript\">// <![CDATA["); sb.AppendLine ("$(document).ready(function() {"); sb.AppendLine ("$('#file').uploadify({"); // UPLOADER if ((uploadifyOptions != null) && uploadifyOptions.Contains ("uploader")) { sb.AppendLine ("'uploader':" + uploadifyOptions["uploader"] + ","); uploadifyOptions.Remove ("uploader"); } else sb.AppendLine ("'uploader':'uploadify/uploadify.swf',"); // SCRIPT if ((uploadifyOptions != null) && uploadifyOptions.Contains ("script")) { sb.AppendLine ("'script':" + uploadifyOptions["script"] + ","); uploadifyOptions.Remove ("script"); } else sb.AppendLine ("'script':'" + this.UploadUrl + "',"); // MULTI if ((uploadifyOptions != null) && uploadifyOptions.Contains ("multi")) { sb.AppendLine ("'multi':" + uploadifyOptions["multi"] + ","); uploadifyOptions.Remove ("multi"); } else sb.AppendLine ("'multi':true,"); // SCRIPTDATA if ((uploadifyOptions != null) && uploadifyOptions.Contains ("scriptData")) { // scriptData should be a Hashtable if( uploadifyOptions["scriptData"].GetType() == typeof(Hashtable) ) { Hashtable scriptData = (Hashtable)uploadifyOptions["scriptData"]; foreach( string data in scriptData.Keys) { parameters.Add( data, scriptData[data]); } } sb.Append( "'scriptData': ").AppendLine( ToJson(parameters) + "," ); uploadifyOptions.Remove ("scriptData"); } else sb.Append ("'scriptData': ").AppendLine (ToJson (parameters) + ","); // CANCELIMG if ((uploadifyOptions != null) && uploadifyOptions.Contains ("cancelImg")) { sb.AppendLine ("'cancelImg':" + uploadifyOptions["cancelImg"] + ","); uploadifyOptions.Remove ("cancelImg"); } else sb.AppendLine ("'cancelImg':'uploadify/cancel.png',"); // AUTO if ((uploadifyOptions != null) && uploadifyOptions.Contains ("auto")) { sb.AppendLine ("'auto':" + uploadifyOptions["auto"] + ","); uploadifyOptions.Remove ("auto"); } else sb.AppendLine ("'auto':true,"); // add any other options that don't have default options if (uploadifyOptions != null) { foreach (object obj in uploadifyOptions.Keys) { sb.AppendLine ("'" + obj + "':" + uploadifyOptions[obj] + ","); } } // ONCOMPLETE //sb.AppendLine ("'onComplete' : function(event, queueID, fileObj, response, data){ alert('all done'); }"); sb.AppendLine ("});"); sb.AppendLine ("});"); sb.AppendLine ("// ]]></script>"); return sb.ToString (); } /// <summary> /// Extracts the error message. /// </summary> /// <param name="errorResponse">The error response.</param> /// <returns></returns> protected string ExtractErrorMessage(WebResponse errorResponse) { string message = string.Empty; StreamReader reader = new StreamReader(errorResponse.GetResponseStream()); XmlDocument doc = new XmlDocument(); doc.Load(reader); XmlNodeList nodes = doc.SelectNodes("/response/message"); message = nodes[0].InnerText; return message; } #endregion #region Mapping /// <summary> /// Maps the drop. /// </summary> /// <param name="d">The d.</param> /// <param name="node">The doc.</param> /// <returns></returns> protected void MapDrop(Drop d, XmlNode node) { XmlNode dropNode = node; d.Name = this.ExtractInnerText(dropNode, "name"); d.AssetCount = this.ExtractInt(dropNode, "asset_count"); d.CurrentBytes = this.ExtractInt(dropNode, "current_bytes"); d.MaxBytes = this.ExtractInt(dropNode, "max_bytes"); d.Email = this.ExtractInnerText(dropNode, "email"); d.Description = this.ExtractInnerText(dropNode, "description"); d.ChatPassword = this.ExtractInnerText(dropNode, "chat_password"); } /// <summary> /// Creates and maps a drop. /// </summary> /// <param name="node">The node.</param> /// <returns></returns> protected Drop CreateAndMapDrop(XmlNode node) { Drop d = new Drop(); this.MapDrop(d, node); return d; } /// <summary> /// Creates the and map subscription. /// </summary> /// <param name="d">The d.</param> /// <param name="node">The node.</param> /// <returns></returns> protected Subscription CreateAndMapSubscription(Drop d, XmlNode node) { Subscription s = new Subscription(); this.MapSubscription(d, s, node); return s; } /// <summary> /// Creates the and map asset. /// </summary> /// <param name="d">The d.</param> /// <param name="node">The node.</param> /// <returns></returns> protected Asset CreateAndMapAsset(Drop d, XmlNode node) { Asset a = new Asset(); this.MapAsset(a, d, node); return a; } /// <summary> /// Maps the asset. /// </summary> /// <param name="asset">The asset.</param> /// <param name="drop">The drop.</param> /// <param name="node">The node.</param> protected Asset MapAsset(Asset asset, Drop drop, XmlNode node) { asset.CreatedAt = this.ExtractDateTime(this.ExtractInnerText(node, "created_at")); asset.Filesize = this.ExtractInt(node, "filesize"); asset.Description = this.ExtractInnerText(node, "description"); asset.Title = this.ExtractInnerText(node,"title"); asset.Name = this.ExtractInnerText(node, "name"); asset.Id = this.ExtractInnerText(node, "id"); asset.DropName = this.ExtractInnerText(node, "drop_name"); asset.Type = this.MapAssetType( this.ExtractInnerText(node, "type") ); asset.Drop = drop; asset.Roles = new List<AssetRoleAndLocations>(); XmlNodeList roles = node.SelectNodes( "roles/role"); foreach( XmlNode roleNode in roles ) { AssetRoleAndLocations rolesAndLocations = new AssetRoleAndLocations(); rolesAndLocations.Role = new Hashtable(); rolesAndLocations.Locations = new List<Hashtable>(); foreach( XmlNode roleInfo in roleNode) { if ( roleInfo.Name == "locations") { XmlNodeList locations = roleInfo.SelectNodes( "location" ); foreach( XmlNode locationNode in locations ) { Hashtable temp = new Hashtable(); foreach( XmlNode locationInfo in locationNode ) { // PUT STUFF INTO LOCATION HASH temp.Add( locationInfo.Name, locationInfo.InnerText ); } rolesAndLocations.Locations.Add( temp ); } } else { rolesAndLocations.Role.Add( roleInfo.Name.ToString(), roleInfo.InnerText.ToString() ); } } asset.Roles.Add( rolesAndLocations ); } return asset; } /// <summary> /// /// </summary> /// <param name="Type"> /// A <see cref="System.String"/> /// </param> /// <returns> /// A <see cref="AssetType"/> /// </returns> protected AssetType MapAssetType( string Type ) { switch( Type ) { case "image": return AssetType.Image; case "other": return AssetType.Other; case "audio": return AssetType.Audio; case "document": return AssetType.Document; case "movie": return AssetType.Movie; case "link": return AssetType.Link; default: throw new ArgumentException( "UnknownArgument", "Asset type " + Type + " is unknown" ); } } /// <summary> /// Maps the subscription. /// </summary> /// <param name="subscription">The subscription.</param> /// <param name="drop">The drop.</param> /// <param name="node">The node.</param> protected void MapSubscription(Drop drop, Subscription subscription, XmlNode node) { subscription.Id = this.ExtractInt(node, "id"); //subscription.Message = this.ExtractInnerText(node, "message"); subscription.Type = this.ExtractInnerText(node, "type"); //subscription.Username = this.ExtractInnerText(node, "username"); subscription.Url = this.ExtractInnerText(node, "url"); subscription.Drop = drop; } /// <summary> /// Extracts the boolean. /// </summary> /// <param name="node">The node.</param> /// <param name="path">The path.</param> /// <returns></returns> protected bool ExtractBoolean(XmlNode node, string path) { bool result = false; bool.TryParse(this.ExtractInnerText(node, path), out result); return result; } /// <summary> /// Extracts the int. /// </summary> /// <param name="node">The node.</param> /// <param name="path">The path.</param> /// <returns></returns> protected int ExtractInt(XmlNode node, string path) { string val = this.ExtractInnerText(node, path); if (!string.IsNullOrEmpty(val)) { int result = 0; int.TryParse(val, out result); return result; } return 0; } /// <summary> /// Extracts the inner text. /// </summary> /// <param name="node">The node.</param> /// <param name="path">The path.</param> /// <returns></returns> protected string ExtractInnerText(XmlNode node, string path) { XmlNode result = node.SelectSingleNode(path); if (result != null) { return result.InnerText; } return string.Empty; } /// <summary> /// Extracts the date time. /// </summary> /// <param name="p">The p.</param> /// <returns></returns> protected DateTime ExtractDateTime(string p) { p = p.Replace("UTC", string.Empty); DateTime extracted = DateTime.Now; try { extracted = DateTime.Parse(p); } catch (FormatException) { } return extracted; } #endregion #region HTTP Methods /// <summary> /// Creates the drop URL. /// </summary> /// <param name="dropName">Name of the drop.</param> /// <returns></returns> protected string CreateDropUrl(string dropName) { return this.ApiBaseUrl + DROPS + dropName; } /// <summary> /// Creates the URL responsible for getting back a paginated list of Drops associated with the Manager Account. /// </summary> /// <returns></returns> protected string CreateAllDropsUrl() { return this.ApiBaseUrl + ACCOUNTS + DROPS; } /// <summary> /// Creates the drop empty URL. /// </summary> /// <param name="dropName">Name of the drop.</param> /// <returns></returns> protected string CreateEmptyDropUrl(string dropName) { return this.ApiBaseUrl + DROPS + dropName + EMPTY_DROP; } /// <summary> /// Creates the asset embed code URL. /// </summary> /// <param name="dropName">Name of the drop.</param> /// <param name="assetName">Name of the asset.</param> /// <returns></returns> protected string CreateAssetUrl (string dropName, string assetId, string action) { return this.ApiBaseUrl + DROPS + dropName + ASSETS + assetId + action; } /// <summary> /// Creates the subscription URL. /// </summary> /// <param name="dropName">Name of the drop.</param> /// <returns></returns> protected string CreateSubscriptionsUrl(string dropName) { return this.ApiBaseUrl + DROPS + dropName + SUBSCRIPTIONS; } /// <summary> /// Creates the subscription URL. /// </summary> /// <param name="dropName">Name of the drop.</param> /// <param name="subscriptionId">The subscription id.</param> /// <returns></returns> protected string CreateSubscriptionUrl(string dropName, int subscriptionId) { return this.ApiBaseUrl + DROPS + dropName + SUBSCRIPTIONS + subscriptionId.ToString(); } /// <summary> /// Creates a get request. /// </summary> /// <param name="url"> /// The url. /// </param> /// <returns> /// /// </returns> protected HttpWebRequest CreateUrlEncodedRequest(string method, string url) { return this.CreateUrlEncodedRequest(method, url, new Hashtable() ); } /// <summary> /// Creates the get request. /// </summary> /// <param name="url">The URL.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> protected HttpWebRequest CreateUrlEncodedRequest(string method, string url, Hashtable parameters ) { this.AddCommonParameters( ref parameters ); this.SignIfNeeded( ref parameters ); StringBuilder sb = new StringBuilder( url ); sb.Append( "?" ); int index=0; foreach (string key in parameters.Keys) { index++; sb.Append( HttpUtility.UrlEncode( key ) + "=" + HttpUtility.UrlEncode( parameters[key].ToString() )); if( index < parameters.Count ) sb.Append( "&" ); } HttpWebRequest request = HttpWebRequest.Create(sb.ToString()) as HttpWebRequest; request.Method = method; return request; } /// <summary> /// Creates a post request. /// </summary> /// <param name="url"> /// The parameters. /// </param> /// <param name="parameters"> /// /// </param> /// <returns> /// /// </returns> protected HttpWebRequest CreatePostRequest(string url, Hashtable parameters) { return this.CreateRequestWithParameters(url, "POST", parameters); } /// <summary> /// Creates the request with parameters. /// </summary> /// <param name="url">The url.</param> /// <param name="method">The method.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> protected HttpWebRequest CreateRequestWithParameters(string url, string method, Hashtable parameters) { HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Method = method; request.ContentType = "application/json"; AddCommonParameters( ref parameters ); SignIfNeeded( ref parameters ); StringBuilder p = new StringBuilder( ToJson( parameters )); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(p.ToString()); request.ContentLength = bytes.Length; IAsyncResult result = request.BeginGetRequestStream(null, null); result.AsyncWaitHandle.WaitOne(); using (Stream requestStream = request.EndGetRequestStream(result)) { requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } return request; } /// <summary> /// Creates a put request. /// </summary> /// <param name="url">The url.</param> /// <param name="parameters">The parameters.</param> /// <returns></returns> protected HttpWebRequest CreatePutRequest(string url, Hashtable parameters) { return this.CreateRequestWithParameters(url, "PUT", parameters); } #endregion #region Helpers /// <summary> /// Add the parameters common to all api calls to a <see cref="HashTable"/> of parameters. Parameters added are "version", /// "format" and "api_key" /// </summary> /// <param name="parameters"> /// A <see cref="Hashtable"/> reference /// </param> protected void AddCommonParameters( ref Hashtable parameters ) { parameters.Add( "version", VERSION ); parameters.Add( "format", "xml" ); parameters.Add( "api_key", this.ApiKey ); } /// <summary> /// Takes a <see cref="HashTable"/> containing parameters for an HTTP request and puts them in the form /// "k1=v1&k2=v2&...". Also url encodes all data /// </summary> /// <param name="parameters"> /// A <see cref="Hashtable"/> containing the parameters to be used. /// </param> /// <returns> /// A <see cref="System.String"/> containing the request string that can be added to the end of a url /// </returns> protected string BuildParameterString (Hashtable parameters) { StringBuilder paramString = new StringBuilder (); // iterate through each item in the hashtable... foreach (object parameter in parameters.Keys) { paramString.Append (HttpUtility.UrlEncode ( parameter.ToString() ) + "=" + HttpUtility.UrlEncode ( parameters[parameter].ToString() ) + "&"); } return paramString.ToString(); } /// <summary> /// Convenience function to convert a <see cref="Hashtable"/> of parameters to JSON format. Nested Hashtables are OK. /// </summary> /// <param name="parameters"> /// A <see cref="Hashtable"/> containing the option to JSON-ify /// </param> /// <returns> /// A <see cref="System.String"/> containing valid JSON that represents the <see cref="Hashtable"/> that was given. /// </returns> protected string ToJson (Hashtable parameters) { // pretty simple stuff, C# already has a function to JSON-ify JavaScriptSerializer json = new JavaScriptSerializer (); return json.Serialize (parameters); } /// <summary> /// /// </summary> /// <param name="parameters"> /// A <see cref="Hashtable"/> /// </param> public void SignIfNeeded (ref Hashtable parameters) { // only sign if a secret key has been set if (!String.IsNullOrEmpty (this.ApiSecret)) { // add the timestamp to our parameters string timestamp = GenerateUnixTimestamp ().ToString (); parameters.Add ("timestamp", timestamp); // the parameters must be in alpha order before signing // create an array from the hash keys, and use that to sort the parameters ArrayList ParameterKeys = new ArrayList (parameters.Keys); ParameterKeys.Sort (); // concatenate the parameters and values together then add the secret and sign it StringBuilder StringToSign = new StringBuilder (); foreach (object key in ParameterKeys) { StringToSign.Append (key + "=" + parameters[key]); } string signature = GenerateSignature (StringToSign.Append (this.ApiSecret).ToString ()); // Add signature as a parameter parameters.Add ("signature", signature); } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// BasicOperations operations. /// </summary> internal partial class BasicOperations : IServiceOperations<AzureCompositeModel>, IBasicOperations { /// <summary> /// Initializes a new instance of the BasicOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BasicOperations(AzureCompositeModel client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex type {id: 2, name: 'abc', color: 'YELLOW'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BasicInner>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BasicInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </summary> /// <param name='complexBody'> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(BasicInner complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } string apiVersion = "2016-02-29"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is invalid for the local strong type /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BasicInner>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BasicInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BasicInner>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BasicInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type whose properties are null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BasicInner>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BasicInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type while the server doesn't provide a response /// payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<BasicInner>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<BasicInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<BasicInner>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Diagnostics; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; using System.Threading; namespace ICSimulator { public class Simulator { public static Rand rand; // the network (this owns the Routers, the Nodes and the Links) public static Network network; public static Controller controller; public static Stats stats; public const int DIR_UP = 0; public const int DIR_RIGHT = 1; public const int DIR_DOWN = 2; public const int DIR_LEFT = 3; public const int DIR_BLOCKED = -1; public const int DIR_NONE = -99; public const int DIR_CW = 4; public const int DIR_CCW = 5; // simulator state public static ulong CurrentRound = 0; public static bool Warming = false; public static ulong CurrentBarrier = 0; // MT workloads // ready callback and deferred-callback queue public delegate void Ready(); private static PrioQueue<Simulator.Ready> m_deferQueue = new PrioQueue<Simulator.Ready>(); public static void Main(string[] args) { System.Diagnostics.Process.Start("hostname"); Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; Init(args); RunSimulationRun(); Finish(); } public static void Init(string[] args) { Config config = new Config(); config.read(args); rand = new Rand(Config.rand_seed); CurrentRound = 0; controller = Controller.construct(); network = new Network(Config.network_nrX, Config.network_nrY); network.setup(); Warming = true; } public static void Finish() { if (network.isLivelocked()) Simulator.stats.livelock.Add(); if (!Config.ignore_livelock && network.isLivelocked()) Console.WriteLine("STOPPED DUE TO LIVELOCK."); Simulator.stats.Finish(); using (TextWriter tw = new StreamWriter(Config.output)) { Simulator.stats.DumpJSON(tw); //Simulator.stats.Report(tw); } if (Config.matlab != "") using (TextWriter tw = new StreamWriter(Config.matlab)) { Simulator.stats.DumpMATLAB(tw); } Simulator.network.close(); } public static void RunSimulationRun() { if (File.Exists(Config.output)) { Console.WriteLine("Output file {0} exists; exiting.", Config.output); Environment.Exit(0); } if (Config.RouterEvaluation) RouterEval.evaluate(); else RunSimulation(); Console.WriteLine("simulation finished"); } public static bool DoStep() { // handle pending deferred-callbacks first while (!m_deferQueue.Empty && m_deferQueue.MinPrio <= Simulator.CurrentRound) { m_deferQueue.Dequeue() (); // dequeue and call the callback } if (CurrentRound == (ulong)Config.warmup_cyc) { Console.WriteLine("done warming"); //Console.WriteLine("warmup_cyc {0}",Config.warmup_cyc); //throw new Exception("done warming"); Simulator.stats.Reset(); controller.resetStat(); WarmingStats(); Warming = false; } if (!Warming) Simulator.stats.cycle.Add(); if (CurrentRound % 100000 == 0) ProgressUpdate(); CurrentRound++; network.doStep(); controller.doStep(); return !network.isFinished() && (Config.ignore_livelock || !network.isLivelocked()); } public static void RunSimulation() { while (DoStep()) ; } //static bool isLivelock = false; static void ProgressUpdate() { if (!Config.progress) return; Console.Out.WriteLine("cycle {0}: {1} flits injected, {2} flits arrived, avg total latency {3}", CurrentRound, Simulator.stats.inject_flit.Count, Simulator.stats.eject_flit.Count, Simulator.stats.total_latency.Avg); Console.WriteLine("TimeStamp = {0}",DateTime.Now); } static void WarmingStats() { // TODO: update this for new caches /* int l1_warmblocks = 0, l1_totblocks = 0; int l2_warmblocks = 0, l2_totblocks = 0; foreach (Node n in network.nodes) { l1_warmblocks += n.cpu.Sets.WarmBlocks; l1_totblocks += n.cpu.Sets.TotalBlocks; l2_warmblocks += n.SharedCache.Sets.WarmBlocks; l2_totblocks += n.SharedCache.Sets.TotalBlocks; } Simulator.stats.l1_warmblocks.Add((ulong)l1_warmblocks); Simulator.stats.l1_totblocks.Add((ulong)l1_totblocks); Simulator.stats.l2_warmblocks.Add((ulong)l2_warmblocks); Simulator.stats.l2_totblocks.Add((ulong)l2_totblocks); */ } public static void Defer(Simulator.Ready cb, ulong cyc) { m_deferQueue.Enqueue(cb, cyc); } public static ulong distance(Coord c1, Coord c2) { return (ulong)(Math.Abs(c1.x - c2.x) + Math.Abs(c1.y - c2.y)); } public static ulong distance(Coord c1, int x, int y) { return (ulong)(Math.Abs(c1.x - x) + Math.Abs(c1.y - y)); } // helpers public static bool hasNeighbor(int dir, Router router) { int x, y; x = router.coord.x; y = router.coord.y; switch (dir) { case DIR_DOWN: y--; break; case DIR_UP: y++; break; case DIR_LEFT: x--; break; case DIR_RIGHT: x++; break; } return x >= 0 && x < Config.network_nrX && y >= 0 && y < Config.network_nrY; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System; using System.Collections; using System.Data; using System.IO; using System.Threading.Tasks; using System.Threading; namespace System.Data.Common { public abstract class DbDataReader : IDataReader, IDisposable, IEnumerable { protected DbDataReader() : base() { } abstract public int Depth { get; } abstract public int FieldCount { get; } abstract public bool HasRows { get; } abstract public bool IsClosed { get; } abstract public int RecordsAffected { get; } virtual public int VisibleFieldCount { get { return FieldCount; } } abstract public object this[int ordinal] { get; } abstract public object this[string name] { get; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { } } abstract public string GetDataTypeName(int ordinal); abstract public IEnumerator GetEnumerator(); abstract public Type GetFieldType(int ordinal); abstract public string GetName(int ordinal); abstract public int GetOrdinal(string name); abstract public bool GetBoolean(int ordinal); abstract public byte GetByte(int ordinal); abstract public long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length); abstract public char GetChar(int ordinal); abstract public long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length); public DbDataReader GetData(int ordinal) { return GetDbDataReader(ordinal); } virtual protected DbDataReader GetDbDataReader(int ordinal) { throw ADP.NotSupported(); } abstract public DateTime GetDateTime(int ordinal); abstract public Decimal GetDecimal(int ordinal); abstract public double GetDouble(int ordinal); abstract public float GetFloat(int ordinal); abstract public Guid GetGuid(int ordinal); abstract public Int16 GetInt16(int ordinal); abstract public Int32 GetInt32(int ordinal); abstract public Int64 GetInt64(int ordinal); virtual public Type GetProviderSpecificFieldType(int ordinal) { return GetFieldType(ordinal); } virtual public Object GetProviderSpecificValue(int ordinal) { return GetValue(ordinal); } virtual public int GetProviderSpecificValues(object[] values) { return GetValues(values); } abstract public String GetString(int ordinal); virtual public Stream GetStream(int ordinal) { using (MemoryStream bufferStream = new MemoryStream()) { long bytesRead = 0; long bytesReadTotal = 0; byte[] buffer = new byte[4096]; do { bytesRead = GetBytes(ordinal, bytesReadTotal, buffer, 0, buffer.Length); bufferStream.Write(buffer, 0, (int)bytesRead); bytesReadTotal += bytesRead; } while (bytesRead > 0); return new MemoryStream(bufferStream.ToArray(), false); } } virtual public TextReader GetTextReader(int ordinal) { if (IsDBNull(ordinal)) { return new StringReader(String.Empty); } else { return new StringReader(GetString(ordinal)); } } abstract public Object GetValue(int ordinal); virtual public T GetFieldValue<T>(int ordinal) { return (T)GetValue(ordinal); } public Task<T> GetFieldValueAsync<T>(int ordinal) { return GetFieldValueAsync<T>(ordinal, CancellationToken.None); } virtual public Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<T>(cancellationToken); } else { try { return Task.FromResult<T>(GetFieldValue<T>(ordinal)); } catch (Exception e) { return TaskHelpers.FromException<T>(e); } } } abstract public int GetValues(object[] values); abstract public bool IsDBNull(int ordinal); public Task<bool> IsDBNullAsync(int ordinal) { return IsDBNullAsync(ordinal, CancellationToken.None); } virtual public Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<bool>(cancellationToken); } else { try { return IsDBNull(ordinal) ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return TaskHelpers.FromException<bool>(e); } } } abstract public bool NextResult(); abstract public bool Read(); public Task<bool> ReadAsync() { return ReadAsync(CancellationToken.None); } virtual public Task<bool> ReadAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<bool>(cancellationToken); } else { try { return Read() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return TaskHelpers.FromException<bool>(e); } } } public Task<bool> NextResultAsync() { return NextResultAsync(CancellationToken.None); } virtual public Task<bool> NextResultAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return TaskHelpers.FromCancellation<bool>(cancellationToken); } else { try { return NextResult() ? ADP.TrueTask : ADP.FalseTask; } catch (Exception e) { return TaskHelpers.FromException<bool>(e); } } } public virtual void Close() { } virtual public DataTable GetSchemaTable() { throw new NotSupportedException(); } IDataReader IDataRecord.GetData(int ordinal) { return GetDbDataReader(ordinal); } } }
// http://www.codeproject.com/Articles/39120/Lightweight-C-Command-Line-Parser // License CPOL /* Lightweight C# Command line parser * * Author : Christian Bolterauer * Date : 8-Aug-2009 * Version : 1.0 * Changes : */ using System; using System.Collections; using System.Globalization; using System.Text; /// <summary> /// Command Line Parser. /// </summary> /// <remarks> /// supports: /// - 'unlimited' number of alias names /// - Options starting with '-' or '/' /// - String, Integer and Double parameter options /// - option and parameter attached in one argument (e.g. -P=123 ) or as args pair (e.g. -P 123) /// - handling differnt number decimal seperators /// - provides usage message of available (registered) options ///</remarks> /// namespace CMDLine { /// <summary> /// Command Line Parser for creating and parsing command line options /// </summary> /// <remarks> Throws: MissingOptionException, DuplicateOptionException and if set InvalidOptionsException. /// </remarks> /// <seealso cref="Parse"/> /// <example> /// /// //using CMDLine /// /// //create parser /// CMDLineParser parser = new CMDLineParser(); /// /// //add default help "-help",.. /// parser.AddHelpOption(); /// /// //add Option to parse /// CMDLineParser.Option DebugOption = parser.AddBoolSwitch("-Debug", "Print Debug information"); /// /// //add Alias option name /// DebugOption.AddAlias("/Debug"); /// /// CMDLineParser.NumberOption NegNumOpt = parser.AddDoubleParameter("-NegNum", "A required negativ Number", true); /// /// try /// { /// //parse /// parser.Parse(args); /// } /// catch (CMDLineParser.CMDLineParserException e) /// { /// Console.WriteLine("Error: " + e.Message); /// parser.HelpMessage(); /// } /// parser.Debug(); /// ///</example> class CMDLineParser { private string[] _cmdlineArgs = null; private System.Collections.ArrayList SwitchesStore = null; private ArrayList _matchedSwitches = null; private ArrayList _unmatchedArgs = null; private ArrayList _invalidArgs = null; private CMDLineParser.Option _help = null; /// <summary> ///collect not matched (invalid) command line options as invalid args /// </summary> public bool collectInvalidOptions = true; /// <summary> ///throw an exception if not matched (invalid) command line options were detected /// </summary> public bool throwInvalidOptionsException = false; public bool isConsoleApplication = true; /// <summary> /// create a Command Line Parser for creating and parsing command line options /// </summary> public CMDLineParser() {} /// <summary> /// Add a default help switch "-help","-h","-?","/help" /// </summary> public Option AddHelpOption() { _help = this.AddBoolSwitch("-help", "Command line help"); _help.AddAlias("-h"); _help.AddAlias("-?"); _help.AddAlias("/help"); return (_help); } /// <summary> /// Parses the command line and sets the values of each registered switch /// or parameter option. /// </summary> /// <param name="args">The arguments array sent to Main(string[] args)</param> /// <returns>'true' if all parsed options are valid otherwise 'false'</returns> /// <exception cref="MissingOptionException"></exception> /// <exception cref="DuplicateOptionException"></exception> /// <exception cref="InvalidOptionsException"></exception> public bool Parse(string[] args) { this.Clear(); _cmdlineArgs = args; ParseOptions(); if (_invalidArgs.Count > 0) { if (throwInvalidOptionsException) { string iopts = ""; foreach (string arg in _invalidArgs) { iopts += "'" + arg + "';"; } throw new InvalidOptionsException("Invalid command line argument(s): " + iopts); } return false; } else { return true; } } /// <summary> /// Reset Parser and values of registed options. /// </summary> public void Clear() { _matchedSwitches = null; _unmatchedArgs = null; _invalidArgs = null; if (SwitchesStore != null) { foreach (Option s in SwitchesStore) { s.Clear(); } } } /// <summary> /// Add (a custom) Option (Optional) /// </summary> /// <remarks> /// To add instances (or subclasses) of 'CMDLineParser.Option' /// that implement: /// <code>'public override object parseValue(string parameter)'</code> /// </remarks> /// <param name="opt">subclass from 'CMDLineParser.Option'</param> /// <seealso cref="AddBoolSwitch"/> /// <seealso cref="AddStringParameter"/> public void AddOption(Option opt) { CheckCmdLineOption(opt.Name); if (SwitchesStore == null) SwitchesStore = new System.Collections.ArrayList(); SwitchesStore.Add(opt); } /// <summary> /// Add a basic command line switch. /// (exist = 'true' otherwise 'false'). /// </summary> public Option AddBoolSwitch(string name, string description) { Option opt = new Option(name, description, typeof(bool), false, false); AddOption(opt); return (opt); } /// <summary> /// Add a string parameter command line option. /// </summary> public Option AddStringParameter(string name, string description,bool required) { Option opt = new Option(name, description, typeof(string), true, required); AddOption(opt); return (opt); } /// <summary> /// Add a Integer parameter command line option. /// </summary> public NumberOption AddIntParameter(string name, string description, bool required) { NumberOption opt = new NumberOption(name, description, typeof(int), true, required); opt.NumberStyle = NumberStyles.Integer; AddOption(opt); return (opt); } /// <summary> /// Add a Double parameter command line option. /// </summary> public NumberOption AddDoubleParameter(string name, string description,bool required) { NumberOption opt = new NumberOption(name, description, typeof(double), true, required); opt.NumberStyle = NumberStyles.Float; AddOption(opt); return (opt); } /// <summary> /// Add a Double parameter command line option. /// </summary> public NumberOption AddDoubleParameter(string name, string description, bool required, NumberFormatInfo numberformat ) { NumberOption opt = new NumberOption(name, description, typeof(double), true, required); opt.NumberFormat = numberformat; opt.parseDecimalSeperator = false; opt.NumberStyle = NumberStyles.Float | NumberStyles.AllowThousands; AddOption(opt); return (opt); } /// <summary> /// Check if name is a valid Option name /// </summary> /// <param name="name"></param> /// <exception cref="CMDLineParseException"></exception> private void CheckCmdLineOption(string name) { if (!isASwitch(name)) throw new CMDLineParserException("Invalid Option:'" + name + "'::" + IS_NOT_A_SWITCH_MSG); } // protected const string IS_NOT_A_SWITCH_MSG = "The Switch name does not start with an switch identifier '-' or '/' or contains space!"; protected static bool isASwitch(string arg) { return ((arg.StartsWith("-") || arg.StartsWith("/")) & (!arg.Contains(" ")) ); } private void ParseOptions() { _matchedSwitches = new ArrayList(); _unmatchedArgs = new ArrayList(); _invalidArgs = new ArrayList(); if (_cmdlineArgs != null && SwitchesStore != null) { for (int idx = 0; idx < _cmdlineArgs.Length; idx++) { string arg = _cmdlineArgs[idx]; bool found = false; foreach (Option s in SwitchesStore) { if (compare(s,arg)) { s.isMatched = found = true; _matchedSwitches.Add(s); idx=processMatchedSwitch(s, _cmdlineArgs,idx); } } if (found == false) processUnmatchedArg(arg); } checkReqired(); } } private void checkReqired() { foreach (Option s in SwitchesStore) { if(s.isRequired && (!s.isMatched)) throw new MissingRequiredOptionException("Missing Required Option:'" + s.Name + "'"); } } private bool compare(Option s, string arg) { if (!s.needsValue) { foreach (string optname in s.Names) { if (optname.Equals(arg)) { s.Name = optname; //set name in case we match an alias name return (true); } } return false; } else { foreach (string optname in s.Names) { if (arg.StartsWith(optname)) { checkDuplicateAndSetName(s, optname); return (true); } } return false; } } private void checkDuplicateAndSetName(Option s, string optname) { if (s.isMatched && s.needsValue) throw new DuplicateOptionException("Duplicate: The Option:'" + optname + "' allready exists on the comand line as +'" + s.Name + "'"); else { s.Name = optname; //set name in case we match an alias name } } private int retrieveParameter(ref string parameter, string optname, string[] cmdlineArgs, int pos) { if (cmdlineArgs[pos].Length == optname.Length) // arg must be in next cmdlineArg { if (cmdlineArgs.Length > pos + 1) { pos++; //change command line index to next cmdline Arg. parameter = cmdlineArgs[pos]; } } else { parameter = (cmdlineArgs[pos].Substring(optname.Length)); } return pos; } protected int processMatchedSwitch(Option s, string[] cmdlineArgs, int pos) { //if help switch is matched give help .. only works for console apps if (s.Equals(_help)) { if (isConsoleApplication) { Console.Write(this.HelpMessage()); } } //process bool switch if (s.Type == typeof(bool) && s.needsValue == false) { s.Value = true; return pos; } if (s.needsValue == true) { //retrieve parameter value and adjust pos string parameter = ""; pos = retrieveParameter(ref parameter, s.Name, cmdlineArgs, pos); //parse option using 'IParsableOptionParameter.parseValue(parameter)' //and set parameter value try { if (s.Type != null) { ((IParsableOptionParameter)s).Value = ((IParsableOptionParameter)s).parseValue(parameter); return pos; } } catch (Exception ex) { throw new ParameterConversionException(ex.Message); } } //unsupported type .. throw new CMDLineParserException("Unsupported Parameter Type:" + s.Type); } protected void processUnmatchedArg(string arg) { if (collectInvalidOptions && isASwitch(arg) ) //assuming an invalid comand line option { _invalidArgs.Add(arg); //collect first, throw Exception later if set.. } else { _unmatchedArgs.Add(arg); } } /// <summary> /// String array of remaining arguments not identified as command line options /// </summary> public String[] RemainingArgs() { if (_unmatchedArgs == null) return null; return ((String[])_unmatchedArgs.ToArray(typeof(string))); } /// <summary> /// String array of matched command line options /// </summary> public String[] matchedOptions() { if (_matchedSwitches == null) return null; ArrayList names = new ArrayList(); for (int s = 0; s < _matchedSwitches.Count; s++) names.Add( ((Option)_matchedSwitches[s]).Name); return ((String[])names.ToArray(typeof(string))); } /// <summary> /// String array of not identified command line options /// </summary> public String[] invalidArgs() { if (_invalidArgs == null) return null; return ((String[]) _invalidArgs.ToArray(typeof(string))); } /// <summary> /// Create usage: A formated help message with a list of registered command line options. /// </summary> public string HelpMessage() { const string indent = " "; int ind = indent.Length; const int spc = 3; int len = 0; foreach (Option s in SwitchesStore) { foreach (string name in s.Names) { int nlen = name.Length; if (s.needsValue) nlen += (" [..]").Length; len = Math.Max(len, nlen); } } string help = "\nCommand line options are:\n\n"; bool req = false; foreach (Option s in SwitchesStore) { string line = indent + s.Names[0]; if (s.needsValue) line += " [..]"; while (line.Length < len + spc + ind) line += " "; if (s.isRequired) { line += "(*) "; req = true; } line += s.Description; help += line + "\n"; if (s.Aliases != null && s.Aliases.Length > 0) { foreach (string name in s.Aliases) { line = indent + name; if (s.needsValue) line += " [..]"; help += line + "\n"; } } help += "\n"; } if(req) help += "(*) Required.\n"; return help; } /// <summary> /// Print debug information of this CMDLineParser to the system console. /// </summary> public void Debug() { Console.WriteLine(); Console.WriteLine("\n------------- DEBUG CMDLineParser -------------\n"); if (SwitchesStore != null) { Console.WriteLine("There are {0} registered switches:", SwitchesStore.Count); foreach (Option s in SwitchesStore) { Console.WriteLine("Command : {0} : [{1}]", s.Names[0], s.Description); Console.Write("Type : {0} ", s.Type); Console.WriteLine(); if (s.Aliases != null) { Console.Write("Aliases : [{0}] : ", s.Aliases.Length); foreach (string alias in s.Aliases) Console.Write(" {0}", alias); Console.WriteLine(); } Console.WriteLine("Required: {0}", s.isRequired); Console.WriteLine("Value is: {0} \n", s.Value != null ? s.Value : "(Unknown)"); } } else { Console.WriteLine("There are no registered switches."); } if (_matchedSwitches != null) { if (_matchedSwitches.Count > 0) { Console.WriteLine("\nThe following switches were found:"); foreach (Option s in _matchedSwitches) { Console.WriteLine(" {0} Value:{1}", s.Name != null ? s.Name : "(Unknown)", s.Value != null ? s.Value : "(Unknown)"); } } else { Console.WriteLine("\nNo Command Line Options detected."); } } Console.Write(InvalidArgsMessage()); Console.WriteLine("\n----------- DEBUG CMDLineParser END -----------\n"); } private string InvalidArgsMessage() { const string indent = " "; string msg = ""; if (_invalidArgs != null) { msg += "\nThe following args contain invalid (unknown) options:"; if (_invalidArgs.Count > 0) { foreach (string s in _invalidArgs) { msg += "\n" + indent + s; } } else { msg += "\n"+ indent+ "- Non -"; } } return msg + "\n"; } /// <summary> /// Interface supporting parsing and setting of string parameter Values to objects /// </summary> private interface IParsableOptionParameter { /// <summary> /// parse string parameter to convert to an object /// </summary> /// <param name="parameter"></param> /// <returns>an object</returns> object parseValue(string parameter); /// <summary> /// Get or Set the value /// </summary> object Value { get; set; } } /// <summary> /// A comand line Option: A switch or a string parameter option. /// </summary> /// <remarks> Use AddBoolSwitch(..) or AddStringParameter(..) (Factory) /// Methods to create and store a new parsable 'CMDLineParser.Option'. /// </remarks> public class Option : IParsableOptionParameter { private System.Collections.ArrayList _Names = null; private bool _matched = false; private string _name = ""; private string _description = ""; private object _value = null; private System.Type _switchType; private bool _needsVal = false; private bool _required = false; private Option() { } public Option(string name, string description, System.Type type, bool hasval, bool required) { _switchType = type; _needsVal = hasval; _required = required; Initialize(name, description); } private void Initialize(string name, string description) { _name = name; _description = description; _Names = new System.Collections.ArrayList(); _Names.Add(name); } public void AddAlias(string alias) { if (!CMDLineParser.isASwitch(alias)) throw new CMDLineParserException("Invalid Option:'" + alias + "'::" + IS_NOT_A_SWITCH_MSG); if (_Names == null) _Names = new System.Collections.ArrayList(); _Names.Add(alias); } public void Clear() { _matched = false; _value = null; } //getters and setters public string Name { get { return _name; } set { _name = value; } } public string Description { get { return _description; } set { _description = value; } } /// <summary> /// Object Type of Option Value (e.g. typeof(int)) /// </summary> public System.Type Type { get { return _switchType; } } public bool needsValue { get { return _needsVal; } } public bool isRequired { get { return _required; } set { _required = value; } } /// <summary> /// set to 'true' if Option has been detected on the command line /// </summary> public bool isMatched { get { return _matched; } set { _matched = value; } } public string[] Names { get { return (_Names != null) ? (string[])_Names.ToArray(typeof(string)) : null; } } public string[] Aliases { get { if (_Names == null) return null; ArrayList list = new ArrayList(_Names); list.RemoveAt(0); //remove 'name' (first element) from the list to leave aliases only return (string[])list.ToArray(typeof(string)); } } public object Value { get { return (_value); } set { _value = value; } } #region IParsableOptionParameter Member /// <summary> /// Default implementation of parseValue: /// Subclasses should override this method to provide a method for converting /// the parsed string parameter to its Object type /// </summary> /// <param name="parameter"></param> /// <returns>converted value</returns> /// <see cref="NumberOption.parseValue"/> public virtual object parseValue(string parameter) { //set string parameter if (Type == typeof(string) && needsValue == true ) { return(parameter);//string needs no parsing (conversion) to string... } else { //throw Exception when parseValue has not been implemented by a subclass throw new Exception("Option is missing an method to convert the value."); } } #endregion } /// <summary> /// An command line option with a Number parameter. /// </summary> ///<remarks> /// To avoid unpredictable results on plattforms that use different 'Culture' settings /// the default is set to 'invariant Culture' and parseDecimalSeperator=true; /// The number format can be changed for each CMDLineParser.NumberOption individually for /// more strict parsing. ///</remarks> public class NumberOption : Option { /// <summary> /// If set to true the parser tries to detect and set the Decimalseparetor ("." or ",") /// automaticly. (default=true) /// </summary> public bool parseDecimalSeperator = true; private NumberFormatInfo _numberformat = null; private NumberStyles _numberstyle; /// <summary> /// Get or Set the NumberFormat Information for parsing the parameter /// </summary> public NumberFormatInfo NumberFormat { get { return _numberformat; } set { _numberformat = value;} } /// <summary> /// Get or Set the NumberStyle for parsing the parameter /// </summary> public NumberStyles NumberStyle { get { return _numberstyle; } set { _numberstyle = value; } } public NumberOption(string name, string description, System.Type type, bool hasval, bool required) : base(name,description,type,hasval,required) { //use invariant Culture as default _numberformat = (new CultureInfo("", false)).NumberFormat; } public override object parseValue(string parameter) { // int parameter if (base.Type == typeof(int)) { return parseIntValue(parameter); } // double parameter if (base.Type == typeof(double)) { return parseDoubleValue(parameter); } throw new ParameterConversionException("Invalid Option Type: " + base.Type); } // private int parseIntValue(string parameter) { try { return (System.Int32.Parse(parameter, _numberstyle, _numberformat)); } catch (Exception e) { throw new ParameterConversionException("Invalid Int Parameter:" + parameter + " - " + e.Message); } } // private double parseDoubleValue(string parameter) { if (parseDecimalSeperator) SetIdentifiedDecimalSeperator(parameter); try { return (System.Double.Parse(parameter, _numberstyle, _numberformat)); } catch (Exception e) { throw new ParameterConversionException("Invalid Double Parameter:" + parameter + " - " + e.Message); } } // private void SetIdentifiedDecimalSeperator(string parameter) { if (_numberformat.NumberDecimalSeparator == "." && parameter.Contains(",") && !(parameter.Contains("."))) { _numberformat.NumberDecimalSeparator = ","; if (_numberformat.NumberGroupSeparator == ",") _numberformat.NumberGroupSeparator = "."; } else { if (_numberformat.NumberDecimalSeparator == "," && parameter.Contains(".") && !(parameter.Contains(","))) { _numberformat.NumberDecimalSeparator = "."; if (_numberformat.NumberGroupSeparator == ".") _numberformat.NumberGroupSeparator = ","; } } } } /// <summary> /// Command line parsing Exception. /// </summary> [Serializable] public class CMDLineParserException : Exception { public CMDLineParserException(string message) : base(message) {} } /// <summary> /// Thrown when required option was not detected /// </summary> [Serializable] public class MissingRequiredOptionException : CMDLineParserException { public MissingRequiredOptionException(string message) : base(message) { } } /// <summary> /// Thrown when invalid (not registered) options have been detected /// </summary> [Serializable] public class InvalidOptionsException : CMDLineParserException { public InvalidOptionsException(string message) : base(message) {} } /// <summary> /// Thrown when duplicate option was detected /// </summary> [Serializable] public class DuplicateOptionException : CMDLineParserException { public DuplicateOptionException(string message) : base(message) { } } /// <summary> /// Thrown when parameter value conversion to specified type failed /// </summary> [Serializable] public class ParameterConversionException : CMDLineParserException { public ParameterConversionException(string message) : base(message) { } } } }
namespace java.lang { [global::MonoJavaBridge.JavaClass()] public sealed partial class Float : java.lang.Number, Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Float() { InitJNI(); } internal Float(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _equals12958; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Float._equals12958, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._equals12958, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString12959; public static global::java.lang.String toString(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Float.staticClass, global::java.lang.Float._toString12959, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _toString12960; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.Float._toString12960)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._toString12960)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode12961; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Float._hashCode12961); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._hashCode12961); } internal static global::MonoJavaBridge.MethodId _floatToRawIntBits12962; public static int floatToRawIntBits(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Float.staticClass, global::java.lang.Float._floatToRawIntBits12962, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _floatToIntBits12963; public static int floatToIntBits(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Float.staticClass, global::java.lang.Float._floatToIntBits12963, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _intBitsToFloat12964; public static float intBitsToFloat(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticFloatMethod(java.lang.Float.staticClass, global::java.lang.Float._intBitsToFloat12964, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo12965; public int compareTo(java.lang.Float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Float._compareTo12965, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._compareTo12965, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo12966; public int compareTo(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Float._compareTo12966, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._compareTo12966, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toHexString12967; public static global::java.lang.String toHexString(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Float.staticClass, global::java.lang.Float._toHexString12967, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _valueOf12968; public static global::java.lang.Float valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Float.staticClass, global::java.lang.Float._valueOf12968, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Float; } internal static global::MonoJavaBridge.MethodId _valueOf12969; public static global::java.lang.Float valueOf(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Float.staticClass, global::java.lang.Float._valueOf12969, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Float; } internal static global::MonoJavaBridge.MethodId _compare12970; public static int compare(float arg0, float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Float.staticClass, global::java.lang.Float._compare12970, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isNaN12971; public static bool isNaN(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(java.lang.Float.staticClass, global::java.lang.Float._isNaN12971, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isNaN12972; public bool isNaN() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Float._isNaN12972); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._isNaN12972); } internal static global::MonoJavaBridge.MethodId _parseFloat12973; public static float parseFloat(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticFloatMethod(java.lang.Float.staticClass, global::java.lang.Float._parseFloat12973, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isInfinite12974; public static bool isInfinite(float arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(java.lang.Float.staticClass, global::java.lang.Float._isInfinite12974, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isInfinite12975; public bool isInfinite() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Float._isInfinite12975); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._isInfinite12975); } internal static global::MonoJavaBridge.MethodId _byteValue12976; public sealed override byte byteValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallByteMethod(this.JvmHandle, global::java.lang.Float._byteValue12976); else return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._byteValue12976); } internal static global::MonoJavaBridge.MethodId _shortValue12977; public sealed override short shortValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::java.lang.Float._shortValue12977); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._shortValue12977); } internal static global::MonoJavaBridge.MethodId _intValue12978; public sealed override int intValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Float._intValue12978); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._intValue12978); } internal static global::MonoJavaBridge.MethodId _longValue12979; public sealed override long longValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.lang.Float._longValue12979); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._longValue12979); } internal static global::MonoJavaBridge.MethodId _floatValue12980; public sealed override float floatValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::java.lang.Float._floatValue12980); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._floatValue12980); } internal static global::MonoJavaBridge.MethodId _doubleValue12981; public sealed override double doubleValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::java.lang.Float._doubleValue12981); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.lang.Float.staticClass, global::java.lang.Float._doubleValue12981); } internal static global::MonoJavaBridge.MethodId _Float12982; public Float(float arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Float.staticClass, global::java.lang.Float._Float12982, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Float12983; public Float(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Float.staticClass, global::java.lang.Float._Float12983, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Float12984; public Float(double arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Float.staticClass, global::java.lang.Float._Float12984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.Float.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Float")); global::java.lang.Float._equals12958 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.lang.Float._toString12959 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "toString", "(F)Ljava/lang/String;"); global::java.lang.Float._toString12960 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "toString", "()Ljava/lang/String;"); global::java.lang.Float._hashCode12961 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "hashCode", "()I"); global::java.lang.Float._floatToRawIntBits12962 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "floatToRawIntBits", "(F)I"); global::java.lang.Float._floatToIntBits12963 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "floatToIntBits", "(F)I"); global::java.lang.Float._intBitsToFloat12964 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "intBitsToFloat", "(I)F"); global::java.lang.Float._compareTo12965 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "compareTo", "(Ljava/lang/Float;)I"); global::java.lang.Float._compareTo12966 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "compareTo", "(Ljava/lang/Object;)I"); global::java.lang.Float._toHexString12967 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "toHexString", "(F)Ljava/lang/String;"); global::java.lang.Float._valueOf12968 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Float;"); global::java.lang.Float._valueOf12969 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "valueOf", "(F)Ljava/lang/Float;"); global::java.lang.Float._compare12970 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "compare", "(FF)I"); global::java.lang.Float._isNaN12971 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "isNaN", "(F)Z"); global::java.lang.Float._isNaN12972 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "isNaN", "()Z"); global::java.lang.Float._parseFloat12973 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "parseFloat", "(Ljava/lang/String;)F"); global::java.lang.Float._isInfinite12974 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Float.staticClass, "isInfinite", "(F)Z"); global::java.lang.Float._isInfinite12975 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "isInfinite", "()Z"); global::java.lang.Float._byteValue12976 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "byteValue", "()B"); global::java.lang.Float._shortValue12977 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "shortValue", "()S"); global::java.lang.Float._intValue12978 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "intValue", "()I"); global::java.lang.Float._longValue12979 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "longValue", "()J"); global::java.lang.Float._floatValue12980 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "floatValue", "()F"); global::java.lang.Float._doubleValue12981 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "doubleValue", "()D"); global::java.lang.Float._Float12982 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "<init>", "(F)V"); global::java.lang.Float._Float12983 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "<init>", "(Ljava/lang/String;)V"); global::java.lang.Float._Float12984 = @__env.GetMethodIDNoThrow(global::java.lang.Float.staticClass, "<init>", "(D)V"); } } }
// 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.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Diagnostics.Contracts; namespace System.Windows.Forms { // Summary: // Represents a small rectangular pop-up window that displays a brief description // of a control's purpose when the user rests the pointer on the control. //[DefaultEvent("Popup")] //[ProvideProperty("ToolTip", typeof(Control))] //[ToolboxItemFilter("System.Windows.Forms")] public class ToolTip // : Component, IExtenderProvider { // Summary: // Initializes a new instance of the System.Windows.Forms.ToolTip without a // specified container. //public ToolTip(); // // Summary: // Initializes a new instance of the System.Windows.Forms.ToolTip class with // a specified container. // // Parameters: // cont: // An System.ComponentModel.IContainer that represents the container of the // System.Windows.Forms.ToolTip. public ToolTip(IContainer cont) { Contract.Requires(cont != null); } // Summary: // Gets or sets a value indicating whether the ToolTip is currently active. // // Returns: // true if the ToolTip is currently active; otherwise, false. The default is // true. //[DefaultValue(true)] //public bool Active { get; set; } // // Summary: // Gets or sets the automatic delay for the ToolTip. // // Returns: // The automatic delay, in milliseconds. The default is 500. //[DefaultValue(500)] //[RefreshProperties(RefreshProperties.All)] public int AutomaticDelay { get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } set { Contract.Requires(value >= 0); } } // // Summary: // Gets or sets the period of time the ToolTip remains visible if the pointer // is stationary on a control with specified ToolTip text. // // Returns: // The period of time, in milliseconds, that the System.Windows.Forms.ToolTip // remains visible when the pointer is stationary on a control. The default // value is 5000. //[RefreshProperties(RefreshProperties.All)] public int AutoPopDelay { get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } set { Contract.Requires(value >= 0); } } // // Summary: // Gets or sets the background color for the ToolTip. // // Returns: // The background System.Drawing.Color. //[DefaultValue(typeof(Color), "Info")] //public Color BackColor { get; set; } // // Summary: // Gets the creation parameters for the ToolTip window. // // Returns: // A System.Windows.Forms.CreateParams containing the information needed to // create the ToolTip. //protected virtual CreateParams CreateParams { get; } // // Summary: // Gets or sets the foreground color for the ToolTip. // // Returns: // The foreground System.Drawing.Color. //[DefaultValue(typeof(Color), "InfoText")] public Color ForeColor { get { Contract.Ensures(!Contract.Result<Color>().IsEmpty); return default(Color); } set { Contract.Requires(!value.IsEmpty); } } // // Summary: // Gets or sets the time that passes before the ToolTip appears. // // Returns: // The period of time, in milliseconds, that the pointer must remain stationary // on a control before the ToolTip window is displayed. //[RefreshProperties(RefreshProperties.All)] public int InitialDelay { get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } set { Contract.Requires(value >= 0); } } // // Summary: // Gets or sets a value indicating whether the ToolTip should use a balloon // window. // // Returns: // true if a balloon window should be used; otherwise, false if a standard rectangular // window should be used. The default is false. //[DefaultValue(false)] //public bool IsBalloon { get; set; } // // Summary: // Gets or sets a value indicating whether the ToolTip is drawn by the operating // system or by code that you provide. // // Returns: // true if the System.Windows.Forms.ToolTip is drawn by code that you provide; // false if the System.Windows.Forms.ToolTip is drawn by the operating system. // The default is false. //[DefaultValue(false)] //public bool OwnerDraw { get; set; } // // Summary: // Gets or sets the length of time that must transpire before subsequent ToolTip // windows appear as the pointer moves from one control to another. // // Returns: // The length of time, in milliseconds, that it takes subsequent ToolTip windows // to appear. //[RefreshProperties(RefreshProperties.All)] public int ReshowDelay { get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } set { Contract.Requires(value >= 0); } } // // Summary: // Gets or sets a value indicating whether a ToolTip window is displayed, even // when its parent control is not active. // // Returns: // true if the ToolTip is always displayed; otherwise, false. The default is // false. //[DefaultValue(false)] //public bool ShowAlways { get; set; } // // Summary: // Gets or sets a value that determines how ampersand (&) characters are treated. // // Returns: // true if ampersand characters are stripped from the ToolTip text; otherwise, // false. The default is false. //[Browsable(true)] //[DefaultValue(false)] //public bool StripAmpersands { get; set; } // // Summary: // Gets or sets the object that contains programmer-supplied data associated // with the System.Windows.Forms.ToolTip. // // Returns: // An System.Object that contains data about the System.Windows.Forms.ToolTip. // The default is null. //[Localizable(false)] //[Bindable(true)] //[DefaultValue("")] //[TypeConverter(typeof(StringConverter))] //public object Tag { get; set; } // // Summary: // Gets or sets a value that defines the type of icon to be displayed alongside // the ToolTip text. // // Returns: // One of the System.Windows.Forms.ToolTipIcon enumerated values. //public ToolTipIcon ToolTipIcon { get; set; } // // Summary: // Gets or sets a title for the ToolTip window. // // Returns: // A System.String containing the window title. //[DefaultValue("")] //public string ToolTipTitle { get; set; } // // Summary: // Gets or sets a value determining whether an animation effect should be used // when displaying the ToolTip. // // Returns: // true if window animation should be used; otherwise, false. The default is // true. //[Browsable(true)] //[DefaultValue(true)] //public bool UseAnimation { get; set; } // // Summary: // Gets or sets a value determining whether a fade effect should be used when // displaying the ToolTip. // // Returns: // true if window fading should be used; otherwise, false. The default is true. //[DefaultValue(true)] //[Browsable(true)] //public bool UseFading { get; set; } // Summary: // Occurs when the ToolTip is drawn and the System.Windows.Forms.ToolTip.OwnerDraw // property is set to true. //public event DrawToolTipEventHandler Draw; // // Summary: // Occurs before a ToolTip is initially displayed. This is the default event // for the System.Windows.Forms.ToolTip class. //public event PopupEventHandler Popup; // Summary: // Returns true if the ToolTip can offer an extender property to the specified // target component. // // Parameters: // target: // The target object to add an extender property to. // // Returns: // true if the System.Windows.Forms.ToolTip class can offer one or more extender // properties; otherwise, false. [Pure] public virtual bool CanExtend(object target) { return default(bool); } // // Summary: // Disposes of the System.Windows.Forms.ToolTip component. // // Parameters: // disposing: // true to release both managed and unmanaged resources; false to release only // unmanaged resources. //protected override void Dispose(bool disposing); // // Summary: // Retrieves the ToolTip text associated with the specified control. // // Parameters: // control: // The System.Windows.Forms.Control for which to retrieve the System.Windows.Forms.ToolTip // text. // // Returns: // A System.String containing the ToolTip text for the specified control. //[DefaultValue("")] //[Localizable(true)] //[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] [Pure] public string GetToolTip(Control control) { Contract.Ensures(Contract.Result<string>() != null); return default(string); } // // Summary: // Hides the specified ToolTip window. // // Parameters: // win: // The System.Windows.Forms.IWin32Window of the associated window or control // that the ToolTip is associated with. // // Exceptions: // System.ArgumentNullException: // win is null. public void Hide(IWin32Window win) { Contract.Requires(win != null); } // // Summary: // Removes all ToolTip text currently associated with the ToolTip component. //public void RemoveAll(); // // Summary: // Associates ToolTip text with the specified control. // // Parameters: // control: // The System.Windows.Forms.Control to associate the ToolTip text with. // // caption: // The ToolTip text to display when the pointer is on the control. //public void SetToolTip(Control control, string caption); // // Summary: // Sets the ToolTip text associated with the specified control, and displays // the ToolTip modally. // // Parameters: // text: // A System.String containing the new ToolTip text. // // window: // The System.Windows.Forms.Control to display the ToolTip for. // // Exceptions: // System.ArgumentNullException: // The window parameter is null. public void Show(string text, IWin32Window window) { Contract.Requires(window != null); } // // Summary: // Sets the ToolTip text associated with the specified control, and then displays // the ToolTip for the specified duration. // // Parameters: // text: // A System.String containing the new ToolTip text. // // window: // The System.Windows.Forms.Control to display the ToolTip for. // // duration: // An System.Int32 containing the duration, in milliseconds, to display the // ToolTip. // // Exceptions: // System.ArgumentNullException: // The window parameter is null. // // System.ArgumentOutOfRangeException: // duration is less than or equal to 0. [Pure] public void Show(string text, IWin32Window window, int duration) { Contract.Requires(window != null); Contract.Requires(duration >= 0); } // Summary: // Sets the ToolTip text associated with the specified control, and then displays // the ToolTip modally at the specified relative position. // // Parameters: // text: // A System.String containing the new ToolTip text. // // window: // The System.Windows.Forms.Control to display the ToolTip for. // // point: // A System.Drawing.Point containing the offset, in pixels, relative to the // upper-left corner of the associated control window, to display the ToolTip. // // Exceptions: // System.ArgumentNullException: // The window parameter is null. [Pure] public void Show(string text, IWin32Window window, Point point) { Contract.Requires(window != null); } // // Summary: // Sets the ToolTip text associated with the specified control, and then displays // the ToolTip modally at the specified relative position. // // Parameters: // text: // A System.String containing the new ToolTip text. // // window: // The System.Windows.Forms.Control to display the ToolTip for. // // x: // The horizontal offset, in pixels, relative to the upper-left corner of the // associated control window, to display the ToolTip. // // y: // The vertical offset, in pixels, relative to the upper-left corner of the // associated control window, to display the ToolTip. [Pure] public void Show(string text, IWin32Window window, int x, int y) { Contract.Requires(window != null); } // // Summary: // Sets the ToolTip text associated with the specified control, and then displays // the ToolTip for the specified duration at the specified relative position. // // Parameters: // text: // A System.String containing the new ToolTip text. // // window: // The System.Windows.Forms.Control to display the ToolTip for. // // point: // A System.Drawing.Point containing the offset, in pixels, relative to the // upper-left corner of the associated control window, to display the ToolTip. // // duration: // An System.Int32 containing the duration, in milliseconds, to display the // ToolTip. // // Exceptions: // System.ArgumentNullException: // The window parameter is null. // // System.ArgumentOutOfRangeException: // duration is less than or equal to 0. [Pure] public void Show(string text, IWin32Window window, Point point, int duration) { Contract.Requires(window != null); Contract.Requires(duration >= 0); } // // Summary: // Sets the ToolTip text associated with the specified control, and then displays // the ToolTip for the specified duration at the specified relative position. // // Parameters: // text: // A System.String containing the new ToolTip text. // // window: // The System.Windows.Forms.Control to display the ToolTip for. // // x: // The horizontal offset, in pixels, relative to the upper-left corner of the // associated control window, to display the ToolTip. // // y: // The vertical offset, in pixels, relative to the upper-left corner of the // associated control window, to display the ToolTip. // // duration: // An System.Int32 containing the duration, in milliseconds, to display the // ToolTip. // // Exceptions: // System.ArgumentNullException: // The window parameter is null. // // System.ArgumentOutOfRangeException: // duration is less than or equal to 0. [Pure] public void Show(string text, IWin32Window window, int x, int y, int duration) { Contract.Requires(window != null); Contract.Requires(duration >= 0); } // // Summary: // Stops the timer that hides displayed ToolTips. //protected void StopTimer(); // // Summary: // Returns a string representation for this control. // // Returns: // A System.String containing a description of the System.Windows.Forms.ToolTip. //public override string ToString(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core; namespace Microsoft.Msagl.Layout.Incremental { /// <summary> /// Fast incremental layout settings /// </summary> #if PROPERTY_GRID_SUPPORT [DisplayName("Fast Incremental layout settings")] [Description("Settings for Fast Incremental Layout algorithm"), TypeConverter(typeof(ExpandableObjectConverter))] #endif public class FastIncrementalLayoutSettings : LayoutAlgorithmSettings { /// <summary> /// Stop after maxIterations completed /// </summary> int maxIterations = 100; /// <summary> /// Stop after maxIterations completed /// </summary> public int MaxIterations { get { return maxIterations; } set { maxIterations = value; } } int minorIterations = 3; /// <summary> /// Number of iterations in inner loop. /// </summary> public int MinorIterations { get { return minorIterations; } set { minorIterations = value; } } int iterations; /// <summary> /// Number of iterations completed /// </summary> public int Iterations { get { return iterations; } set { iterations = value; } } int projectionIterations = 5; /// <summary> /// number of times to project over all constraints at each layout iteration /// </summary> public int ProjectionIterations { get { return projectionIterations; } set { projectionIterations = value; } } bool approximateRepulsion = true; /// <summary> /// Rather than computing the exact repulsive force between all pairs of nodes (which would take O(n^2) time for n nodes) /// use a fast inexact technique (that takes O(n log n) time) /// </summary> public bool ApproximateRepulsion { get { return approximateRepulsion; } set { approximateRepulsion = value; } } /// <summary> /// RungaKutta integration potentially gives smoother increments, but is more expensive /// </summary> public bool RungeKuttaIntegration { get; set; } double initialStepSize = 1.4; /// <summary> /// StepSize taken at each iteration (a coefficient of the force on each node) adapts depending on change in /// potential energy at each step. With this scheme changing the InitialStepSize doesn't have much effect /// because if it is too large or too small it will be quickly updated by the algorithm anyway. /// </summary> public double InitialStepSize { get { return initialStepSize; } set { if (value <= 0 || value > 2) { throw new ArgumentException("ForceScalar should be greater than 0 and less than 2 (if we let you set it to 0 nothing would happen, greater than 2 would most likely be very unstable!)"); } initialStepSize = value; } } double decay = 0.9; /// <summary> /// FrictionalDecay isn't really friction so much as a scaling of velocity to improve convergence. 0.8 seems to work well. /// </summary> public double Decay { get { return decay; } set { if (value < 0.1 || value > 1) { throw new ArgumentException("Setting decay too small gives no progress. 1==no decay, 0.1==minimum allowed value"); } decay = value; } } double friction = 0.8; /// <summary> /// Friction isn't really friction so much as a scaling of velocity to improve convergence. 0.8 seems to work well. /// </summary> public double Friction { get { return friction; } set { if (value < 0 || value > 1) { throw new ArgumentException("Setting friction less than 0 or greater than 1 would just be strange. 1==no friction, 0==no conservation of velocity"); } friction = value; } } double repulsiveForceConstant = 1.0; /// <summary> /// strength of repulsive force between each pair of nodes. A setting of 1.0 should work OK. /// </summary> public double RepulsiveForceConstant { get { return repulsiveForceConstant; } set { repulsiveForceConstant = value; } } double attractiveForceConstant = 1.0; /// <summary> /// strength of attractive force between pairs of nodes joined by an edge. A setting of 1.0 should work OK. /// </summary> public double AttractiveForceConstant { get { return attractiveForceConstant; } set { attractiveForceConstant = value; } } double gravity = 1.0; /// <summary> /// gravity is a constant force applied to all nodes attracting them to the Origin /// and keeping disconnected components from flying apart. A setting of 1.0 should work OK. /// </summary> public double GravityConstant { get { return gravity; } set { gravity = value; } } bool interComponentForces = true; /// <summary> /// If the following is false forces will not be considered between each component and each component will have its own gravity origin. /// </summary> public bool InterComponentForces { get { return interComponentForces; } set { interComponentForces = value; } } bool applyForces = true; /// <summary> /// If the following is false forces will not be applied, but constraints will still be satisfied. /// </summary> public bool ApplyForces { get { return applyForces; } set { applyForces = value; } } internal FastIncrementalLayout algorithm; internal LinkedList<LockPosition> locks = new LinkedList<LockPosition>(); /// <summary> /// Add a LockPosition for each node whose position you want to keep fixed. LockPosition allows you to, /// for example, do interactive mouse dragging. /// We return the LinkedListNode which you can store together with your local Node object so that a RemoveLock operation can be performed in /// constant time. /// </summary> /// <param name="node"></param> /// <param name="bounds"></param> /// <returns>LinkedListNode which you should hang on to if you want to call RemoveLock later on.</returns> public LockPosition CreateLock(Node node, Rectangle bounds) { LockPosition lp = new LockPosition(node, bounds); lp.listNode = locks.AddLast(lp); return lp; } /// <summary> /// Add a LockPosition for each node whose position you want to keep fixed. LockPosition allows you to, /// for example, do interactive mouse dragging. /// We return the LinkedListNode which you can store together with your local Node object so that a RemoveLock operation can be performed in /// constant time. /// </summary> /// <param name="node"></param> /// <param name="bounds"></param> /// <param name="weight">stay weight of lock</param> /// <returns>LinkedListNode which you should hang on to if you want to call RemoveLock later on.</returns> public LockPosition CreateLock(Node node, Rectangle bounds, double weight) { LockPosition lp = new LockPosition(node, bounds, weight); lp.listNode = locks.AddLast(lp); return lp; } /// <summary> /// Remove all locks on node positions /// </summary> public void ClearLocks() { // foreach (var l in locks) { // l.listNode = null; // } locks.Clear(); } /// <summary> /// Remove a specific lock on node position. Once you remove it, you'll have to call AddLock again to create a new one if you want to lock it again. /// </summary> /// <param name="lockPosition">the LinkedListNode returned by the AddLock method above</param> [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.WriteLine(System.String)"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "FastIncrementalLayoutSettings"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "RemoveLock")] public void RemoveLock(LockPosition lockPosition) { ValidateArg.IsNotNull(lockPosition, "lockPosition"); if (lockPosition.listNode != null) { lockPosition.RestoreNodeWeight(); try { locks.Remove(lockPosition.listNode); } catch (InvalidOperationException e) { Console.WriteLine("Problem in FastIncrementalLayoutSettings.RemoveLock "+e.Message); } lockPosition.listNode = null; } } /// <summary> /// restart layout, use e.g. after a mouse drag or non-structural change to the graph /// </summary> public void ResetLayout() { Unconverge(); if (algorithm != null) { algorithm.ResetNodePositions(); algorithm.SetLockNodeWeights(); } } /// <summary> /// reset iterations and convergence status /// </summary> internal void Unconverge() { iterations = 0; //EdgeRoutesUpToDate = false; converged = false; } /// <summary> /// /// </summary> public void InitializeLayout(GeometryGraph graph, int initialConstraintLevel) { InitializeLayout(graph, initialConstraintLevel, anyCluster => this); } /// <summary> /// Initialize the layout algorithm /// </summary> /// <param name="graph">The graph upon which layout is performed</param> /// <param name="initialConstraintLevel"></param> /// <param name="clusterSettings"></param> public void InitializeLayout(GeometryGraph graph, int initialConstraintLevel, Func<Cluster, LayoutAlgorithmSettings> clusterSettings) { ValidateArg.IsNotNull(graph, "graph"); algorithm = new FastIncrementalLayout(graph, this, initialConstraintLevel, clusterSettings); ResetLayout(); } /// <summary> /// /// </summary> public void Uninitialize() { this.algorithm = null; } /// <summary> /// /// </summary> public bool IsInitialized { get { return this.algorithm != null; } } /// <summary> /// /// </summary> public void IncrementalRun(GeometryGraph graph) { IncrementalRun(graph, anyCluster => this); } private void SetupIncrementalRun(GeometryGraph graph, Func<Cluster, LayoutAlgorithmSettings> clusterSettings) { ValidateArg.IsNotNull(graph, "graph"); if (!IsInitialized) { InitializeLayout(graph, MaxConstraintLevel, clusterSettings); } else if (IsDone) { // If we were already done from last time but we are doing more work then something has changed. ResetLayout(); } } /// <summary> /// Run the FastIncrementalLayout instance incrementally /// </summary> public void IncrementalRun(GeometryGraph graph, Func<Cluster, LayoutAlgorithmSettings> clusterSettings) { SetupIncrementalRun(graph, clusterSettings); algorithm.Run(); graph.UpdateBoundingBox(); } /// <summary> /// /// </summary> public void IncrementalRun(CancelToken cancelToken, GeometryGraph graph, Func<Cluster, LayoutAlgorithmSettings> clusterSettings) { if (cancelToken != null) { cancelToken.ThrowIfCanceled(); } SetupIncrementalRun(graph, clusterSettings); algorithm.Run(cancelToken); graph.UpdateBoundingBox(); } /// <summary> /// Clones the object /// </summary> /// <returns></returns> public override LayoutAlgorithmSettings Clone() { return MemberwiseClone() as LayoutAlgorithmSettings; } /// <summary> /// /// </summary> public IEnumerable<IConstraint> StructuralConstraints { get { return structuralConstraints; } } /// <summary> /// /// </summary> public void AddStructuralConstraint(IConstraint cc) { structuralConstraints.Add(cc); } internal List<IConstraint> structuralConstraints = new List<IConstraint>(); /// <summary> /// Clear all constraints over the graph /// </summary> public void ClearConstraints() { locks.Clear(); structuralConstraints.Clear(); // clusterHierarchies.Clear(); } /// <summary> /// /// </summary> public void ClearStructuralConstraints() { structuralConstraints.Clear(); } /// <summary> /// Avoid overlaps between nodes boundaries, and if there are any /// clusters, then between each cluster boundary and nodes that are not /// part of that cluster. /// </summary> public bool AvoidOverlaps { get; set; } /// <summary> /// If edges have FloatingPorts then the layout will optimize edge lengths based on the port locations. /// If MultiLocationFloatingPorts are specified then the layout will choose the nearest pair of locations for each such edge. /// </summary> public bool RespectEdgePorts { get; set; } /// <summary> /// Apply nice but expensive routing of edges once layout converges /// </summary> public bool RouteEdges { get; set; } bool approximateRouting = true; /// <summary> /// If RouteEdges is true then the following is checked to see whether to do optimal shortest path routing /// or use a sparse visibility graph spanner to do approximate---but much faster---shortest path routing /// </summary> public bool ApproximateRouting { get { return approximateRouting; } set { approximateRouting = value; } } bool logScaleEdgeForces = true; /// <summary> /// If true then attractive forces across edges are computed as: /// AttractiveForceConstant * actualLength * Math.Log((actualLength + epsilon) / (idealLength + epsilon)) /// where epsilon is a small positive constant to avoid divide by zero or taking the log of zero. /// Note that LogScaleEdges can lead to ghost forces in highly constrained scenarios. /// If false then a the edge force is based on (actualLength - idealLength)^2, which works better with /// lots of constraints. /// </summary> public bool LogScaleEdgeForces { get { return logScaleEdgeForces; } set { logScaleEdgeForces = value; } } double displacementThreshold = 0.1; /// <summary> /// If the amount of total squared displacement after a particular iteration falls below DisplacementThreshold then Converged is set to true. /// Make DisplacementThreshold larger if you want layout to finish sooner - but not necessarily make as much progress towards a good layout. /// </summary> public double DisplacementThreshold { get { return displacementThreshold; } set { displacementThreshold = value; } } bool converged; /// <summary> /// Set to true if displacement from the last iteration was less than DisplacementThreshold. /// The caller should invoke FastIncrementalLayout.CalculateLayout() in a loop, e.g.: /// /// while(!settings.Converged) /// { /// layout.CalculateLayout(); /// redrawGraphOrHandleInteractionOrWhatever(); /// } /// /// RemainingIterations affects damping. /// </summary> public bool Converged { get { return converged; } set { this.converged = value; } } /// <summary> /// Return iterations as a percentage of MaxIterations. Useful for reporting progress, e.g. in a progress bar. /// </summary> public int PercentDone { get { if (Converged) { return 100; } else { return (int)((100.0 * (double)iterations) / (double)MaxIterations); } } } /// <summary> /// Not quite the same as Converged: /// </summary> public bool IsDone { get { return Converged || iterations >= MaxIterations; } } /// <summary> /// Returns an estimate of the cost function calculated in the most recent iteration. /// It's a float because FastIncrementalLayout.Energy is a volatile float so it /// can be safely read from other threads /// </summary> public float Energy { get { if (algorithm != null) { return algorithm.energy; } return 0; } } /// <summary> /// When layout is in progress the following is false. /// When layout has converged, routes are populated and this is set to true to tell the UI that the routes can be drawn. /// </summary> public bool EdgeRoutesUpToDate { get; set; } int maxConstraintLevel = 2; /// <summary> /// /// </summary> public int MaxConstraintLevel { get { return maxConstraintLevel; } set { if (maxConstraintLevel != value) { maxConstraintLevel = value; if (this.IsInitialized) { this.Uninitialize(); } } } } int minConstraintLevel = 0; /// <summary> /// /// </summary> public int MinConstraintLevel { get { return minConstraintLevel; } set { minConstraintLevel = value; } } /// <summary> /// Constraint level ranges from Min to MaxConstraintLevel. /// 0 = no constraints /// 1 = only structural constraints /// 2 = all constraints including non-overlap constraints /// /// A typical run of FastIncrementalLayout will apply it at each constraint level, starting at 0 to /// obtain an untangled unconstrained layout, then 1 to introduce structural constraints and finally 2 to beautify. /// Running only at level 2 will most likely leave the graph stuck in a tangled local minimum. /// </summary> public int CurrentConstraintLevel { get { return algorithm.CurrentConstraintLevel; } set { algorithm.CurrentConstraintLevel = value; } } double attractiveInterClusterForceConstant = 1.0; /// <summary> /// Attractive strength of edges connected to clusters /// </summary> public double AttractiveInterClusterForceConstant { get { return attractiveInterClusterForceConstant; } set { attractiveInterClusterForceConstant = value; } } /// <summary> /// /// </summary> public FastIncrementalLayoutSettings() { } /// <summary> /// Shallow copy the settings /// </summary> /// <param name="previousSettings"></param> public FastIncrementalLayoutSettings(FastIncrementalLayoutSettings previousSettings) { ValidateArg.IsNotNull(previousSettings, "previousSettings"); maxIterations = previousSettings.maxIterations; minorIterations = previousSettings.minorIterations; projectionIterations = previousSettings.projectionIterations; approximateRepulsion = previousSettings.approximateRepulsion; initialStepSize = previousSettings.initialStepSize; RungeKuttaIntegration = previousSettings.RungeKuttaIntegration; decay = previousSettings.decay; friction = previousSettings.friction; repulsiveForceConstant = previousSettings.repulsiveForceConstant; attractiveForceConstant = previousSettings.attractiveForceConstant; gravity = previousSettings.gravity; interComponentForces = previousSettings.interComponentForces; applyForces = previousSettings.applyForces; IdealEdgeLength = previousSettings.IdealEdgeLength; AvoidOverlaps = previousSettings.AvoidOverlaps; RespectEdgePorts = previousSettings.RespectEdgePorts; RouteEdges = previousSettings.RouteEdges; approximateRouting = previousSettings.approximateRouting; logScaleEdgeForces = previousSettings.logScaleEdgeForces; displacementThreshold = previousSettings.displacementThreshold; minConstraintLevel = previousSettings.minConstraintLevel; maxConstraintLevel = previousSettings.maxConstraintLevel; attractiveInterClusterForceConstant = previousSettings.attractiveInterClusterForceConstant; clusterGravity = previousSettings.clusterGravity; PackingAspectRatio = previousSettings.PackingAspectRatio; NodeSeparation = previousSettings.NodeSeparation; ClusterMargin = previousSettings.ClusterMargin; } double clusterGravity = 1.0; /// <summary> /// Controls how tightly members of clusters are pulled together /// </summary> public double ClusterGravity { get { return clusterGravity; } set { clusterGravity = value; } } /// <summary> /// Settings for calculation of ideal edge length /// </summary> public IdealEdgeLengthSettings IdealEdgeLength { get; set; } bool updateClusterBoundaries = true; /// <summary> /// Force groups to follow their constituent nodes, /// true by default. /// </summary> public bool UpdateClusterBoundariesFromChildren { get { return updateClusterBoundaries; } set { updateClusterBoundaries = value; } } /// <summary> /// creates the settings that seems working /// </summary> /// <returns></returns> public static FastIncrementalLayoutSettings CreateFastIncrementalLayoutSettings() { return new FastIncrementalLayoutSettings { ApplyForces = false, ApproximateRepulsion = true, ApproximateRouting = true, AttractiveForceConstant = 1.0, AttractiveInterClusterForceConstant = 1.0, AvoidOverlaps = true, ClusterGravity = 1.0, Decay = 0.9, DisplacementThreshold = 0.00000005, Friction = 0.8, GravityConstant = 1.0, InitialStepSize = 2.0, InterComponentForces = false, Iterations = 0, LogScaleEdgeForces = false, MaxConstraintLevel = 2, MaxIterations = 20, MinConstraintLevel = 0, MinorIterations = 1, ProjectionIterations = 5, RepulsiveForceConstant = 2.0, RespectEdgePorts = false, RouteEdges = false, RungeKuttaIntegration = true, UpdateClusterBoundariesFromChildren = true, NodeSeparation = 20 }; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="NHibernateConfigurator.cs" company="Itransition"> // Itransition (c) Copyright. All right reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text.RegularExpressions; using Castle.Core.Configuration; using Castle.Facilities.NHibernateIntegration; using Castle.MicroKernel; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using Framework.Core; using Framework.Core.Configuration; using Framework.Core.Helpers; using Framework.Facilities.NHibernate.Filters; using Configuration = NHibernate.Cfg.Configuration; namespace Framework.Facilities.NHibernate.Castle { /// <summary> /// Builds nhibernate configuration. /// </summary> public class NHibernateConfigurator : IConfigurationBuilder { #region Fields private readonly IApplication application; private readonly IKernel kernel; private readonly Regex nhibernatePropertyPattern = new Regex("^hibernate\\.", RegexOptions.IgnoreCase); private BinaryFormatter binaryFormatter; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="NHibernateConfigurator"/> class. /// </summary> /// <param name="application">The application.</param> /// <param name="kernel">The kernel.</param> public NHibernateConfigurator(IApplication application, IKernel kernel) { this.application = application; this.kernel = kernel; this.binaryFormatter = new BinaryFormatter(); } #endregion #region IConfigurationBuilder members /// <summary> /// Gets the configuration. /// </summary> /// <param name="config">The config.</param> /// <returns>nhibernate configuration.</returns> public Configuration GetConfiguration(IConfiguration config) { var environment = EnumHelper.GetKey(application.Environment); var alias = config.Attributes["alias"]; if (!String.IsNullOrEmpty(alias)) { var environmentSpecific = String.Format("{0}-{1}", environment, alias); if (application.DatabaseConfiguration.ContainsKey(environmentSpecific)) { return BuildConfig(application.DatabaseConfiguration[environmentSpecific], config); } if (application.DatabaseConfiguration.ContainsKey(alias)) { return BuildConfig(application.DatabaseConfiguration[alias], config); } } else { if (application.DatabaseConfiguration.ContainsKey(environment)) { return BuildConfig(application.DatabaseConfiguration[environment], config); } } throw new ConfigurationErrorsException(String.Format("Could not build configuration for database (environment = \"{0}\", alias = \"{1}\").", environment, alias)); } #endregion #region Helper methods /// <summary> /// Determines whether [is new configuration required] [the specified file name]. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns> /// <c>true</c> if [is new configuration required] [the specified file name]; otherwise, <c>false</c>. /// </returns> protected virtual bool IsNewConfigurationRequired(string fileName) { return !File.Exists(fileName); } /// <summary> /// Writes the <see cref="Configuration"/> to stream. /// </summary> /// <param name="stream">The stream to be written.</param> /// <param name="cfg">The configuration.</param> protected virtual void WriteConfigurationToStream(Stream stream, Configuration cfg) { binaryFormatter.Serialize(stream, cfg); } /// <summary> /// Gets the <see cref="Configuration"/> from stream. /// </summary> /// <param name="fs">The stream from which the configuration will be deserialized.</param> /// <returns>The <see cref="Configuration"/>.</returns> protected virtual Configuration GetConfigurationFromStream(Stream fs) { return binaryFormatter.Deserialize(fs) as Configuration; } private static IPersistenceConfigurer GetDatabase(DatabaseConfiguration databaseConfiguration) { switch (databaseConfiguration.Platform) { case DatabasePlatform.SqlServer: return MsSqlConfiguration.MsSql2008.ConnectionString(databaseConfiguration.GetConnectionString()); case DatabasePlatform.SqlServer2000: return MsSqlConfiguration.MsSql2000.ConnectionString(databaseConfiguration.GetConnectionString()); case DatabasePlatform.SqlServer2005: return MsSqlConfiguration.MsSql2005.ConnectionString(databaseConfiguration.GetConnectionString()); case DatabasePlatform.SQLite: return SQLiteConfiguration.Standard.ConnectionString(databaseConfiguration.GetConnectionString()); case DatabasePlatform.MySQL: return MySQLConfiguration.Standard.ConnectionString(databaseConfiguration.GetConnectionString()); case DatabasePlatform.PostgreSQL: return PostgreSQLConfiguration.Standard.ConnectionString(databaseConfiguration.GetConnectionString()); case DatabasePlatform.Oracle9: return OracleClientConfiguration.Oracle9.ConnectionString(databaseConfiguration.GetConnectionString()); case DatabasePlatform.Oracle10: return OracleClientConfiguration.Oracle9.ConnectionString(databaseConfiguration.GetConnectionString()); default: throw new ConfigurationErrorsException(String.Format("{0} platform is not supported by nhibernate facility.", databaseConfiguration.Platform)); } } private Configuration BuildConfig(DatabaseConfiguration databaseConfiguration, IConfiguration config) { string fileName = config.Attributes["fileName"]; Configuration cfg; if (IsNewConfigurationRequired(fileName)) { using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate)) { var fluenty = Fluently.Configure() .Database(GetDatabase(databaseConfiguration)) .Mappings(m => { foreach (var mapper in kernel.ResolveAll<INHibernateMapper>()) { mapper.Map(m, databaseConfiguration); } m.FluentMappings.Add(typeof(CultureFilter)); }); cfg = fluenty.ExposeConfiguration(ProcessConfiguration).BuildConfiguration().AddProperties(GetNHibernateProperties(databaseConfiguration)); WriteConfigurationToStream(fileStream, cfg); } } else { using (var fileStream = new FileStream(fileName, FileMode.OpenOrCreate)) { cfg = GetConfigurationFromStream(fileStream); } } return cfg; } private void ProcessConfiguration(Configuration configuration) { foreach (var configurationChain in kernel.ResolveAll<INHibernateConfigurationChain>()) { configurationChain.Process(configuration); } } private Dictionary<String, String> GetNHibernateProperties(DatabaseConfiguration databaseConfiguration) { var nhibernateProperties = new Dictionary<String, String>(); foreach (var property in databaseConfiguration.Properties) { if (nhibernatePropertyPattern.IsMatch(property.Key)) { var key = nhibernatePropertyPattern.Replace(property.Key, String.Empty); nhibernateProperties[key] = property.Value; } } return nhibernateProperties; } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public abstract class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest { internal abstract IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(TestWorkspace workspace, string fixAllActionEquivalenceKey); internal abstract IEnumerable<Diagnostic> GetDiagnostics(TestWorkspace workspace); protected override IList<CodeAction> GetCodeActionsWorker(TestWorkspace workspace, string fixAllActionEquivalenceKey) { var diagnostics = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey); return diagnostics?.Item2?.Fixes.Select(f => f.Action).ToList(); } internal Tuple<Diagnostic, CodeFixCollection> GetDiagnosticAndFix(TestWorkspace workspace, string fixAllActionEquivalenceKey = null) { return GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceKey).FirstOrDefault(); } protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any()); span = hostDocument.SelectedSpans.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span) { var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any()); if (hostDocument == null) { document = null; span = default(TextSpan); return false; } span = hostDocument.SelectedSpans.Single(); document = workspace.CurrentSolution.GetDocument(hostDocument.Id); return true; } protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span) { var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any()); var annotatedSpan = hostDocument.AnnotatedSpans.Single(); annotation = annotatedSpan.Key; span = annotatedSpan.Value.Single(); return workspace.CurrentSolution.GetDocument(hostDocument.Id); } protected FixAllScope GetFixAllScope(string annotation) { switch (annotation) { case "FixAllInDocument": return FixAllScope.Document; case "FixAllInProject": return FixAllScope.Project; case "FixAllInSolution": return FixAllScope.Solution; } throw new InvalidProgramException("Incorrect FixAll annotation in test"); } internal IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes( IEnumerable<Diagnostic> diagnostics, DiagnosticAnalyzer provider, CodeFixProvider fixer, TestDiagnosticAnalyzerDriver testDriver, Document document, TextSpan span, string annotation, string fixAllActionId) { foreach (var diagnostic in diagnostics) { if (annotation == null) { var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, diagnostic, (a, d) => fixes.Add(new CodeFix(document.Project, a, d)), CancellationToken.None); fixer.RegisterCodeFixesAsync(context).Wait(); if (fixes.Any()) { var codeFix = new CodeFixCollection(fixer, diagnostic.Location.SourceSpan, fixes); yield return Tuple.Create(diagnostic, codeFix); } } else { var fixAllProvider = fixer.GetFixAllProvider(); Assert.NotNull(fixAllProvider); FixAllScope scope = GetFixAllScope(annotation); Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync = (d, diagIds, c) => { var root = d.GetSyntaxRootAsync().Result; var diags = testDriver.GetDocumentDiagnostics(provider, d, root.FullSpan); diags = diags.Where(diag => diagIds.Contains(diag.Id)); return Task.FromResult(diags); }; Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync = (p, includeAllDocumentDiagnostics, diagIds, c) => { var diags = includeAllDocumentDiagnostics ? testDriver.GetAllDiagnostics(provider, p) : testDriver.GetProjectDiagnostics(provider, p); diags = diags.Where(diag => diagIds.Contains(diag.Id)); return Task.FromResult(diags); }; var diagnosticIds = ImmutableHashSet.Create(diagnostic.Id); var fixAllDiagnosticProvider = new FixAllCodeActionContext.FixAllDiagnosticProvider(diagnosticIds, getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync); var fixAllContext = diagnostic.Location.IsInSource ? new FixAllContext(document, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None) : new FixAllContext(document.Project, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None); var fixAllFix = fixAllProvider.GetFixAsync(fixAllContext).WaitAndGetResult(CancellationToken.None); if (fixAllFix != null) { var diagnosticSpan = diagnostic.Location.IsInSource ? diagnostic.Location.SourceSpan : default(TextSpan); var codeFix = new CodeFixCollection(fixAllProvider, diagnosticSpan, ImmutableArray.Create(new CodeFix(document.Project, fixAllFix, diagnostic))); yield return Tuple.Create(diagnostic, codeFix); } } } } protected void TestEquivalenceKey(string initialMarkup, string equivalenceKey) { using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions: null, compilationOptions: null)) { var diagnosticAndFix = GetDiagnosticAndFix(workspace); Assert.Equal(equivalenceKey, diagnosticAndFix.Item2.Fixes.ElementAt(index: 0).Action.EquivalenceKey); } } protected void TestActionCountInAllFixes( string initialMarkup, int count, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null) { using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { var diagnosticAndFix = GetDiagnosticAndFixes(workspace, null); var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum(); Assert.Equal(count, diagnosticCount); } } protected void TestSpans( string initialMarkup, string expectedMarkup, int index = 0, ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, string diagnosticId = null, string fixAllActionEquivalenceId = null) { IList<TextSpan> spansList; string unused; MarkupTestFile.GetSpans(expectedMarkup, out unused, out spansList); var expectedTextSpans = spansList.ToSet(); using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions)) { ISet<TextSpan> actualTextSpans; if (diagnosticId == null) { var diagnosticsAndFixes = GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceId); var diagnostics = diagnosticsAndFixes.Select(t => t.Item1); actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet(); } else { var diagnostics = GetDiagnostics(workspace); actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet(); } Assert.True(expectedTextSpans.SetEquals(actualTextSpans)); } } protected async Task TestAddDocument( string initialMarkup, string expectedMarkup, IList<string> expectedContainers, string expectedDocumentName, int index = 0, bool compareTokens = true, bool isLine = true) { await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, null, null, compareTokens, isLine).ConfigureAwait(true); await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens, isLine).ConfigureAwait(true); } private async Task TestAddDocument( string initialMarkup, string expectedMarkup, int index, IList<string> expectedContainers, string expectedDocumentName, ParseOptions parseOptions, CompilationOptions compilationOptions, bool compareTokens, bool isLine) { using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup)) { var codeActions = GetCodeActions(workspace, fixAllActionEquivalenceKey: null); await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName, codeActions, compareTokens).ConfigureAwait(true); } } private async Task TestAddDocument( TestWorkspace workspace, string expectedMarkup, int index, IList<string> expectedFolders, string expectedDocumentName, IList<CodeAction> actions, bool compareTokens) { var operations = VerifyInputsAndGetOperations(index, actions); await TestAddDocument( workspace, expectedMarkup, operations, hasProjectChange: false, modifiedProjectId: null, expectedFolders: expectedFolders, expectedDocumentName: expectedDocumentName, compareTokens: compareTokens).ConfigureAwait(true); } private async Task<Tuple<Solution, Solution>> TestAddDocument( TestWorkspace workspace, string expected, IEnumerable<CodeActionOperation> operations, bool hasProjectChange, ProjectId modifiedProjectId, IList<string> expectedFolders, string expectedDocumentName, bool compareTokens) { var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; Document addedDocument = null; if (!hasProjectChange) { addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution); } else { Assert.NotNull(modifiedProjectId); addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName); } Assert.NotNull(addedDocument); AssertEx.Equal(expectedFolders, addedDocument.Folders); Assert.Equal(expectedDocumentName, addedDocument.Name); if (compareTokens) { TokenUtilities.AssertTokensEqual( expected, addedDocument.GetTextAsync().Result.ToString(), GetLanguage()); } else { Assert.Equal(expected, addedDocument.GetTextAsync().Result.ToString()); } var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); if (!hasProjectChange) { // If there is just one document change then we expect the preview to be a WpfTextView var content = await editHandler.GetPreviews(workspace, operations, CancellationToken.None).TakeNextPreviewAsync().ConfigureAwait(true); var diffView = content as IWpfDifferenceViewer; Assert.NotNull(diffView); diffView.Close(); } else { // If there are more changes than just the document we need to browse all the changes and get the document change var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None); bool hasPreview = false; object preview; while ((preview = await contents.TakeNextPreviewAsync().ConfigureAwait(true)) != null) { var diffView = preview as IWpfDifferenceViewer; if (diffView != null) { hasPreview = true; diffView.Close(); break; } } Assert.True(hasPreview); } return Tuple.Create(oldSolution, newSolution); } internal async Task TestWithMockedGenerateTypeDialog( string initial, string languageName, string typeName, string expected = null, bool isLine = true, bool isMissing = false, Accessibility accessibility = Accessibility.NotApplicable, TypeKind typeKind = TypeKind.Class, string projectName = null, bool isNewFile = false, string existingFilename = null, IList<string> newFileFolderContainers = null, string fullFilePath = null, string newFileName = null, string assertClassName = null, bool checkIfUsingsIncluded = false, bool checkIfUsingsNotIncluded = false, string expectedTextWithUsings = null, string defaultNamespace = "", bool areFoldersValidIdentifiers = true, GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null, IList<TypeKindOptions> assertTypeKindPresent = null, IList<TypeKindOptions> assertTypeKindAbsent = null, bool isCancelled = false) { using (var testState = new GenerateTypeTestState(initial, isLine, projectName, typeName, existingFilename, languageName)) { // Initialize the viewModel values testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions( accessibility: accessibility, typeKind: typeKind, typeName: testState.TypeName, project: testState.ProjectToBeModified, isNewFile: isNewFile, newFileName: newFileName, folders: newFileFolderContainers, fullFilePath: fullFilePath, existingDocument: testState.ExistingDocument, areFoldersValidIdentifiers: areFoldersValidIdentifiers, isCancelled: isCancelled); testState.TestProjectManagementService.SetDefaultNamespace( defaultNamespace: defaultNamespace); var diagnosticsAndFixes = GetDiagnosticAndFixes(testState.Workspace, null); var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id)); if (isMissing) { Assert.Null(generateTypeDiagFixes); return; } var fixes = generateTypeDiagFixes.Item2.Fixes; Assert.NotNull(fixes); var fixActions = MassageActions(fixes.Select(f => f.Action).ToList()); Assert.NotNull(fixActions); // Since the dialog option is always fed as the last CodeAction var index = fixActions.Count() - 1; var action = fixActions.ElementAt(index); Assert.Equal(action.Title, FeaturesResources.GenerateNewType); var operations = action.GetOperationsAsync(CancellationToken.None).Result; Tuple<Solution, Solution> oldSolutionAndNewSolution = null; if (!isNewFile) { oldSolutionAndNewSolution = TestOperations( testState.Workspace, expected, operations, conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false, expectedChangedDocumentId: testState.ExistingDocument.Id); } else { oldSolutionAndNewSolution = await TestAddDocument( testState.Workspace, expected, operations, projectName != null, testState.ProjectToBeModified.Id, newFileFolderContainers, newFileName, compareTokens: false).ConfigureAwait(true); } if (checkIfUsingsIncluded) { Assert.NotNull(expectedTextWithUsings); TestOperations(testState.Workspace, expectedTextWithUsings, operations, conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false, expectedChangedDocumentId: testState.InvocationDocument.Id); } if (checkIfUsingsNotIncluded) { var oldSolution = oldSolutionAndNewSolution.Item1; var newSolution = oldSolutionAndNewSolution.Item2; var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution); Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id)); } // Added into a different project than the triggering project if (projectName != null) { var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations); var newSolution = appliedChanges.Item2; var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id); // Make sure the Project reference is present Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id)); } // Assert Option Calculation if (assertClassName != null) { Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName); } if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null) { var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions; if (assertGenerateTypeDialogOptions != null) { Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility); Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions); Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute); } if (assertTypeKindPresent != null) { foreach (var typeKindPresentEach in assertTypeKindPresent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0); } } if (assertTypeKindAbsent != null) { foreach (var typeKindPresentEach in assertTypeKindAbsent) { Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0); } } } } } } }
/* Copyright (C) 2015 Kevin Boronka * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Security.Cryptography; namespace sar.Tools { public static class IO { public static bool IncludeSubFolders = true; public static string ProgramFilesx86 { get { if (IntPtr.Size == 8 || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))) { return Environment.GetEnvironmentVariable("ProgramFiles(x86)") + @"\"; } return Environment.GetEnvironmentVariable("ProgramFiles") + @"\"; } } public static string ProgramFiles { get { return Environment.GetEnvironmentVariable("ProgramW6432") + @"\"; } } public static string Windows { get { return Environment.GetEnvironmentVariable("SystemRoot") + @"\"; } } public static string System32 { get { return Environment.SystemDirectory + @"\"; } } public static string Temp { get { return System.IO.Path.GetTempPath(); } } public static bool IsSVN(string path) { path = path.ToLower(); if (path.Contains(@"\.svn\")) return true; if (path.Contains(@"\.cvs\")) return true; return false; } public static bool IsFileReadOnly(string path) { if (!File.Exists(path)) throw new FileNotFoundException("file " + path + " not found"); var info = new System.IO.FileInfo(path); return (System.IO.FileAttributes.ReadOnly == info.Attributes); } public static List<string> GetAllDirectories(string root) { var directories = new List<string>(); directories.Add(root); try { if (IO.IncludeSubFolders) { foreach (string dir in System.IO.Directory.GetDirectories(root)) { try { directories.AddRange(GetAllDirectories(dir)); } catch (Exception ex) { ConsoleHelper.WriteException(ex); } } } } catch (Exception ex) { ConsoleHelper.WriteException(ex); } return directories; } public static List<string> GetAllFiles(string root) { if (String.IsNullOrEmpty(root)) { throw new NullReferenceException("root search path was not specified"); } string pattern = "*.*"; // handle filepaths in root if (!Directory.Exists(root) && root.Contains("*")) { ConsoleHelper.DebugWriteLine("root: " + root); pattern = root.Substring(root.LastIndexOf('\\') + 1); root = root.Substring(0, root.LastIndexOf('\\')); ConsoleHelper.DebugWriteLine("root: " + root); ConsoleHelper.DebugWriteLine("pattern: " + pattern); } return GetAllFiles(root, pattern); } public static string GetRoot(string filepath) { string root = filepath.Substring(0, filepath.LastIndexOf('\\')); if (root.Substring(root.Length - 1) != "\\") root += "\\"; return root; } public static string GetFilename(string filepath) { return filepath.Substring(filepath.LastIndexOf('\\') + 1); } public static string GetFileDirectory(string filepath) { return filepath.Substring(0, filepath.LastIndexOf('\\')); } public static string GetFileExtension(string filepath) { string filename = GetFilename(filepath); return (filename.LastIndexOf(".", StringComparison.CurrentCulture) != -1) ? filename.Substring(filename.LastIndexOf(".", StringComparison.CurrentCulture) + 1) : ""; } public static string CheckRoot(string root) { if (!root.StartsWith(@"\\", StringComparison.CurrentCulture)) { if (root.StartsWith(@"..\", StringComparison.CurrentCulture)) root = Directory.GetCurrentDirectory() + @"\" + root; if (root.StartsWith(@".\", StringComparison.CurrentCulture)) root = Directory.GetCurrentDirectory() + @"\" + root; if (root.StartsWith(@"\", StringComparison.CurrentCulture)) root = Directory.GetCurrentDirectory() + root; } if (!root.EndsWith(@"\", StringComparison.CurrentCulture)) root += @"\"; root = root.Replace(@"\.\", @"\"); return root; } public static void CheckRootAndPattern(ref string root) { string pattern = "*.*"; CheckRootAndPattern(ref root, ref pattern); } public static string CheckPath(string root, string path) { if (path.LastIndexOf("\"") != -1) path = path.Substring(0, path.Length - 1); if (root.LastIndexOf("\"") != -1) root = root.Substring(0, root.Length - 1); if (path.LastIndexOf(@"\") == -1) path = @".\" + path; if (path.Substring(path.Length - 1, 1) != @"\") path += @"\"; CheckRootAndPattern(ref root, ref path); return root + path; } public static void CheckRootAndPattern(ref string root, ref string pattern) { if (String.IsNullOrEmpty(root)) { throw new NullReferenceException("root search path was not specified"); } if (!Directory.Exists(root)) { throw new FileNotFoundException("root search path does not exist [" + root + "]"); } var files = new List<string>(); if (pattern.LastIndexOf(':') != -1) { // mapped drive absolute paths root = pattern.Substring(0, pattern.LastIndexOf(@"\") + 1); pattern = pattern.Substring(pattern.LastIndexOf(@"\") + 1, pattern.Length - pattern.LastIndexOf(@"\") - 1); } else if (pattern.Substring(0, 2) == @"\\") { // UNC absolute paths root = pattern.Substring(0, pattern.LastIndexOf(@"\")); pattern = pattern.Substring(pattern.LastIndexOf(@"\") + 1, pattern.Length - pattern.LastIndexOf(@"\") - 1); } else if (pattern.LastIndexOf(@"\") != -1) { // relative paths if (pattern.Substring(0, 1) != @"\") pattern = @"\" + pattern; if (root.Substring(root.Length - 1) == @"\") root = root.Substring(0, root.Length - 1); root += pattern.Substring(0, pattern.LastIndexOf(@"\")); pattern = pattern.Substring(pattern.LastIndexOf(@"\") + 1, pattern.Length - pattern.LastIndexOf(@"\") - 1); } if (root.Substring(root.Length - 1) != "\\") root += "\\"; } public static List<string> GetAllFiles(string root, string pattern) { CheckRootAndPattern(ref root, ref pattern); var files = new List<string>(); foreach (string dir in GetAllDirectories(root)) { try { files.AddRange(Directory.GetFiles(dir, pattern)); } catch (Exception ex) { ConsoleHelper.WriteException(ex); } } return files; } private static int GetLineNumber(string content, int index) { int lines = 1; for (int i = 0; i <= index - 1; i++) if (content[i] == '\n') lines++; return lines; } #region searching within files public struct SearchResult { public string FilePath; public List<Match> Matches; } public static List<SearchResult> SearchAndReplaceInFiles(string root, string filePattern, string search, string replace) { var results = new List<SearchResult>(); IO.CheckRootAndPattern(ref root, ref filePattern); foreach (string file in IO.GetAllFiles(root, filePattern)) { if (!IO.IsSVN(file)) { SearchResult result = IO.SearchAndReplaceInFile(file, search, replace); if (result.Matches.Count > 0) { results.Add(result); } } } return results; } public static SearchResult SearchAndReplaceInFile(string path, string search, string replace) { var result = new SearchResult(); result.FilePath = path; result.Matches = new List<Match>(); string content = ReadFileAsUtf8(path); string newcontent; string lastResult = content; do { newcontent = lastResult; Match match = Regex.Match(newcontent, search); if (match.Success) { if (ConsoleHelper.ShowDebug) ConsoleHelper.DebugWriteLine("found in " + GetFilename(path) + " @ ln#" + GetLineNumber(newcontent, match.Index).ToString()); result.Matches.Add(match); lastResult = Regex.Replace(lastResult, search, replace); } } while (lastResult != newcontent); if (newcontent != content) { using(var writer = new StreamWriter(path, false, Encoding.UTF8)) { writer.Write(newcontent); } } return result; } public static List<SearchResult> SearchInFiles(string root, string filePattern, string search) { var results = new List<SearchResult>(); IO.CheckRootAndPattern(ref root, ref filePattern); foreach (string file in IO.GetAllFiles(root, filePattern)) { if (!IO.IsSVN(file)) { SearchResult result = IO.SearchInFile(file, search); if (result.Matches.Count > 0) { results.Add(result); } } } return results; } public static SearchResult SearchInFile(string path, string search) { var result = new SearchResult(); result.FilePath = path; result.Matches = new List<Match>(); string content = ReadFileAsUtf8(path); MatchCollection matches = Regex.Matches(content, search); foreach (Match match in matches) { result.Matches.Add(match); } return result; } #endregion public static Encoding ReadEncoding(string filepath) { if (String.IsNullOrEmpty(filepath)) { throw new NullReferenceException("filepath was not specified"); } if (!File.Exists(filepath)) { throw new FileNotFoundException("filepath does not exist"); } Encoding encoding; using (var reader = new StreamReader(filepath, true)) { encoding = reader.CurrentEncoding; } ConsoleHelper.DebugWriteLine("current EncodingName: " + encoding.EncodingName.ToString()); ConsoleHelper.DebugWriteLine("current BodyName: " + encoding.BodyName.ToString()); ConsoleHelper.DebugWriteLine("current HeaderName: " + encoding.HeaderName.ToString()); return encoding; } private static FileStream WaitForFile (string path, FileMode mode, FileAccess access, FileShare share) { // check if file is locked by another application for (int attempts = 0; attempts < 10; attempts++) { try { var fs = new FileStream(path, mode, access, share); fs.ReadByte(); fs.Seek(0, SeekOrigin.Begin); return fs; } catch (IOException) { Thread.Sleep(50); } } return null; } public static byte[] ReadAllBytes(string path) { byte[] buffer; using (var fs = WaitForFile(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); } return buffer; } public static String ReadFileAsUtf8(string fileName) { Encoding encoding = Encoding.Default; String original = String.Empty; using (var sr = new StreamReader(fileName, Encoding.Default)) { original = sr.ReadToEnd(); encoding = sr.CurrentEncoding; sr.Close(); } //if (encoding == Encoding.UTF8) // return original; byte[] encBytes = encoding.GetBytes(original); byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes); return Encoding.UTF8.GetString(utf8Bytes); } public static string ReadFile(string filepath) { return ReadFileAsUtf8(filepath); } public static string[] ReadFileLines(string filepath) { return Regex.Split(ReadFile(filepath), "\r\n|\r|\n"); } public static void WriteFileLines(string filepath, string[] lines) { var linesList = new List<string>(); foreach (string line in lines) { linesList.Add(line); } WriteFileLines(filepath, linesList); } public static void WriteFileLines(string filepath, List<string> lines) { string newFile = ""; string linebreak = ""; foreach (string line in lines) { newFile += linebreak + line; linebreak = System.Environment.NewLine; } WriteFile(filepath, newFile); } public static void WriteFile(string filepath, string text) { Encoding encoding = Encoding.UTF8; if (!File.Exists(filepath) || text != ReadFile(filepath)) { using (var writter = new StreamWriter(filepath, false, encoding)) { writter.Write(text); } } } public static void Encode(string filepath, Encoding encoding) { if (String.IsNullOrEmpty(filepath)) { throw new NullReferenceException("filepath was not specified"); } if (!File.Exists(filepath)) { throw new FileNotFoundException("filepath does not exist"); } Encoding currentEncoding = ReadEncoding(filepath); string content = ""; // read file using (var reader = new StreamReader(filepath, true)) { content = reader.ReadToEnd(); } File.Delete(filepath); // write to file using (var writer = new StreamWriter(filepath, false, encoding)) { ConsoleHelper.DebugWriteLine("after: " + writer.Encoding.ToString()); writer.Write(content); } } public static string FindApplication(string exeName) { return FindApplication(exeName, "."); } public static string FindApplication(string exeName, string folder) { // check application name if (String.IsNullOrEmpty(exeName)) { throw new NullReferenceException("application filename was not specified"); } if (exeName.Length <= 4) { throw new InvalidDataException("application filename too short"); } string extension = exeName.Substring(exeName.Length - 4, 4); if (extension != ".exe" && extension != ".com" && extension != ".bat") { throw new InvalidDataException("application filename must end in .exe, .com, or .bat"); } // search in program files folders var files = new List<string>(); if (Directory.Exists(IO.ProgramFilesx86 + folder + @"\")) files = IO.GetAllFiles(IO.ProgramFilesx86 + folder + @"\", exeName); if (files.Count == 0) { if (Directory.Exists(IO.ProgramFiles + folder + @"\")) files = IO.GetAllFiles(IO.ProgramFiles + folder + @"\", exeName); } // unable to locate application if (files.Count == 0) { throw new FileNotFoundException("unable to locate " + exeName); } return files[0]; } public static string FindFile(string root, string filepattern) { // check application name if (String.IsNullOrEmpty(filepattern)) { throw new NullReferenceException("filename was not specified"); } // check root if (String.IsNullOrEmpty(root)) { throw new NullReferenceException("root was not specified"); } IO.CheckRootAndPattern(ref root, ref filepattern); List<string> files = IO.GetAllFiles(root, filepattern); // unable to locate application if (files.Count == 0) { throw new FileNotFoundException("unable to locate " + filepattern); } return files[0]; } public static string FindFile(string filepattern) { string root = Directory.GetCurrentDirectory(); return FindFile(root, filepattern); } public static List<string> GetDotNetVersions() { // get list of msbuild versions availble string msbuildFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.System) + @"\..\Microsoft.NET\Framework"; var allVersions = new List<string>(); foreach (string path in Directory.GetDirectories(msbuildFolder)) { string version = path.Remove(0,path.LastIndexOf('\\')+1).Substring(1,3); string msBuildPath = path + @"\MSBuild.exe"; string vbcBuildPath = path + @"\vbc.exe"; string cbcBuildPath = path + @"\cbc.exe"; if (File.Exists(msBuildPath) || File.Exists(vbcBuildPath) || File.Exists(cbcBuildPath)) { allVersions.Add(version); } } return allVersions; } public static string FindDotNetFolder(string netVersion) { // get list of msbuild versions availble string msbuildFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.System) + @"\..\Microsoft.NET\Framework"; var msBuildFolders = new Dictionary<string, string>(); foreach (string path in Directory.GetDirectories(msbuildFolder)) { string version = path.Remove(0,path.LastIndexOf('\\')+1).Substring(1,3); string msBuildPath = path + @"\MSBuild.exe"; string vbcBuildPath = path + @"\vbc.exe"; string cbcBuildPath = path + @"\cbc.exe"; if (File.Exists(msBuildPath) || File.Exists(vbcBuildPath) || File.Exists(cbcBuildPath)) { msBuildFolders.Add(version, path); ConsoleHelper.DebugWriteLine(version + " = " + path); } } // sanity - .net version installed if (!msBuildFolders.ContainsKey(netVersion)) throw new ArgumentOutOfRangeException(".net version"); return msBuildFolders[netVersion]; } public static FileInfo GetOldestFile(string directory) { if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException(directory); } var parent = new DirectoryInfo(directory); var files = parent.GetFiles(); if (files.Length == 0) { return null; } FileInfo oldestFile = files[0]; foreach (var file in files) { if (file.CreationTime < oldestFile.CreationTime) { oldestFile = file; } } return oldestFile; } public static FileInfo GetNewestFile(string directory) { if (!Directory.Exists(directory)) { throw new DirectoryNotFoundException(directory); } var parent = new DirectoryInfo(directory); var files = parent.GetFiles(); if (files.Length == 0) { return null; } FileInfo oldestFile = files[0]; foreach (var file in files) { if (file.CreationTime > oldestFile.CreationTime) { oldestFile = file; } } return oldestFile; } public static void CopyFile(string sourcePath, string destinationPath) { if (File.Exists(destinationPath)) { var toFile = new FileInfo(destinationPath); if (toFile.IsReadOnly) toFile.IsReadOnly = false; } var sourceFile = new FileInfo(sourcePath); sourceFile.CopyTo(destinationPath, true); var destinationFile = new FileInfo(destinationPath); if (destinationFile.IsReadOnly) { destinationFile.IsReadOnly = false; destinationFile.CreationTime = sourceFile.CreationTime; destinationFile.LastWriteTime = sourceFile.LastWriteTime; destinationFile.LastAccessTime = sourceFile.LastAccessTime; destinationFile.IsReadOnly = true; } else { destinationFile.CreationTime = sourceFile.CreationTime; destinationFile.LastWriteTime = sourceFile.LastWriteTime; destinationFile.LastAccessTime = sourceFile.LastAccessTime; } } public static void CopyFile(string path) { IO.CopyFile(path, -1); } public static void CopyFile(string path, int bytesPerSecond) { // check path if (String.IsNullOrEmpty(path)) { throw new NullReferenceException("filepath was not specified"); } // original file must exits if (!File.Exists(path)) { throw new FileNotFoundException("file not found. \"" + path + "\""); } } public static long FileSize(string file) { long size; using(Stream inStream = File.OpenRead(file)) { size = inStream.Length; } return size; } public static long FileSize(List<string> files) { long size = 0; foreach (string file in files) { size += IO.FileSize(file); } return size; } public static void DestroyFile(string path) { // file must exits if (!File.Exists(path)) { throw new FileNotFoundException("file not found. \"" + path + "\""); } byte[] overwriteData = new byte[512]; double writes = Math.Ceiling(new FileInfo(path).Length/(double)overwriteData.Length); RNGCryptoServiceProvider randomData = new RNGCryptoServiceProvider(); File.SetAttributes(path, FileAttributes.Normal); FileStream stream = new FileStream(path, FileMode.Open); stream.Position = 0; for (int sectorsWritten = 0; sectorsWritten < writes; sectorsWritten++) { randomData.GetBytes(overwriteData); stream.Write(overwriteData, 0, overwriteData.Length); } stream.SetLength(0); stream.Close(); DateTime dt = DateTime.Now.AddYears(21); File.SetCreationTime(path, dt); File.SetLastAccessTime(path, dt); File.SetLastWriteTime(path, dt); File.Delete(path); } private static void CopyFileSection(string source, string destination, int offset, int length, byte[] buffer) { using(Stream inStream = File.OpenRead(source)) { using (Stream outStream = File.OpenWrite(destination)) { inStream.Seek(offset, SeekOrigin.Begin); int bufferLength = buffer.Length, bytesRead; while (length > bufferLength && (bytesRead = inStream.Read(buffer, 0, bufferLength)) > 0) { outStream.Write(buffer, 0, bytesRead); length -= bytesRead; } while (length > 0 && (bytesRead = inStream.Read(buffer, 0, length)) > 0) { outStream.Write(buffer, 0, bytesRead); length -= bytesRead; } } } } public static bool WaitForFileSystem(string root, int timeout, bool expected) { bool found; Stopwatch timer = new Stopwatch(); timer.Start(); do { try { found = Directory.Exists(root); } catch { Thread.Sleep(200); found = false; } } while (found != expected && !(timer.ElapsedMilliseconds > timeout)); return (found == expected); } #region byte array helpers public static byte[] Combine(byte[] first, byte[] second) { byte[] result = new byte[first.Length + second.Length]; Buffer.BlockCopy(first, 0, result, 0, first.Length); Buffer.BlockCopy(second, 0, result, first.Length, second.Length); return result; } public static byte[] Combine(byte[] first, byte[] second, byte[] third) { byte[] result = new byte[first.Length + second.Length + third.Length]; Buffer.BlockCopy(first, 0, result, 0, first.Length); Buffer.BlockCopy(second, 0, result, first.Length, second.Length); Buffer.BlockCopy(third, 0, result, first.Length + second.Length, third.Length); return result; } public static byte[] Combine(params byte[][] arrays) { int size = 0; foreach (byte[] data in arrays) { size += data.Length; } byte[] result = new byte[size]; int offset = 0; foreach (byte[] data in arrays) { Buffer.BlockCopy(data, 0, result, offset, data.Length); offset += data.Length; } return result; } public static byte[] Split(ushort u16) { byte lower = (byte)(u16 & 0xff); byte upper = (byte)(u16 >> 8); return new byte[] { upper, lower }; } public static byte[] Split(uint u32) { ushort lower = (ushort)(u32 & 0xffff); ushort upper = (ushort)(u32 >> 16); return Combine(Split(upper), Split(lower)); } public static byte[] SubSet(byte[] source, int first, int length) { byte[] result = new byte[length]; Buffer.BlockCopy(source, first, result, 0, length); return result; } public static byte[] ReverseBytes(byte[] source) { Array.Reverse(source); return source; } public static byte[] SubSetReversed(byte[] source, int first, int length) { byte[] result = SubSet(source, first, length); Array.Reverse(result); return result; } #endregion } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="iCall.TriggeredHandlerBinding", Namespace="urn:iControl")] public partial class iCallTriggeredHandler : iControlInterface { public iCallTriggeredHandler() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_filter //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void add_filter( string [] handlers, string [] [] subscriptions, string [] [] [] filters, string [] [] [] values ) { this.Invoke("add_filter", new object [] { handlers, subscriptions, filters, values}); } public System.IAsyncResult Beginadd_filter(string [] handlers,string [] [] subscriptions,string [] [] [] filters,string [] [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_filter", new object[] { handlers, subscriptions, filters, values}, callback, asyncState); } public void Endadd_filter(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_subscription //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void add_subscription( string [] handlers, string [] [] subscriptions, string [] [] events ) { this.Invoke("add_subscription", new object [] { handlers, subscriptions, events}); } public System.IAsyncResult Beginadd_subscription(string [] handlers,string [] [] subscriptions,string [] [] events, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_subscription", new object[] { handlers, subscriptions, events}, callback, asyncState); } public void Endadd_subscription(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void create( string [] handlers, string [] scripts ) { this.Invoke("create", new object [] { handlers, scripts}); } public System.IAsyncResult Begincreate(string [] handlers,string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { handlers, scripts}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_handlers //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void delete_all_handlers( ) { this.Invoke("delete_all_handlers", new object [0]); } public System.IAsyncResult Begindelete_all_handlers(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_handlers", new object[0], callback, asyncState); } public void Enddelete_all_handlers(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_handler //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void delete_handler( string [] handlers ) { this.Invoke("delete_handler", new object [] { handlers}); } public System.IAsyncResult Begindelete_handler(string [] handlers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_handler", new object[] { handlers}, callback, asyncState); } public void Enddelete_handler(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] handlers ) { object [] results = this.Invoke("get_description", new object [] { handlers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] handlers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { handlers}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_filter //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] [] get_filter( string [] handlers, string [] [] subscriptions ) { object [] results = this.Invoke("get_filter", new object [] { handlers, subscriptions}); return ((string [] [] [])(results[0])); } public System.IAsyncResult Beginget_filter(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_filter", new object[] { handlers, subscriptions}, callback, asyncState); } public string [] [] [] Endget_filter(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [] [])(results[0])); } //----------------------------------------------------------------------- // get_filter_match_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public iCallMatchAlgorithm [] [] [] get_filter_match_algorithm( string [] handlers, string [] [] subscriptions, string [] [] [] filters ) { object [] results = this.Invoke("get_filter_match_algorithm", new object [] { handlers, subscriptions, filters}); return ((iCallMatchAlgorithm [] [] [])(results[0])); } public System.IAsyncResult Beginget_filter_match_algorithm(string [] handlers,string [] [] subscriptions,string [] [] [] filters, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_filter_match_algorithm", new object[] { handlers, subscriptions, filters}, callback, asyncState); } public iCallMatchAlgorithm [] [] [] Endget_filter_match_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((iCallMatchAlgorithm [] [] [])(results[0])); } //----------------------------------------------------------------------- // get_filter_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] [] get_filter_value( string [] handlers, string [] [] subscriptions, string [] [] [] filters ) { object [] results = this.Invoke("get_filter_value", new object [] { handlers, subscriptions, filters}); return ((string [] [] [])(results[0])); } public System.IAsyncResult Beginget_filter_value(string [] handlers,string [] [] subscriptions,string [] [] [] filters, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_filter_value", new object[] { handlers, subscriptions, filters}, callback, asyncState); } public string [] [] [] Endget_filter_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [] [])(results[0])); } //----------------------------------------------------------------------- // get_handler_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public iCallGeneralHandlerState [] get_handler_state( string [] handlers ) { object [] results = this.Invoke("get_handler_state", new object [] { handlers}); return ((iCallGeneralHandlerState [])(results[0])); } public System.IAsyncResult Beginget_handler_state(string [] handlers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_handler_state", new object[] { handlers}, callback, asyncState); } public iCallGeneralHandlerState [] Endget_handler_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((iCallGeneralHandlerState [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_script //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_script( string [] handlers ) { object [] results = this.Invoke("get_script", new object [] { handlers}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_script(string [] handlers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_script", new object[] { handlers}, callback, asyncState); } public string [] Endget_script(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_subscription //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_subscription( string [] handlers ) { object [] results = this.Invoke("get_subscription", new object [] { handlers}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_subscription(string [] handlers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_subscription", new object[] { handlers}, callback, asyncState); } public string [] [] Endget_subscription(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_subscription_event //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_subscription_event( string [] handlers, string [] [] subscriptions ) { object [] results = this.Invoke("get_subscription_event", new object [] { handlers, subscriptions}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_subscription_event(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_subscription_event", new object[] { handlers, subscriptions}, callback, asyncState); } public string [] [] Endget_subscription_event(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // remove_all_filters //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void remove_all_filters( string [] handlers, string [] [] subscriptions ) { this.Invoke("remove_all_filters", new object [] { handlers, subscriptions}); } public System.IAsyncResult Beginremove_all_filters(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_filters", new object[] { handlers, subscriptions}, callback, asyncState); } public void Endremove_all_filters(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_all_subscriptions //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void remove_all_subscriptions( string [] handlers ) { this.Invoke("remove_all_subscriptions", new object [] { handlers}); } public System.IAsyncResult Beginremove_all_subscriptions(string [] handlers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_subscriptions", new object[] { handlers}, callback, asyncState); } public void Endremove_all_subscriptions(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_filter //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void remove_filter( string [] handlers, string [] [] subscriptions, string [] [] [] filters ) { this.Invoke("remove_filter", new object [] { handlers, subscriptions, filters}); } public System.IAsyncResult Beginremove_filter(string [] handlers,string [] [] subscriptions,string [] [] [] filters, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_filter", new object[] { handlers, subscriptions, filters}, callback, asyncState); } public void Endremove_filter(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_subscription //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void remove_subscription( string [] handlers, string [] [] subscriptions ) { this.Invoke("remove_subscription", new object [] { handlers, subscriptions}); } public System.IAsyncResult Beginremove_subscription(string [] handlers,string [] [] subscriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_subscription", new object[] { handlers, subscriptions}, callback, asyncState); } public void Endremove_subscription(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void set_description( string [] handlers, string [] descriptions ) { this.Invoke("set_description", new object [] { handlers, descriptions}); } public System.IAsyncResult Beginset_description(string [] handlers,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { handlers, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_filter_match_algorithm //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void set_filter_match_algorithm( string [] handlers, string [] [] subscriptions, string [] [] [] filters, iCallMatchAlgorithm [] [] [] algorithms ) { this.Invoke("set_filter_match_algorithm", new object [] { handlers, subscriptions, filters, algorithms}); } public System.IAsyncResult Beginset_filter_match_algorithm(string [] handlers,string [] [] subscriptions,string [] [] [] filters,iCallMatchAlgorithm [] [] [] algorithms, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_filter_match_algorithm", new object[] { handlers, subscriptions, filters, algorithms}, callback, asyncState); } public void Endset_filter_match_algorithm(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_filter_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void set_filter_value( string [] handlers, string [] [] subscriptions, string [] [] [] filters, string [] [] [] values ) { this.Invoke("set_filter_value", new object [] { handlers, subscriptions, filters, values}); } public System.IAsyncResult Beginset_filter_value(string [] handlers,string [] [] subscriptions,string [] [] [] filters,string [] [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_filter_value", new object[] { handlers, subscriptions, filters, values}, callback, asyncState); } public void Endset_filter_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_handler_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void set_handler_state( string [] handlers, iCallGeneralHandlerState [] states ) { this.Invoke("set_handler_state", new object [] { handlers, states}); } public System.IAsyncResult Beginset_handler_state(string [] handlers,iCallGeneralHandlerState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_handler_state", new object[] { handlers, states}, callback, asyncState); } public void Endset_handler_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_script //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void set_script( string [] handlers, string [] scripts ) { this.Invoke("set_script", new object [] { handlers, scripts}); } public System.IAsyncResult Beginset_script(string [] handlers,string [] scripts, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_script", new object[] { handlers, scripts}, callback, asyncState); } public void Endset_script(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_subscription_event //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:iCall/TriggeredHandler", RequestNamespace="urn:iControl:iCall/TriggeredHandler", ResponseNamespace="urn:iControl:iCall/TriggeredHandler")] public void set_subscription_event( string [] handlers, string [] [] subscriptions, string [] [] events ) { this.Invoke("set_subscription_event", new object [] { handlers, subscriptions, events}); } public System.IAsyncResult Beginset_subscription_event(string [] handlers,string [] [] subscriptions,string [] [] events, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_subscription_event", new object[] { handlers, subscriptions, events}, callback, asyncState); } public void Endset_subscription_event(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; namespace LewisTech.Utils.Collections { /// <summary> /// Same as Queue except Dequeue function blocks until there is an object to return. /// Note: This class does not need to be synchronized /// </summary> public class BlockingQueue<T> : ICollection { private readonly Queue<T> _base; private bool _open; /// <summary> /// Create new BlockingQueue. /// </summary> /// <param name="col">The System.Collections.ICollection to copy elements from</param> //public BlockingQueue(ICollection<T> col) //{ // _base = new Queue<T>(col); // _open = true; //} /// <summary> /// Create new BlockingQueue. /// </summary> /// <param name="capacity">The initial number of elements that the queue can contain</param> public BlockingQueue(int capacity) { _base = new Queue<T>(capacity); _open = true; } /// <summary> /// Create new BlockingQueue. /// </summary> public BlockingQueue() { _base = new Queue<T>(); _open = true; } /// <summary> /// BlockingQueue Destructor (Close queue, resume any waiting thread). /// </summary> ~BlockingQueue() { Close(); } /// <summary> /// Remove all objects from the Queue. /// </summary> public void Clear() { lock (_SyncRoot) { _base.Clear(); } } /// <summary> /// Remove all objects from the Queue, resume all dequeue threads. /// </summary> public void Close() { lock (_SyncRoot) { if (_open) { _open = false; _base.Clear(); // resume any waiting threads Monitor.PulseAll(_SyncRoot); } } } /// <summary> /// Removes and returns the object at the beginning of the Queue. /// </summary> /// <returns>Object in queue.</returns> public T Dequeue() { return Dequeue(Timeout.Infinite); } /// <summary> /// Removes and returns the object at the beginning of the Queue. /// </summary> /// <param name="timeout">time to wait before returning</param> /// <returns>Object in queue.</returns> public T Dequeue(TimeSpan timeout) { return Dequeue(timeout.Milliseconds); } /// <summary> /// Removes and returns the object at the beginning of the Queue. /// </summary> /// <param name="timeout">time to wait before returning (in milliseconds)</param> /// <returns>Object in queue.</returns> public T Dequeue(int timeout) { lock (_SyncRoot) { while (_open && (_base.Count == 0)) { if (!Monitor.Wait(_SyncRoot, timeout)) { throw new InvalidOperationException("Timeout"); } } if (_open) { return _base.Dequeue(); } throw new InvalidOperationException("Queue Closed"); } } public T Peek() { lock (_SyncRoot) { while (_open && (_base.Count == 0)) { if (!Monitor.Wait(_SyncRoot, Timeout.Infinite)) { throw new InvalidOperationException("Timeout"); } } if (_open) { return _base.Peek(); } throw new InvalidOperationException("Queue Closed"); } } /// <summary> /// Adds an object to the end of the Queue. /// </summary> /// <param name="obj">Object to put in queue</param> public void Enqueue(T obj) { lock (_SyncRoot) { _base.Enqueue(obj); Monitor.Pulse(_SyncRoot); } } public bool EnqueueIfNotContains(T obj, IEqualityComparer<T> comparer) { bool added = false; lock (_SyncRoot) { if (!_base.Contains(obj, comparer)) { _base.Enqueue(obj); added = true; //Else // Trace.WriteLine("Already in Queue") } Monitor.Pulse(_SyncRoot); } return added; } /// <summary> /// Open Queue. /// </summary> public void Open() { lock (_SyncRoot) { _open = true; } } /// <summary> /// Gets flag indicating if queue has been closed. /// </summary> public bool Closed { get { return !_open; } } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { return _base.Count; } } public bool IsSynchronized { get { return true; } } private object _SyncRoot = new object(); public object SyncRoot { get { return _SyncRoot; } } public System.Collections.IEnumerator GetEnumerator() { return _base.GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Content.Server.Atmos.EntitySystems; using Content.Server.Chemistry.EntitySystems; using Content.Server.DoAfter; using Content.Server.Popups; using Content.Server.Tools.Components; using Content.Shared.ActionBlocker; using Content.Shared.Audio; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Player; using Robust.Shared.Prototypes; namespace Content.Server.Tools { public sealed partial class ToolSystem : EntitySystem { [Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!; [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; [Dependency] private readonly DoAfterSystem _doAfterSystem = default!; [Dependency] private readonly SolutionContainerSystem _solutionContainerSystem = default!; [Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!; [Dependency] private readonly PopupSystem _popupSystem = default!; public override void Initialize() { base.Initialize(); InitializeTilePrying(); InitializeWelders(); InitializeMultipleTools(); SubscribeLocalEvent<ToolDoAfterComplete>(OnDoAfterComplete); SubscribeLocalEvent<ToolDoAfterCancelled>(OnDoAfterCancelled); } private void OnDoAfterComplete(ToolDoAfterComplete ev) { // Actually finish the tool use! Depending on whether that succeeds or not, either event will be broadcast. if(ToolFinishUse(ev.Uid, ev.UserUid, ev.Fuel)) { if (ev.EventTarget != null) RaiseLocalEvent(ev.EventTarget.Value, ev.CompletedEvent, false); else RaiseLocalEvent(ev.CompletedEvent); } else if(ev.CancelledEvent != null) { if (ev.EventTarget != null) RaiseLocalEvent(ev.EventTarget.Value, ev.CancelledEvent, false); else RaiseLocalEvent(ev.CancelledEvent); } } private void OnDoAfterCancelled(ToolDoAfterCancelled ev) { if (ev.EventTarget != null) RaiseLocalEvent(ev.EventTarget.Value, ev.Event, false); else RaiseLocalEvent(ev.Event); } /// <summary> /// Whether a tool entity has the specified quality or not. /// </summary> public bool HasQuality(EntityUid uid, string quality, ToolComponent? tool = null) { return Resolve(uid, ref tool, false) && tool.Qualities.Contains(quality); } /// <summary> /// Whether a tool entity has all specified qualities or not. /// </summary> public bool HasAllQualities(EntityUid uid, IEnumerable<string> qualities, ToolComponent? tool = null) { return Resolve(uid, ref tool, false) && tool.Qualities.ContainsAll(qualities); } /// <summary> /// Sync version of UseTool. /// </summary> /// <param name="tool">The tool entity.</param> /// <param name="user">The entity using the tool.</param> /// <param name="target">Optionally, a target to use the tool on.</param> /// <param name="fuel">An optional amount of fuel or energy to consume-</param> /// <param name="doAfterDelay">A doAfter delay in seconds.</param> /// <param name="toolQualitiesNeeded">The tool qualities needed to use the tool.</param> /// <param name="doAfterCompleteEvent">An event to raise once the doAfter is completed successfully.</param> /// <param name="doAfterCancelledEvent">An event to raise once the doAfter is canceled.</param> /// <param name="doAfterEventTarget">Where to direct the do-after events. If null, events are broadcast</param> /// <param name="doAfterCheck">An optional check to perform for the doAfter.</param> /// <param name="toolComponent">The tool component.</param> /// <param name="cancelToken">Token to provide to do_after for cancelling</param> /// <returns>Whether initially, using the tool succeeded. If there's a doAfter delay, you'll need to listen to /// the <see cref="doAfterCompleteEvent"/> and <see cref="doAfterCancelledEvent"/> being broadcast /// to see whether using the tool succeeded or not. If the <see cref="doAfterDelay"/> is zero, /// this simply returns whether using the tool succeeded or not.</returns> public bool UseTool( EntityUid tool, EntityUid user, EntityUid? target, float fuel, float doAfterDelay, IEnumerable<string> toolQualitiesNeeded, object? doAfterCompleteEvent = null, object? doAfterCancelledEvent = null, EntityUid? doAfterEventTarget = null, Func<bool>? doAfterCheck = null, ToolComponent? toolComponent = null, CancellationToken? cancelToken = null) { // No logging here, after all that'd mean the caller would need to check if the component is there or not. if (!Resolve(tool, ref toolComponent, false)) return false; if (!ToolStartUse(tool, user, fuel, toolQualitiesNeeded, toolComponent)) return false; if (doAfterDelay > 0f) { var doAfterArgs = new DoAfterEventArgs(user, doAfterDelay / toolComponent.SpeedModifier, cancelToken ?? default, target) { ExtraCheck = doAfterCheck, BreakOnDamage = true, BreakOnStun = true, BreakOnTargetMove = true, BreakOnUserMove = true, NeedHand = true, BroadcastFinishedEvent = doAfterCompleteEvent != null ? new ToolDoAfterComplete(doAfterCompleteEvent, doAfterCancelledEvent, tool, user, fuel, doAfterEventTarget) : null, BroadcastCancelledEvent = doAfterCancelledEvent != null ? new ToolDoAfterCancelled(doAfterCancelledEvent, doAfterEventTarget) : null, }; _doAfterSystem.DoAfter(doAfterArgs); return true; } return ToolFinishUse(tool, user, fuel, toolComponent); } // This is hilariously long. /// <inheritdoc cref="UseTool(Robust.Shared.GameObjects.EntityUid,Robust.Shared.GameObjects.EntityUid,System.Nullable{Robust.Shared.GameObjects.EntityUid},float,float,System.Collections.Generic.IEnumerable{string},Robust.Shared.GameObjects.EntityUid,object,object,System.Func{bool}?,Content.Server.Tools.Components.ToolComponent?)"/> public bool UseTool(EntityUid tool, EntityUid user, EntityUid? target, float fuel, float doAfterDelay, string toolQualityNeeded, object doAfterCompleteEvent, object doAfterCancelledEvent, EntityUid? doAfterEventTarget = null, Func<bool>? doAfterCheck = null, ToolComponent? toolComponent = null) { return UseTool(tool, user, target, fuel, doAfterDelay, new[] { toolQualityNeeded }, doAfterCompleteEvent, doAfterCancelledEvent, doAfterEventTarget, doAfterCheck, toolComponent); } /// <summary> /// Async version of UseTool. /// </summary> /// <param name="tool">The tool entity.</param> /// <param name="user">The entity using the tool.</param> /// <param name="target">Optionally, a target to use the tool on.</param> /// <param name="fuel">An optional amount of fuel or energy to consume-</param> /// <param name="doAfterDelay">A doAfter delay in seconds.</param> /// <param name="toolQualitiesNeeded">The tool qualities needed to use the tool.</param> /// <param name="doAfterCheck">An optional check to perform for the doAfter.</param> /// <param name="toolComponent">The tool component.</param> /// <returns>Whether using the tool succeeded or not.</returns> public async Task<bool> UseTool(EntityUid tool, EntityUid user, EntityUid? target, float fuel, float doAfterDelay, IEnumerable<string> toolQualitiesNeeded, Func<bool>? doAfterCheck = null, ToolComponent? toolComponent = null) { // No logging here, after all that'd mean the caller would need to check if the component is there or not. if (!Resolve(tool, ref toolComponent, false)) return false; if (!ToolStartUse(tool, user, fuel, toolQualitiesNeeded, toolComponent)) return false; if (doAfterDelay > 0f) { var doAfterArgs = new DoAfterEventArgs(user, doAfterDelay / toolComponent.SpeedModifier, default, target) { ExtraCheck = doAfterCheck, BreakOnDamage = true, BreakOnStun = true, BreakOnTargetMove = true, BreakOnUserMove = true, NeedHand = true, }; var result = await _doAfterSystem.WaitDoAfter(doAfterArgs); if (result == DoAfterStatus.Cancelled) return false; } return ToolFinishUse(tool, user, fuel, toolComponent); } // This is hilariously long. /// <inheritdoc cref="UseTool(Robust.Shared.GameObjects.EntityUid,Robust.Shared.GameObjects.EntityUid,System.Nullable{Robust.Shared.GameObjects.EntityUid},float,float,System.Collections.Generic.IEnumerable{string},Robust.Shared.GameObjects.EntityUid,object,object,System.Func{bool}?,Content.Server.Tools.Components.ToolComponent?)"/> public Task<bool> UseTool(EntityUid tool, EntityUid user, EntityUid? target, float fuel, float doAfterDelay, string toolQualityNeeded, Func<bool>? doAfterCheck = null, ToolComponent? toolComponent = null) { return UseTool(tool, user, target, fuel, doAfterDelay, new [] {toolQualityNeeded}, doAfterCheck, toolComponent); } private bool ToolStartUse(EntityUid tool, EntityUid user, float fuel, IEnumerable<string> toolQualitiesNeeded, ToolComponent? toolComponent = null) { if (!Resolve(tool, ref toolComponent)) return false; if (!toolComponent.Qualities.ContainsAll(toolQualitiesNeeded)) return false; var beforeAttempt = new ToolUseAttemptEvent(fuel, user); RaiseLocalEvent(tool, beforeAttempt, false); return !beforeAttempt.Cancelled; } private bool ToolFinishUse(EntityUid tool, EntityUid user, float fuel, ToolComponent? toolComponent = null) { if (!Resolve(tool, ref toolComponent)) return false; var afterAttempt = new ToolUseFinishAttemptEvent(fuel, user); RaiseLocalEvent(tool, afterAttempt, false); if (afterAttempt.Cancelled) return false; if (toolComponent.UseSound != null) PlayToolSound(tool, toolComponent); return true; } public void PlayToolSound(EntityUid uid, ToolComponent? tool = null) { if (!Resolve(uid, ref tool)) return; if (tool.UseSound is not {} sound) return; // Pass tool.Owner to Filter.Pvs to avoid a TryGetEntity call. SoundSystem.Play(Filter.Pvs(tool.Owner), sound.GetSound(), uid, AudioHelpers.WithVariation(0.175f).WithVolume(-5f)); } public override void Update(float frameTime) { base.Update(frameTime); UpdateWelders(frameTime); } private sealed class ToolDoAfterComplete : EntityEventArgs { public readonly object CompletedEvent; public readonly object? CancelledEvent; public readonly EntityUid Uid; public readonly EntityUid UserUid; public readonly float Fuel; public readonly EntityUid? EventTarget; public ToolDoAfterComplete(object completedEvent, object? cancelledEvent, EntityUid uid, EntityUid userUid, float fuel, EntityUid? eventTarget = null) { CompletedEvent = completedEvent; Uid = uid; UserUid = userUid; Fuel = fuel; CancelledEvent = cancelledEvent; EventTarget = eventTarget; } } private sealed class ToolDoAfterCancelled : EntityEventArgs { public readonly object Event; public readonly EntityUid? EventTarget; public ToolDoAfterCancelled(object @event, EntityUid? eventTarget = null) { Event = @event; EventTarget = eventTarget; } } } /// <summary> /// Attempt event called *before* any do afters to see if the tool usage should succeed or not. /// You can change the fuel consumption by changing the Fuel property. /// </summary> public sealed class ToolUseAttemptEvent : CancellableEntityEventArgs { public float Fuel { get; set; } public EntityUid User { get; } public ToolUseAttemptEvent(float fuel, EntityUid user) { Fuel = fuel; User = user; } } /// <summary> /// Attempt event called *after* any do afters to see if the tool usage should succeed or not. /// You can use this event to consume any fuel needed. /// </summary> public sealed class ToolUseFinishAttemptEvent : CancellableEntityEventArgs { public float Fuel { get; } public EntityUid User { get; } public ToolUseFinishAttemptEvent(float fuel, EntityUid user) { Fuel = fuel; } } }
// // Copyright (c) 2004-2018 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.Targets { using System; using System.Collections.Generic; using System.Linq; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Represents logging target. /// </summary> [NLogConfigurationItem] public abstract class Target : ISupportsInitialize, IDisposable { private readonly object _lockObject = new object(); private List<Layout> _allLayouts; /// <summary> Are all layouts in this target thread-agnostic, if so we don't precalculate the layouts </summary> private bool _allLayoutsAreThreadAgnostic; private bool _allLayoutsAreThreadSafe; private bool _oneLayoutIsMutableUnsafe; private bool _scannedForLayouts; private Exception _initializeException; /// <summary> /// The Max StackTraceUsage of all the <see cref="Layout"/> in this Target /// </summary> internal StackTraceUsage StackTraceUsage { get; private set; } /// <summary> /// Gets or sets the name of the target. /// </summary> /// <docgen category='General Options' order='10' /> public string Name { get; set; } /// <summary> /// Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers /// Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit /// </summary> /// <docgen category='Performance Tuning Options' order='10' /> public bool OptimizeBufferReuse { get; set; } /// <summary> /// Gets the object which can be used to synchronize asynchronous operations that must rely on the . /// </summary> protected object SyncRoot => _lockObject; /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } /// <summary> /// Gets a value indicating whether the target has been initialized. /// </summary> protected bool IsInitialized { get { if (_isInitialized) return true; // Initialization has completed // Lets wait for initialization to complete, and then check again lock (SyncRoot) { return _isInitialized; } } } private volatile bool _isInitialized; /// <summary> /// Can be used if <see cref="OptimizeBufferReuse"/> has been enabled. /// </summary> internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator(); private StringBuilderPool _precalculateStringBuilderPool; /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { bool wasInitialized = _isInitialized; Initialize(configuration); if (wasInitialized && configuration != null) { FindAllLayouts(); } } } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { Close(); } /// <summary> /// Closes the target. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Flush(AsyncContinuation asyncContinuation) { if (asyncContinuation == null) { throw new ArgumentNullException(nameof(asyncContinuation)); } asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation); lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed asyncContinuation(null); return; } try { FlushAsync(asyncContinuation); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } asyncContinuation(exception); } } } /// <summary> /// Calls the <see cref="Layout.Precalculate"/> on each volatile layout /// used by this target. /// This method won't prerender if all layouts in this target are thread-agnostic. /// </summary> /// <param name="logEvent"> /// The log event. /// </param> public void PrecalculateVolatileLayouts(LogEventInfo logEvent) { if (_allLayoutsAreThreadAgnostic) { if (!_oneLayoutIsMutableUnsafe || logEvent.IsLogEventMutableSafe()) return; } // Not all Layouts support concurrent threads, so we have to protect them if (OptimizeBufferReuse) { if (_allLayoutsAreThreadSafe) { if (!IsInitialized) return; if (_allLayouts == null) return; if (_precalculateStringBuilderPool == null) { System.Threading.Interlocked.CompareExchange(ref _precalculateStringBuilderPool, new StringBuilderPool(System.Environment.ProcessorCount * 4, 1024), null); } using (var targetBuilder = _precalculateStringBuilderPool.Acquire()) { foreach (Layout layout in _allLayouts) { targetBuilder.Item.ClearBuilder(); layout.PrecalculateBuilder(logEvent, targetBuilder.Item); } } } else { lock (SyncRoot) { if (!_isInitialized) return; if (_allLayouts == null) return; using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { foreach (Layout layout in _allLayouts) { targetBuilder.Result.ClearBuilder(); layout.PrecalculateBuilder(logEvent, targetBuilder.Result); } } } } } else { lock (SyncRoot) { if (!_isInitialized) return; if (_allLayouts == null) return; foreach (Layout layout in _allLayouts) { layout.Precalculate(logEvent); } } } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var targetAttribute = GetType().GetCustomAttribute<TargetAttribute>(); if (targetAttribute != null) { return $"{targetAttribute.Name} Target[{(Name ?? "(unnamed)")}]"; } return GetType().Name; } /// <summary> /// Writes the log to the target. /// </summary> /// <param name="logEvent">Log event to write.</param> public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent) { if (!IsInitialized) { lock (SyncRoot) { logEvent.Continuation(null); } return; } if (_initializeException != null) { lock (SyncRoot) { logEvent.Continuation(CreateInitException()); } return; } var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation); var wrappedLogEvent = logEvent.LogEvent.WithContinuation(wrappedContinuation); try { WriteAsyncThreadSafe(wrappedLogEvent); } catch (Exception ex) { if (ex.MustBeRethrown()) throw; wrappedLogEvent.Continuation(ex); } } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents) { if (logEvents == null || logEvents.Length == 0) { return; } WriteAsyncLogEvents((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes the array of log events. /// </summary> /// <param name="logEvents">The log events.</param> public void WriteAsyncLogEvents(IList<AsyncLogEventInfo> logEvents) { if (logEvents == null || logEvents.Count == 0) { return; } if (!IsInitialized) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } } return; } if (_initializeException != null) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(CreateInitException()); } } return; } IList<AsyncLogEventInfo> wrappedEvents; if (OptimizeBufferReuse) { for (int i = 0; i < logEvents.Count; ++i) { logEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation)); } wrappedEvents = logEvents; } else { var cloneLogEvents = new AsyncLogEventInfo[logEvents.Count]; for (int i = 0; i < logEvents.Count; ++i) { AsyncLogEventInfo ev = logEvents[i]; cloneLogEvents[i] = ev.LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(ev.Continuation)); } wrappedEvents = cloneLogEvents; } try { WriteAsyncThreadSafe(wrappedEvents); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } // in case of synchronous failure, assume that nothing is running asynchronously for (int i = 0; i < wrappedEvents.Count; ++i) { wrappedEvents[i].Continuation(exception); } } } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { lock (SyncRoot) { LoggingConfiguration = configuration; if (!IsInitialized) { PropertyHelper.CheckRequiredParameters(this); try { InitializeTarget(); _initializeException = null; if (!_scannedForLayouts) { InternalLogger.Debug("{0}: InitializeTarget is done but not scanned For Layouts", this); //this is critical, as we need the layouts. So if base.InitializeTarget() isn't called, we fix the layouts here. FindAllLayouts(); } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error initializing target", this); _initializeException = exception; if (exception.MustBeRethrown()) { throw; } } finally { _isInitialized = true; } } } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { lock (SyncRoot) { LoggingConfiguration = null; if (IsInitialized) { _isInitialized = false; try { if (_initializeException == null) { // if Init succeeded, call Close() InternalLogger.Debug("Closing target '{0}'.", this); CloseTarget(); InternalLogger.Debug("Closed target '{0}'.", this); } } catch (Exception exception) { InternalLogger.Error(exception, "{0}: Error closing target", this); if (exception.MustBeRethrown()) { throw; } } } } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (_isInitialized) { _isInitialized = false; if (_initializeException == null) { CloseTarget(); } } } } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected virtual void InitializeTarget() { //rescan as amount layouts can be changed. FindAllLayouts(); } private void FindAllLayouts() { _allLayouts = ObjectGraphScanner.FindReachableObjects<Layout>(false, this); InternalLogger.Trace("{0} has {1} layouts", this, _allLayouts.Count); _allLayoutsAreThreadAgnostic = _allLayouts.All(layout => layout.ThreadAgnostic); _oneLayoutIsMutableUnsafe = _allLayoutsAreThreadAgnostic && _allLayouts.Any(layout => layout.MutableUnsafe); if (!_allLayoutsAreThreadAgnostic || _oneLayoutIsMutableUnsafe) { _allLayoutsAreThreadSafe = _allLayouts.All(layout => layout.ThreadSafe); } StackTraceUsage = _allLayouts.DefaultIfEmpty().Max(layout => layout?.StackTraceUsage ?? StackTraceUsage.None); if (this is IUsesStackTrace usesStackTrace && usesStackTrace.StackTraceUsage > StackTraceUsage) StackTraceUsage = usesStackTrace.StackTraceUsage; _scannedForLayouts = true; } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected virtual void CloseTarget() { } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected virtual void FlushAsync(AsyncContinuation asyncContinuation) { asyncContinuation(null); } /// <summary> /// Writes logging event to the log target. Must be overridden in inheriting /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected virtual void Write(LogEventInfo logEvent) { // Override to perform the actual write-operation } /// <summary> /// Writes async log event to the log target. /// </summary> /// <param name="logEvent">Async Log event to be written out.</param> protected virtual void Write(AsyncLogEventInfo logEvent) { try { Write(logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } logEvent.Continuation(exception); } } /// <summary> /// Writes a log event to the log target, in a thread safe manner. /// Any override of this method has to provide their own synchronization mechanism. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// threadsafe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvent">Log event to be written out.</param> protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed logEvent.Continuation(null); return; } Write(logEvent); } } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected virtual void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void Write(IList<AsyncLogEventInfo> logEvents) { for (int i = 0; i < logEvents.Count; ++i) { Write(logEvents[i]); } } /// <summary> /// NOTE! Obsolete, instead override WriteAsyncThreadSafe(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target, in a thread safe manner. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// threadsafe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo[] logEvents) { WriteAsyncThreadSafe((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Writes an array of logging events to the log target, in a thread safe manner. /// Any override of this method has to provide their own synchronization mechanism. /// /// !WARNING! Custom targets should only override this method if able to provide their /// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be /// threadsafe, so using them without a SyncRoot-object can be dangerous. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected virtual void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents) { lock (SyncRoot) { if (!IsInitialized) { // In case target was Closed for (int i = 0; i < logEvents.Count; ++i) { logEvents[i].Continuation(null); } return; } AsyncLogEventInfo[] logEventsArray = OptimizeBufferReuse ? null : logEvents as AsyncLogEventInfo[]; if (!OptimizeBufferReuse && logEventsArray != null) { // Backwards compatibility #pragma warning disable 612, 618 Write(logEventsArray); #pragma warning restore 612, 618 } else { Write(logEvents); } } } private Exception CreateInitException() { return new NLogRuntimeException($"Target {this} failed to initialize.", _initializeException); } /// <summary> /// Merges (copies) the event context properties from any event info object stored in /// parameters of the given event info object. /// </summary> /// <param name="logEvent">The event info object to perform the merge to.</param> [Obsolete("Logger.Trace(logEvent) now automatically captures the logEvent Properties. Marked obsolete on NLog 4.6")] protected void MergeEventProperties(LogEventInfo logEvent) { if (logEvent.Parameters == null || logEvent.Parameters.Length == 0) { return; } //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < logEvent.Parameters.Length; ++i) { var logEventParameter = logEvent.Parameters[i] as LogEventInfo; if (logEventParameter != null && logEventParameter.HasProperties) { foreach (var key in logEventParameter.Properties.Keys) { logEvent.Properties.Add(key, logEventParameter.Properties[key]); } logEventParameter.Properties.Clear(); } } } /// <summary> /// Renders the event info in layout. /// </summary> /// <param name="layout">The layout.</param> /// <param name="logEvent">The event info.</param> /// <returns>String representing log event.</returns> protected string RenderLogEvent(Layout layout, LogEventInfo logEvent) { if (layout == null || logEvent == null) return null; // Signal that input was wrong if (OptimizeBufferReuse) { SimpleLayout simpleLayout = layout as SimpleLayout; if (simpleLayout != null && simpleLayout.IsFixedText) return simpleLayout.Render(logEvent); if (!layout.ThreadAgnostic || layout.MutableUnsafe) { if (logEvent.TryGetCachedLayoutValue(layout, out var value)) { return value?.ToString() ?? string.Empty; } } using (var localTarget = ReusableLayoutBuilder.Allocate()) { return layout.RenderAllocateBuilder(logEvent, localTarget.Result); } } else { return layout.Render(logEvent); } } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T"> Type of the Target.</typeparam> /// <param name="name"> Name of the Target.</param> public static void Register<T>(string name) where T : Target { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom Target. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="targetType"> Type of the Target.</param> /// <param name="name"> Name of the Target.</param> public static void Register(string name, Type targetType) { ConfigurationItemFactory.Default.Targets .RegisterDefinition(name, targetType); } } }
// // AppleDeviceSource.cs // // Author: // Alan McGovern <amcgovern@novell.com> // // Copyright (C) 2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Banshee.Base; using Banshee.Collection.Database; using Banshee.ServiceStack; using Banshee.Library; using System.Collections.Generic; using System.Threading; using Banshee.Hardware; using Banshee.Sources; using Banshee.I18n; using Hyena; namespace Banshee.Dap.AppleDevice { public class AppleDeviceSource : DapSource { GPod.Device Device { get; set; } IVolume Volume { get; set; } GPod.ITDB MediaDatabase { get; set; } private Dictionary<int, AppleDeviceTrackInfo> tracks_map = new Dictionary<int, AppleDeviceTrackInfo> (); // FIXME: EPIC FAIL #region Device Setup/Dispose public override void DeviceInitialize (IDevice device) { Volume = device as IVolume; if (Volume == null) { throw new InvalidDeviceException (); } Device = new GPod.Device (Volume.MountPoint); if (GPod.ITDB.GetControlPath (Device) == null) { throw new InvalidDeviceException (); } base.DeviceInitialize (device); Name = Volume.Name; SupportsPlaylists = true; SupportsPodcasts = Device.SupportsPodcast; SupportsVideo = Device.SupportsVideo; Initialize (); // FIXME: Properly parse the device, color and generation and don't use the fallback strings // IpodInfo is null on Macos formated ipods. I don't think we can really do anything with them // but they get loaded as UMS devices if we throw an NRE here. if (Device.IpodInfo != null) { AddDapProperty (Catalog.GetString ("Device"), Device.IpodInfo.ModelString); AddDapProperty (Catalog.GetString ("Generation"), Device.IpodInfo.GenerationString); } // FIXME //AddDapProperty (Catalog.GetString ("Color"), "black"); AddDapProperty (Catalog.GetString ("Capacity"), string.Format ("{0:0.00}GB", BytesCapacity)); AddDapProperty (Catalog.GetString ("Available"), string.Format ("{0:0.00}GB", BytesAvailable)); AddDapProperty (Catalog.GetString ("Serial number"), Volume.Serial); //AddDapProperty (Catalog.GetString ("Produced on"), ipod_device.ProductionInfo.DisplayDate); //AddDapProperty (Catalog.GetString ("Firmware"), ipod_device.FirmwareVersion); //string [] capabilities = new string [ipod_device.ModelInfo.Capabilities.Count]; //ipod_device.ModelInfo.Capabilities.CopyTo (capabilities, 0); //AddDapProperty (Catalog.GetString ("Capabilities"), String.Join (", ", capabilities)); AddYesNoDapProperty (Catalog.GetString ("Supports cover art"), Device.SupportsArtwork); AddYesNoDapProperty (Catalog.GetString ("Supports photos"), Device.SupportsPhoto); } public override void Dispose () { //ThreadAssist.ProxyToMain (DestroyUnsupportedView); CancelSyncThread (); base.Dispose (); } // WARNING: This will be called from a thread! protected override void Eject () { base.Eject (); CancelSyncThread (); if (Volume.CanUnmount) Volume.Unmount (); if (Volume.CanEject) Volume.Eject (); Dispose (); } protected override bool CanHandleDeviceCommand (DeviceCommand command) { // Whats this for? return false; // try { // SafeUri uri = new SafeUri (command.DeviceId); // return IpodDevice.MountPoint.StartsWith (uri.LocalPath); // } catch { // return false; // } } #endregion #region Database Loading // WARNING: This will be called from a thread! protected override void LoadFromDevice () { LoadFromDevice (false); OnTracksAdded (); } private void LoadFromDevice (bool refresh) { tracks_map.Clear (); if (refresh || MediaDatabase == null) { if (MediaDatabase != null) MediaDatabase.Dispose (); MediaDatabase = new GPod.ITDB (Device.Mountpoint); } foreach (var ipod_track in MediaDatabase.Tracks) { try { var track = new AppleDeviceTrackInfo (ipod_track); if (!tracks_map.ContainsKey (track.TrackId)) { track.PrimarySource = this; track.Save (false); tracks_map.Add (track.TrackId, track); } } catch (Exception e) { Log.Exception (e); } } // Hyena.Data.Sqlite.HyenaSqliteCommand insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand ( // @"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) // SELECT ?, TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND ExternalID = ?"); // foreach (IPod.Playlist playlist in ipod_device.TrackDatabase.Playlists) { // if (playlist.IsOnTheGo) { // || playlist.IsPodcast) { // continue; // } // PlaylistSource pl_src = new PlaylistSource (playlist.Name, this); // pl_src.Save (); // // We use the IPod.Track.Id here b/c we just shoved it into ExternalID above when we loaded // // the tracks, however when we sync, the Track.Id values may/will change. // foreach (IPod.Track track in playlist.Tracks) { // ServiceManager.DbConnection.Execute (insert_cmd, pl_src.DbId, this.DbId, track.Id); // } // pl_src.UpdateCounts (); // AddChildSource (pl_src); // } /*else { BuildDatabaseUnsupportedWidget (); }*/ /*if(previous_database_supported != database_supported) { OnPropertiesChanged(); }*/ } // private void DestroyUnsupportedView () // { // if (unsupported_view != null) { // unsupported_view.Refresh -= OnRebuildDatabaseRefresh; // unsupported_view.Destroy (); // unsupported_view = null; // } // } #endregion #region Source Cosmetics internal string [] _GetIconNames () { return GetIconNames (); } protected override string [] GetIconNames () { string [] names = new string[4]; string prefix = "multimedia-player-"; //string shell_color = "green"; names[0] = ""; names[2] = "ipod-standard-color"; names[3] = "multimedia-player"; /* switch ("grayscale") { case "grayscale": names[1] = "ipod-standard-monochrome"; break; case "color": names[1] = "ipod-standard-color"; break; case "mini": names[1] = String.Format ("ipod-mini-{0}", shell_color); names[2] = "ipod-mini-silver"; break; case "shuffle": names[1] = String.Format ("ipod-shuffle-{0}", shell_color); names[2] = "ipod-shuffle"; break; case "nano": case "nano3": names[1] = String.Format ("ipod-nano-{0}", shell_color); names[2] = "ipod-nano-white"; break; case "video": names[1] = String.Format ("ipod-video-{0}", shell_color); names[2] = "ipod-video-white"; break; case "classic": case "touch": case "phone": default: break; } */ names[1] = names[1] ?? names[2]; names[1] = prefix + names[1]; names[2] = prefix + names[2]; return names; } public override void Rename (string name) { return; // if (!CanRename) { // return; // } // // try { // if (name_path != null) { // Directory.CreateDirectory (Path.GetDirectoryName (name_path)); // // using (StreamWriter writer = new StreamWriter (File.Open (name_path, FileMode.Create), // System.Text.Encoding.Unicode)) { // writer.Write (name); // } // } // } catch (Exception e) { // Log.Exception (e); // } // // ipod_device.Name = name; // base.Rename (name); } public override bool CanRename { get { return !(IsAdding || IsDeleting || IsReadOnly); } } public override long BytesUsed { get { return (long) Volume.Capacity - Volume.Available; } } public override long BytesCapacity { get { return (long) Volume.Capacity; } } #endregion #region Syncing protected override void OnTracksAdded () { if (!IsAdding && tracks_to_add.Count > 0 && !Sync.Syncing) { QueueSync (); } base.OnTracksAdded (); } protected override void OnTracksDeleted () { if (!IsDeleting && tracks_to_remove.Count > 0 && !Sync.Syncing) { QueueSync (); } base.OnTracksDeleted (); } private Queue<AppleDeviceTrackInfo> tracks_to_add = new Queue<AppleDeviceTrackInfo> (); private Queue<AppleDeviceTrackInfo> tracks_to_remove = new Queue<AppleDeviceTrackInfo> (); private uint sync_timeout_id = 0; private object sync_timeout_mutex = new object (); private object sync_mutex = new object (); private Thread sync_thread; private AutoResetEvent sync_thread_wait; private bool sync_thread_dispose = false; public override bool AcceptsInputFromSource (Source source) { return base.AcceptsInputFromSource (source); } public override bool CanAddTracks { get { return base.CanAddTracks; } } public override bool IsReadOnly { get { return false; }//!database_supported; } } public override void Import () { Banshee.ServiceStack.ServiceManager.Get<LibraryImportManager> ().Enqueue (GPod.ITDB.GetMusicPath (Device)); } public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job) { Banshee.IO.File.Copy (track.Uri, uri, false); } protected override bool DeleteTrack (DatabaseTrackInfo track) { lock (sync_mutex) { if (!tracks_map.ContainsKey (track.TrackId)) { return true; } var ipod_track = tracks_map[track.TrackId]; if (ipod_track != null) { tracks_to_remove.Enqueue (ipod_track); } return true; } } protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri) { lock (sync_mutex) { if (track.PrimarySourceId == DbId) { return; } if (track.Duration.Equals (TimeSpan.Zero)) { throw new Exception (Catalog.GetString ("Track duration is zero")); } AppleDeviceTrackInfo ipod_track = new AppleDeviceTrackInfo (track); ipod_track.Uri = fromUri; ipod_track.PrimarySource = this; ipod_track.Save (false); tracks_to_add.Enqueue (ipod_track); } } public override void SyncPlaylists () { if (!IsReadOnly && Monitor.TryEnter (sync_mutex)) { PerformSync (); Monitor.Exit (sync_mutex); } } private void QueueSync () { lock (sync_timeout_mutex) { if (sync_timeout_id > 0) { Application.IdleTimeoutRemove (sync_timeout_id); } sync_timeout_id = Application.RunTimeout (150, PerformSync); } } private void CancelSyncThread () { Thread thread = sync_thread; lock (sync_mutex) { if (sync_thread != null && sync_thread_wait != null) { sync_thread_dispose = true; sync_thread_wait.Set (); } } if (thread != null) { thread.Join (); } } private bool PerformSync () { lock (sync_mutex) { if (sync_thread == null) { sync_thread_wait = new AutoResetEvent (false); sync_thread = new Thread (new ThreadStart (PerformSyncThread)); sync_thread.Name = "iPod Sync Thread"; sync_thread.IsBackground = false; sync_thread.Priority = ThreadPriority.Lowest; sync_thread.Start (); } sync_thread_wait.Set (); lock (sync_timeout_mutex) { sync_timeout_id = 0; } return false; } } private void PerformSyncThread () { try { while (true) { sync_thread_wait.WaitOne (); if (sync_thread_dispose) { break; } PerformSyncThreadCycle (); } lock (sync_mutex) { sync_thread_dispose = false; sync_thread_wait.Close (); sync_thread_wait = null; sync_thread = null; } } catch (Exception e) { Log.Exception (e); } } private void PerformSyncThreadCycle () { OnIpodDatabaseSaveStarted (this, EventArgs.Empty); while (tracks_to_add.Count > 0) { AppleDeviceTrackInfo track = null; lock (sync_mutex) { track = tracks_to_add.Dequeue (); } try { OnIpodDatabaseSaveProgressChanged (this, EventArgs.Empty); track.CommitToIpod (MediaDatabase); tracks_map[track.TrackId] = track; } catch (Exception e) { Log.Exception ("Cannot save track to iPod", e); } } // TODO sync updated metadata to changed tracks while (tracks_to_remove.Count > 0) { AppleDeviceTrackInfo track = null; lock (sync_mutex) { track = tracks_to_remove.Dequeue (); } if (tracks_map.ContainsKey (track.TrackId)) { tracks_map.Remove (track.TrackId); } try { if (track.IpodTrack != null) { OnIpodDatabaseSaveProgressChanged (this, EventArgs.Empty); foreach (var playlist in MediaDatabase.Playlists) playlist.Tracks.Remove (track.IpodTrack); MediaDatabase.MasterPlaylist.Tracks.Remove (track.IpodTrack); MediaDatabase.Tracks.Remove (track.IpodTrack); Banshee.IO.File.Delete (new SafeUri (GPod.ITDB.GetLocalPath (Device, track.IpodTrack))); } else { Log.Error ("The ipod track was null"); } } catch (Exception e) { Log.Exception ("Cannot remove track from iPod", e); } } // // Remove playlists on the device // List<IPod.Playlist> device_playlists = new List<IPod.Playlist> (ipod_device.TrackDatabase.Playlists); // foreach (IPod.Playlist playlist in device_playlists) { // if (!playlist.IsOnTheGo) { // ipod_device.TrackDatabase.RemovePlaylist (playlist); // } // } // device_playlists.Clear (); // // if (SupportsPlaylists) { // // Add playlists from Banshee to the device // foreach (Source child in Children) { // PlaylistSource from = child as PlaylistSource; // if (from != null && from.Count > 0) { // IPod.Playlist playlist = ipod_device.TrackDatabase.CreatePlaylist (from.Name); // foreach (int track_id in ServiceManager.DbConnection.QueryEnumerable<int> (String.Format ( // "SELECT CoreTracks.TrackID FROM {0} WHERE {1}", // from.DatabaseTrackModel.ConditionFromFragment, from.DatabaseTrackModel.Condition))) // { // if (tracks_map.ContainsKey (track_id)) { // playlist.AddTrack (tracks_map[track_id].IpodTrack); // } // } // } // } // } try { // ipod_device.TrackDatabase.SaveStarted += OnIpodDatabaseSaveStarted; // ipod_device.TrackDatabase.SaveEnded += OnIpodDatabaseSaveEnded; // ipod_device.TrackDatabase.SaveProgressChanged += OnIpodDatabaseSaveProgressChanged; MediaDatabase.Write (); Log.Information ("Wrote iPod database"); } catch (Exception e) { Log.Exception ("Failed to save iPod database", e); } finally { OnIpodDatabaseSaveEnded (this, EventArgs.Empty); // ipod_device.TrackDatabase.SaveStarted -= OnIpodDatabaseSaveStarted; // ipod_device.TrackDatabase.SaveEnded -= OnIpodDatabaseSaveEnded; // ipod_device.TrackDatabase.SaveProgressChanged -= OnIpodDatabaseSaveProgressChanged; } } private UserJob sync_user_job; private void OnIpodDatabaseSaveStarted (object o, EventArgs args) { DisposeSyncUserJob (); sync_user_job = new UserJob (Catalog.GetString ("Syncing iPod"), Catalog.GetString ("Preparing to synchronize..."), GetIconNames ()); sync_user_job.Register (); } private void OnIpodDatabaseSaveEnded (object o, EventArgs args) { DisposeSyncUserJob (); } private void DisposeSyncUserJob () { if (sync_user_job != null) { sync_user_job.Finish (); sync_user_job = null; } } private void OnIpodDatabaseSaveProgressChanged (object o, EventArgs args) { string message = string.Format ("Copying track {0} of {1}", 1, tracks_to_add.Count + tracks_to_remove.Count); double progress = 1.0 / (tracks_to_add.Count + tracks_to_remove.Count); if (progress >= 0.99) { sync_user_job.Status = Catalog.GetString ("Flushing to disk..."); sync_user_job.Progress = 0; } else { sync_user_job.Status = message; sync_user_job.Progress = progress; } } public bool SyncNeeded { get { lock (sync_mutex) { return tracks_to_add.Count > 0 || tracks_to_remove.Count > 0; } } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.NetFramework.CSharp.Analyzers; using Microsoft.NetFramework.VisualBasic.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingInApiDesignAnalyzerTests : DiagnosticAnalyzerTestBase { private const string CA3077RuleId = DoNotUseInsecureDtdProcessingInApiDesignAnalyzer.RuleId; private readonly string _CA3077ConstructorMessage = MicrosoftNetFrameworkAnalyzersResources.XmlDocumentDerivedClassConstructorNoSecureXmlResolverMessage; protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new BasicDoNotUseInsecureDtdProcessingInApiDesignAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new CSharpDoNotUseInsecureDtdProcessingInApiDesignAnalyzer(); } private DiagnosticResult GetCA3077ConstructorCSharpResultAt(int line, int column, string name) { return GetCSharpResultAt(line, column, CA3077RuleId, string.Format(_CA3077ConstructorMessage, name)); } private DiagnosticResult GetCA3077ConstructorBasicResultAt(int line, int column, string name) { return GetBasicResultAt(line, column, CA3077RuleId, string.Format(_CA3077ConstructorMessage, name)); } [Fact] public void XmlDocumentDerivedTypeWithEmptyConstructorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { public TestClass () {} } }", GetCA3077ConstructorCSharpResultAt(9, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Public Sub New() End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(7, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetResolverToNullInOnlyCtorShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { public TestClass() { this.XmlResolver = null; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Public Sub New() Me.XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public void XmlDocumentDerivedTypeSetInsecureResolverInOnlyCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { public TestClass(XmlResolver resolver) { this.XmlResolver = resolver; } } }", GetCA3077ConstructorCSharpResultAt(9, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Public Sub New(resolver As XmlResolver) Me.XmlResolver = resolver End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(7, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetInsecureResolverInCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { public TestClass() { this.XmlResolver = null; } public TestClass(XmlResolver resolver) { this.XmlResolver = resolver; } } }", GetCA3077ConstructorCSharpResultAt(14, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Public Sub New() Me.XmlResolver = Nothing End Sub Public Sub New(resolver As XmlResolver) Me.XmlResolver = resolver End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(11, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetSecureResolverForVariableInCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { public TestClass(XmlDocument doc) { doc.XmlResolver = null; } } }", GetCA3077ConstructorCSharpResultAt(9, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Public Sub New(doc As XmlDocument) doc.XmlResolver = Nothing End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(7, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetSecureResolverWithOutThisInCtorShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { public TestClass(XmlDocument doc) { doc.XmlResolver = null; XmlResolver = null; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Public Sub New(doc As XmlDocument) doc.XmlResolver = Nothing XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public void XmlDocumentDerivedTypeSetSecureResolverToAXmlDocumentFieldInCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { private XmlDocument doc = new XmlDocument(); public TestClass(XmlDocument doc) { this.doc.XmlResolver = null; } } }", GetCA3077ConstructorCSharpResultAt(10, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Private doc As New XmlDocument() Public Sub New(doc As XmlDocument) Me.doc.XmlResolver = Nothing End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(8, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetSecureResolverAtLeastOnceInCtorShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { public TestClass(bool flag) { if (flag) { XmlResolver = null; } else { XmlResolver = new XmlUrlResolver(); } } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Public Sub New(flag As Boolean) If flag Then XmlResolver = Nothing Else XmlResolver = New XmlUrlResolver() End If End Sub End Class End Namespace"); } [Fact] public void XmlDocumentDerivedTypeSetNullToHidingFieldInCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { XmlResolver XmlResolver; public TestClass() { this.XmlResolver = null; } } }", GetCA3077ConstructorCSharpResultAt(10, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Private XmlResolver As XmlResolver Public Sub New() Me.XmlResolver = Nothing End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(8, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetNullToBaseXmlResolverInCtorShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { XmlResolver XmlResolver; public TestClass() { base.XmlResolver = null; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Private XmlResolver As XmlResolver Public Sub New() MyBase.XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public void XmlDocumentDerivedTypeSetUrlResolverToBaseXmlResolverInCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { private XmlResolver XmlResolver; public TestClass() { base.XmlResolver = new XmlUrlResolver(); } } }", GetCA3077ConstructorCSharpResultAt(10, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Private XmlResolver As XmlResolver Public Sub New() MyBase.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(8, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetNullToHidingPropertyInCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { XmlResolver XmlResolver { set; get; } public TestClass() { this.XmlResolver = null; } } }", GetCA3077ConstructorCSharpResultAt(11, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Private Property XmlResolver() As XmlResolver Get Return m_XmlResolver End Get Set m_XmlResolver = Value End Set End Property Private m_XmlResolver As XmlResolver Public Sub New() Me.XmlResolver = Nothing End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(17, 20, "TestClass") ); } [Fact] public void XmlDocumentDerivedTypeSetNullToBaseWithHidingPropertyInCtorShouldNotGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { XmlResolver XmlResolver { set; get; } public TestClass() { base.XmlResolver = null; } } }" ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Private Property XmlResolver() As XmlResolver Get Return m_XmlResolver End Get Set m_XmlResolver = Value End Set End Property Private m_XmlResolver As XmlResolver Public Sub New() MyBase.XmlResolver = Nothing End Sub End Class End Namespace"); } [Fact] public void XmlDocumentDerivedTypeSetUrlResolverToBaseWithHidingPropertyInCtorShouldGenerateDiagnostic() { VerifyCSharp(@" using System; using System.Xml; namespace TestNamespace { class TestClass : XmlDocument { XmlResolver XmlResolver { set; get; } public TestClass() { base.XmlResolver = new XmlUrlResolver(); } } }", GetCA3077ConstructorCSharpResultAt(11, 16, "TestClass") ); VerifyBasic(@" Imports System.Xml Namespace TestNamespace Class TestClass Inherits XmlDocument Private Property XmlResolver() As XmlResolver Get Return m_XmlResolver End Get Set m_XmlResolver = Value End Set End Property Private m_XmlResolver As XmlResolver Public Sub New() MyBase.XmlResolver = New XmlUrlResolver() End Sub End Class End Namespace", GetCA3077ConstructorBasicResultAt(17, 20, "TestClass") ); } } }
//----------------------------------------------------------------------- // <copyright file="TcpStages.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Net; using System.Threading.Tasks; using Akka.Actor; using Akka.IO; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using Akka.Util; using Akka.Util.Internal; using StreamTcp = Akka.Streams.Dsl.Tcp; using Tcp = Akka.IO.Tcp; namespace Akka.Streams.Implementation.IO { /// <summary> /// INTERNAL API /// </summary> internal sealed class ConnectionSourceStage : GraphStageWithMaterializedValue<SourceShape<StreamTcp.IncomingConnection>, Task<StreamTcp.ServerBinding>> { #region internal classes private sealed class ConnectionSourceStageLogic : TimerGraphStageLogic, IOutHandler { private const string BindShutdownTimer = "BindTimer"; private readonly AtomicCounterLong _connectionFlowsAwaitingInitialization = new AtomicCounterLong(); private readonly ConnectionSourceStage _stage; private IActorRef _listener; private readonly TaskCompletionSource<StreamTcp.ServerBinding> _bindingPromise; private readonly TaskCompletionSource<NotUsed> _unbindPromise = new TaskCompletionSource<NotUsed>(); private bool _unbindStarted = false; public ConnectionSourceStageLogic(Shape shape, ConnectionSourceStage stage, TaskCompletionSource<StreamTcp.ServerBinding> bindingPromise) : base(shape) { _stage = stage; _bindingPromise = bindingPromise; SetHandler(_stage._out, this); } public void OnPull() { // Ignore if still binding _listener?.Tell(new Tcp.ResumeAccepting(1), StageActorRef); } public void OnDownstreamFinish() => TryUnbind(); private StreamTcp.IncomingConnection ConnectionFor(Tcp.Connected connected, IActorRef connection) { _connectionFlowsAwaitingInitialization.IncrementAndGet(); var tcpFlow = Flow.FromGraph(new IncomingConnectionStage(connection, connected.RemoteAddress, _stage._halfClose)) .Via(new Detacher<ByteString>()) // must read ahead for proper completions .MapMaterializedValue(unit => { _connectionFlowsAwaitingInitialization.DecrementAndGet(); return unit; }); // FIXME: Previous code was wrong, must add new tests var handler = tcpFlow; if (_stage._idleTimeout.HasValue) handler = tcpFlow.Join(TcpIdleTimeout.Create(_stage._idleTimeout.Value, connected.RemoteAddress)); return new StreamTcp.IncomingConnection(connected.LocalAddress, connected.RemoteAddress, handler); } private void TryUnbind() { if (_listener != null && !_unbindStarted) { _unbindStarted = true; SetKeepGoing(true); _listener.Tell(Tcp.Unbind.Instance, StageActorRef); } } private void UnbindCompleted() { StageActorRef.Unwatch(_listener); if (_connectionFlowsAwaitingInitialization.Current == 0) CompleteStage(); else ScheduleOnce(BindShutdownTimer, _stage._bindShutdownTimeout); } protected internal override void OnTimer(object timerKey) { if (Equals(BindShutdownTimer, timerKey)) CompleteStage(); // TODO need to manually shut down instead right? } public override void PreStart() { GetStageActorRef(Receive); _stage._tcpManager.Tell(new Tcp.Bind(StageActorRef, _stage._endpoint, _stage._backlog, _stage._options, pullMode: true), StageActorRef); } private void Receive(Tuple<IActorRef, object> args) { var sender = args.Item1; var msg = args.Item2; if (msg is Tcp.Bound) { var bound = (Tcp.Bound)msg; _listener = sender; StageActorRef.Watch(_listener); if (IsAvailable(_stage._out)) _listener.Tell(new Tcp.ResumeAccepting(1), StageActorRef); var thisStage = StageActorRef; _bindingPromise.TrySetResult(new StreamTcp.ServerBinding(bound.LocalAddress, () => { // Beware, sender must be explicit since stageActor.ref will be invalid to access after the stage stopped thisStage.Tell(Tcp.Unbind.Instance, thisStage); return _unbindPromise.Task; })); } else if (msg is Tcp.CommandFailed) { var ex = BindFailedException.Instance; _bindingPromise.TrySetException(ex); _unbindPromise.TrySetResult(NotUsed.Instance); FailStage(ex); } else if (msg is Tcp.Connected) { var connected = (Tcp.Connected)msg; Push(_stage._out, ConnectionFor(connected, sender)); } else if (msg is Tcp.Unbind) { if (!IsClosed(_stage._out) && !ReferenceEquals(_listener, null)) TryUnbind(); } else if (msg is Tcp.Unbound) { UnbindCompleted(); } else if (msg is Terminated) { if (_unbindStarted) UnbindCompleted(); else FailStage(new IllegalStateException("IO Listener actor terminated unexpectedly")); } } public override void PostStop() { _unbindPromise.TrySetResult(NotUsed.Instance); _bindingPromise.TrySetException( new NoSuchElementException("Binding was unbound before it was completely finished")); } } #endregion private readonly IActorRef _tcpManager; private readonly EndPoint _endpoint; private readonly int _backlog; private readonly IImmutableList<Inet.SocketOption> _options; private readonly bool _halfClose; private readonly TimeSpan? _idleTimeout; private readonly TimeSpan _bindShutdownTimeout; private readonly Outlet<StreamTcp.IncomingConnection> _out = new Outlet<StreamTcp.IncomingConnection>("IncomingConnections.out"); /// <summary> /// TBD /// </summary> /// <param name="tcpManager">TBD</param> /// <param name="endpoint">TBD</param> /// <param name="backlog">TBD</param> /// <param name="options">TBD</param> /// <param name="halfClose">TBD</param> /// <param name="idleTimeout">TBD</param> /// <param name="bindShutdownTimeout">TBD</param> public ConnectionSourceStage(IActorRef tcpManager, EndPoint endpoint, int backlog, IImmutableList<Inet.SocketOption> options, bool halfClose, TimeSpan? idleTimeout, TimeSpan bindShutdownTimeout) { _tcpManager = tcpManager; _endpoint = endpoint; _backlog = backlog; _options = options; _halfClose = halfClose; _idleTimeout = idleTimeout; _bindShutdownTimeout = bindShutdownTimeout; Shape = new SourceShape<StreamTcp.IncomingConnection>(_out); } /// <summary> /// TBD /// </summary> public override SourceShape<StreamTcp.IncomingConnection> Shape { get; } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = Attributes.CreateName("ConnectionSource"); // TODO: Timeout on bind /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<Task<StreamTcp.ServerBinding>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var bindingPromise = new TaskCompletionSource<StreamTcp.ServerBinding>(); var logic = new ConnectionSourceStageLogic(Shape, this, bindingPromise); return new LogicAndMaterializedValue<Task<StreamTcp.ServerBinding>>(logic, bindingPromise.Task); } } /// <summary> /// INTERNAL API /// </summary> public class IncomingConnectionStage : GraphStage<FlowShape<ByteString, ByteString>> { private readonly IActorRef _connection; private readonly EndPoint _remoteAddress; private readonly bool _halfClose; private readonly AtomicBoolean _hasBeenCreated = new AtomicBoolean(); private readonly Inlet<ByteString> _bytesIn = new Inlet<ByteString>("IncomingTCP.in"); private readonly Outlet<ByteString> _bytesOut = new Outlet<ByteString>("IncomingTCP.out"); /// <summary> /// TBD /// </summary> /// <param name="connection">TBD</param> /// <param name="remoteAddress">TBD</param> /// <param name="halfClose">TBD</param> public IncomingConnectionStage(IActorRef connection, EndPoint remoteAddress, bool halfClose) { _connection = connection; _remoteAddress = remoteAddress; _halfClose = halfClose; Shape = new FlowShape<ByteString, ByteString>(_bytesIn, _bytesOut); } /// <summary> /// TBD /// </summary> public override FlowShape<ByteString, ByteString> Shape { get; } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = Attributes.CreateName("IncomingConnection"); /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <exception cref="IllegalStateException">TBD</exception> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) { if (_hasBeenCreated.Value) throw new IllegalStateException("Cannot materialize an incoming connection Flow twice."); _hasBeenCreated.Value = true; return new TcpConnectionStage.TcpStreamLogic(Shape, new TcpConnectionStage.Inbound(_connection, _halfClose), _remoteAddress); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"TCP-from({_remoteAddress})"; } /// <summary> /// INTERNAL API /// </summary> internal static class TcpConnectionStage { private class WriteAck : Tcp.Event { public static readonly WriteAck Instance = new WriteAck(); private WriteAck() { } } /// <summary> /// TBD /// </summary> internal interface ITcpRole { /// <summary> /// TBD /// </summary> bool HalfClose { get; } } /// <summary> /// TBD /// </summary> internal struct Outbound : ITcpRole { /// <summary> /// TBD /// </summary> /// <param name="manager">TBD</param> /// <param name="connectCmd">TBD</param> /// <param name="localAddressPromise">TBD</param> /// <param name="halfClose">TBD</param> public Outbound(IActorRef manager, Tcp.Connect connectCmd, TaskCompletionSource<EndPoint> localAddressPromise, bool halfClose) { Manager = manager; ConnectCmd = connectCmd; LocalAddressPromise = localAddressPromise; HalfClose = halfClose; } /// <summary> /// TBD /// </summary> public readonly IActorRef Manager; /// <summary> /// TBD /// </summary> public readonly Tcp.Connect ConnectCmd; /// <summary> /// TBD /// </summary> public readonly TaskCompletionSource<EndPoint> LocalAddressPromise; /// <summary> /// TBD /// </summary> public bool HalfClose { get; } } /// <summary> /// TBD /// </summary> internal struct Inbound : ITcpRole { /// <summary> /// TBD /// </summary> /// <param name="connection">TBD</param> /// <param name="halfClose">TBD</param> public Inbound(IActorRef connection, bool halfClose) { Connection = connection; HalfClose = halfClose; } /// <summary> /// TBD /// </summary> public readonly IActorRef Connection; /// <summary> /// TBD /// </summary> public bool HalfClose { get; } } /// <summary> /// This is a *non-detached* design, i.e. this does not prefetch itself any of the inputs. It relies on downstream /// stages to provide the necessary prefetch on `bytesOut` and the framework to do the proper prefetch in the buffer /// backing `bytesIn`. If prefetch on `bytesOut` is required (i.e. user stages cannot be trusted) then it is better /// to attach an extra, fused buffer to the end of this flow. Keeping this stage non-detached makes it much simpler and /// easier to maintain and understand. /// </summary> internal sealed class TcpStreamLogic : GraphStageLogic { private readonly ITcpRole _role; private readonly EndPoint _remoteAddress; private readonly Inlet<ByteString> _bytesIn; private readonly Outlet<ByteString> _bytesOut; private IActorRef _connection; private readonly OutHandler _readHandler; public TcpStreamLogic(FlowShape<ByteString, ByteString> shape, ITcpRole role, EndPoint remoteAddress) : base(shape) { _role = role; _remoteAddress = remoteAddress; _bytesIn = shape.Inlet; _bytesOut = shape.Outlet; _readHandler = new LambdaOutHandler( onPull: () => _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef), onDownstreamFinish: () => { if (!IsClosed(_bytesIn)) _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef); else { _connection.Tell(Tcp.Abort.Instance, StageActorRef); CompleteStage(); } }); // No reading until role have been decided SetHandler(_bytesOut, onPull: DoNothing); SetHandler(_bytesIn, onPush: () => { var elem = Grab(_bytesIn); ReactiveStreamsCompliance.RequireNonNullElement(elem); _connection.Tell(Tcp.Write.Create(elem, WriteAck.Instance), StageActorRef); }, onUpstreamFinish: () => { // Reading has stopped before, either because of cancel, or PeerClosed, so just Close now // (or half-close is turned off) if (IsClosed(_bytesOut) || !_role.HalfClose) _connection.Tell(Tcp.Close.Instance, StageActorRef); // We still read, so we only close the write side else if (_connection != null) _connection.Tell(Tcp.ConfirmedClose.Instance, StageActorRef); else CompleteStage(); }, onUpstreamFailure: ex => { if (_connection != null) { if (Interpreter.Log.IsDebugEnabled) Interpreter.Log.Debug( $"Aborting tcp connection to {_remoteAddress} because of upstream failure: {ex.Message}\n{ex.StackTrace}"); _connection.Tell(Tcp.Abort.Instance, StageActorRef); } else FailStage(ex); }); } /// <summary> /// TBD /// </summary> public override void PreStart() { SetKeepGoing(true); if (_role is Inbound) { var inbound = (Inbound)_role; SetHandler(_bytesOut, _readHandler); _connection = inbound.Connection; GetStageActorRef(Connected).Watch(_connection); _connection.Tell(new Tcp.Register(StageActorRef, keepOpenOnPeerClosed: true, useResumeWriting: false), StageActorRef); Pull(_bytesIn); } else { var outbound = (Outbound)_role; GetStageActorRef(Connecting(outbound)).Watch(outbound.Manager); outbound.Manager.Tell(outbound.ConnectCmd, StageActorRef); } } /// <summary> /// TBD /// </summary> public override void PostStop() { if (_role is Outbound) { var outbound = (Outbound)_role; // Fail if has not been completed with an address earlier outbound.LocalAddressPromise.TrySetException(new StreamTcpException("Connection failed")); } } private StageActorRef.Receive Connecting(Outbound outbound) { return args => { var sender = args.Item1; var msg = args.Item2; if (msg is Terminated) FailStage(new StreamTcpException("The IO manager actor (TCP) has terminated. Stopping now.")); else if (msg is Tcp.CommandFailed) FailStage(new StreamTcpException($"Tcp command {((Tcp.CommandFailed)msg).Cmd} failed")); else if (msg is Tcp.Connected) { var connected = (Tcp.Connected)msg; ((Outbound)_role).LocalAddressPromise.TrySetResult(connected.LocalAddress); _connection = sender; SetHandler(_bytesOut, _readHandler); StageActorRef.Unwatch(outbound.Manager); StageActorRef.Become(Connected); StageActorRef.Watch(_connection); _connection.Tell(new Tcp.Register(StageActorRef, keepOpenOnPeerClosed: true, useResumeWriting: false), StageActorRef); if (IsAvailable(_bytesOut)) _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef); Pull(_bytesIn); } }; } private void Connected(Tuple<IActorRef, object> args) { var msg = args.Item2; if (msg is Terminated) FailStage(new StreamTcpException("The connection actor has terminated. Stopping now.")); else if (msg is Tcp.CommandFailed) FailStage(new StreamTcpException($"Tcp command {((Tcp.CommandFailed)msg).Cmd} failed")); else if (msg is Tcp.ErrorClosed) FailStage(new StreamTcpException($"The connection closed with error: {((Tcp.ErrorClosed)msg).Cause}")); else if (msg is Tcp.Aborted) FailStage(new StreamTcpException("The connection has been aborted")); else if (msg is Tcp.Closed) CompleteStage(); else if (msg is Tcp.ConfirmedClosed) CompleteStage(); else if (msg is Tcp.PeerClosed) Complete(_bytesOut); else if (msg is Tcp.Received) { var received = (Tcp.Received)msg; // Keep on reading even when closed. There is no "close-read-side" in TCP if (IsClosed(_bytesOut)) _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef); else Push(_bytesOut, received.Data); } else if (msg is WriteAck) { if (!IsClosed(_bytesIn)) Pull(_bytesIn); } } } } /// <summary> /// INTERNAL API /// </summary> internal sealed class OutgoingConnectionStage : GraphStageWithMaterializedValue<FlowShape<ByteString, ByteString>, Task<StreamTcp.OutgoingConnection>> { private readonly IActorRef _tcpManager; private readonly EndPoint _remoteAddress; private readonly EndPoint _localAddress; private readonly IImmutableList<Inet.SocketOption> _options; private readonly bool _halfClose; private readonly TimeSpan? _connectionTimeout; private readonly Inlet<ByteString> _bytesIn = new Inlet<ByteString>("IncomingTCP.in"); private readonly Outlet<ByteString> _bytesOut = new Outlet<ByteString>("IncomingTCP.out"); /// <summary> /// TBD /// </summary> /// <param name="tcpManager">TBD</param> /// <param name="remoteAddress">TBD</param> /// <param name="localAddress">TBD</param> /// <param name="options">TBD</param> /// <param name="halfClose">TBD</param> /// <param name="connectionTimeout">TBD</param> public OutgoingConnectionStage(IActorRef tcpManager, EndPoint remoteAddress, EndPoint localAddress = null, IImmutableList<Inet.SocketOption> options = null, bool halfClose = true, TimeSpan? connectionTimeout = null) { _tcpManager = tcpManager; _remoteAddress = remoteAddress; _localAddress = localAddress; _options = options; _halfClose = halfClose; _connectionTimeout = connectionTimeout; Shape = new FlowShape<ByteString, ByteString>(_bytesIn, _bytesOut); } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = Attributes.CreateName("OutgoingConnection"); /// <summary> /// TBD /// </summary> public override FlowShape<ByteString, ByteString> Shape { get; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<Task<StreamTcp.OutgoingConnection>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var localAddressPromise = new TaskCompletionSource<EndPoint>(); var outgoingConnectionPromise = new TaskCompletionSource<StreamTcp.OutgoingConnection>(); localAddressPromise.Task.ContinueWith(t => { if (t.IsCanceled) outgoingConnectionPromise.TrySetCanceled(); else if (t.IsFaulted) outgoingConnectionPromise.TrySetException(t.Exception); else outgoingConnectionPromise.TrySetResult(new StreamTcp.OutgoingConnection(_remoteAddress, t.Result)); }, TaskContinuationOptions.AttachedToParent); var logic = new TcpConnectionStage.TcpStreamLogic(Shape, new TcpConnectionStage.Outbound(_tcpManager, new Tcp.Connect(_remoteAddress, _localAddress, _options, _connectionTimeout, pullMode: true), localAddressPromise, _halfClose), _remoteAddress); return new LogicAndMaterializedValue<Task<StreamTcp.OutgoingConnection>>(logic, outgoingConnectionPromise.Task); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override string ToString() => $"TCP-to({_remoteAddress})"; } /// <summary> /// INTERNAL API /// </summary> internal static class TcpIdleTimeout { public static BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> Create(TimeSpan idleTimeout, EndPoint remoteAddress = null) { var connectionString = remoteAddress == null ? "" : $" on connection to [{remoteAddress}]"; var idleException = new TcpIdleTimeoutException( $"TCP idle-timeout encountered{connectionString}, no bytes passed in the last {idleTimeout}", idleTimeout); var toNetTimeout = BidiFlow.FromFlows( Flow.Create<ByteString>().SelectError(e => e is TimeoutException ? idleException : e), Flow.Create<ByteString>()); var fromNetTimeout = toNetTimeout.Reversed(); // now the bottom flow transforms the exception, the top one doesn't (since that one is "fromNet") return fromNetTimeout.Atop(BidiFlow.BidirectionalIdleTimeout<ByteString, ByteString>(idleTimeout)) .Atop(toNetTimeout); } } }