context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Partitions
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
/// <summary>
/// Base class for classes which represent a disk partitioning scheme.
/// </summary>
/// <remarks>After modifying the table, by creating or deleting a partition assume that any
/// previously stored partition indexes of higher value are no longer valid. Re-enumerate
/// the partitions to discover the next index-to-partition mapping.</remarks>
public abstract class PartitionTable
{
private static List<PartitionTableFactory> s_factories;
/// <summary>
/// Gets the GUID that uniquely identifies this disk, if supported (else returns <c>null</c>).
/// </summary>
public abstract Guid DiskGuid { get; }
/// <summary>
/// Gets the list of partitions that contain user data (i.e. non-system / empty).
/// </summary>
public abstract ReadOnlyCollection<PartitionInfo> Partitions { get; }
/// <summary>
/// Gets the number of User partitions on the disk.
/// </summary>
public int Count
{
get { return Partitions.Count; }
}
private static List<PartitionTableFactory> Factories
{
get
{
if (s_factories == null)
{
List<PartitionTableFactory> factories = new List<PartitionTableFactory>();
foreach (var type in typeof(VolumeManager).Assembly.GetTypes())
{
foreach (PartitionTableFactoryAttribute attr in Attribute.GetCustomAttributes(type, typeof(PartitionTableFactoryAttribute), false))
{
factories.Add((PartitionTableFactory)Activator.CreateInstance(type));
}
}
s_factories = factories;
}
return s_factories;
}
}
/// <summary>
/// Gets information about a particular User partition.
/// </summary>
/// <param name="index">The index of the partition</param>
/// <returns>Information about the partition</returns>
public PartitionInfo this[int index]
{
get { return Partitions[index]; }
}
/// <summary>
/// Determines if a disk is partitioned with a known partitioning scheme.
/// </summary>
/// <param name="content">The content of the disk to check</param>
/// <returns><c>true</c> if the disk is partitioned, else <c>false</c>.</returns>
public static bool IsPartitioned(Stream content)
{
foreach (var partTableFactory in Factories)
{
if (partTableFactory.DetectIsPartitioned(content))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if a disk is partitioned with a known partitioning scheme.
/// </summary>
/// <param name="disk">The disk to check</param>
/// <returns><c>true</c> if the disk is partitioned, else <c>false</c>.</returns>
public static bool IsPartitioned(VirtualDisk disk)
{
return IsPartitioned(disk.Content);
}
/// <summary>
/// Gets all of the partition tables found on a disk.
/// </summary>
/// <param name="disk">The disk to inspect</param>
/// <returns>It is rare for a disk to have multiple partition tables, but theoretically
/// possible.</returns>
public static IList<PartitionTable> GetPartitionTables(VirtualDisk disk)
{
List<PartitionTable> tables = new List<PartitionTable>();
foreach (var factory in Factories)
{
PartitionTable table = factory.DetectPartitionTable(disk);
if (table != null)
{
tables.Add(table);
}
}
return tables;
}
/// <summary>
/// Gets all of the partition tables found on a disk.
/// </summary>
/// <param name="contentStream">The content of the disk to inspect</param>
/// <returns>It is rare for a disk to have multiple partition tables, but theoretically
/// possible.</returns>
public static IList<PartitionTable> GetPartitionTables(Stream contentStream)
{
return GetPartitionTables(new Raw.Disk(contentStream, Ownership.None));
}
/// <summary>
/// Creates a new partition that encompasses the entire disk.
/// </summary>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <returns>The index of the partition</returns>
/// <remarks>The partition table must be empty before this method is called,
/// otherwise IOException is thrown.</remarks>
public abstract int Create(WellKnownPartitionType type, bool active);
/// <summary>
/// Creates a new partition with a target size.
/// </summary>
/// <param name="size">The target size (in bytes)</param>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <returns>The index of the new partition</returns>
public abstract int Create(long size, WellKnownPartitionType type, bool active);
/// <summary>
/// Creates a new aligned partition that encompasses the entire disk.
/// </summary>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <param name="alignment">The alignment (in byte)</param>
/// <returns>The index of the partition</returns>
/// <remarks>The partition table must be empty before this method is called,
/// otherwise IOException is thrown.</remarks>
/// <remarks>
/// Traditionally partitions were aligned to the physical structure of the underlying disk,
/// however with modern storage greater efficiency is acheived by aligning partitions on
/// large values that are a power of two.
/// </remarks>
public abstract int CreateAligned(WellKnownPartitionType type, bool active, int alignment);
/// <summary>
/// Creates a new aligned partition with a target size.
/// </summary>
/// <param name="size">The target size (in bytes)</param>
/// <param name="type">The partition type</param>
/// <param name="active">Whether the partition is active (bootable)</param>
/// <param name="alignment">The alignment (in byte)</param>
/// <returns>The index of the new partition</returns>
/// <remarks>
/// Traditionally partitions were aligned to the physical structure of the underlying disk,
/// however with modern storage greater efficiency is acheived by aligning partitions on
/// large values that are a power of two.
/// </remarks>
public abstract int CreateAligned(long size, WellKnownPartitionType type, bool active, int alignment);
/// <summary>
/// Deletes a partition at a given index.
/// </summary>
/// <param name="index">The index of the partition</param>
public abstract void Delete(int index);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.ProjectModel;
using JetBrains.Util;
using JetBrains.Util.Logging;
using ProjectExtensions = JetBrains.ReSharper.Plugins.Unity.Core.ProjectModel.ProjectExtensions;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.Integration.UnityEditorIntegration.EditorPlugin
{
[SolutionComponent]
public class UnityPluginDetector
{
private readonly ISolution mySolution;
private readonly ILogger myLogger;
private const string PluginCsFile = "Unity3DRider.cs";
public UnityPluginDetector(ISolution solution, ILogger logger)
{
mySolution = solution;
myLogger = logger;
}
[NotNull]
public InstallationInfo GetInstallationInfo(Version newVersion, VirtualFileSystemPath previousInstallationDir = null)
{
myLogger.Verbose("GetInstallationInfo.");
try
{
var assetsDir = mySolution.SolutionDirectory.CombineWithShortName(ProjectExtensions.AssetsFolder);
if (!assetsDir.IsAbsolute)
{
myLogger.Warn($"Computed assetsDir {assetsDir} is not absolute. Skipping installation.");
return InstallationInfo.DoNotInstall;
}
if (!assetsDir.ExistsDirectory)
{
myLogger.Info("No Assets directory in the same directory as solution. Skipping installation.");
return InstallationInfo.DoNotInstall;
}
var defaultDir = assetsDir
.CombineWithShortName("Plugins")
.CombineWithShortName("Editor")
.CombineWithShortName("JetBrains");
// default case: all is good, we have cached the installation dir
if (!previousInstallationDir.IsNullOrEmpty() &&
TryFindExistingPluginOnDisk(previousInstallationDir, newVersion, out var installationInfo))
{
return installationInfo;
}
// Check the default location
if (TryFindExistingPluginOnDisk(defaultDir, newVersion, out installationInfo))
return installationInfo;
// dll is there, but was not referenced by any project, for example - only Assembly-CSharp project is present
if (TryFindExistingPluginOnDiskInFolderRecursive(assetsDir, newVersion, out var installationInfo1))
{
return installationInfo1;
}
// not fresh install, but nothing in previously installed dir on in solution
if (!previousInstallationDir.IsNullOrEmpty())
{
myLogger.Info(
"Plugin not found in previous installation dir '{0}' or in solution. Falling back to default directory.",
previousInstallationDir);
}
else
{
myLogger.Info("Plugin not found in solution. Installing to default location");
}
return InstallationInfo.FreshInstall(defaultDir);
}
catch (Exception e)
{
myLogger.LogExceptionSilently(e);
return InstallationInfo.DoNotInstall;
}
}
private bool TryFindExistingPluginOnDiskInFolderRecursive(VirtualFileSystemPath directory, Version newVersion, [NotNull] out InstallationInfo result)
{
myLogger.Verbose("Looking for plugin on disk: '{0}'", directory);
var pluginFiles = directory
.GetChildFiles("*.dll", PathSearchFlags.RecurseIntoSubdirectories)
.Where(f => f.Name == PluginPathsProvider.BasicPluginDllFile)
.ToList();
if (pluginFiles.Count == 0)
{
result = InstallationInfo.DoNotInstall;
return false;
}
result = GetInstallationInfoFromFoundInstallation(pluginFiles, newVersion);
return true;
}
private bool TryFindExistingPluginOnDisk(VirtualFileSystemPath directory, Version newVersion, [NotNull] out InstallationInfo result)
{
myLogger.Verbose("Looking for plugin on disk: '{0}'", directory);
var oldPluginFiles = directory
.GetChildFiles("*.cs")
.Where(f => PluginCsFile == f.Name)
.ToList();
var pluginFiles = directory
.GetChildFiles("*.dll")
.Where(f => f.Name == PluginPathsProvider.BasicPluginDllFile)
.ToList();
pluginFiles.AddRange(oldPluginFiles);
if (pluginFiles.Count == 0)
{
result = InstallationInfo.DoNotInstall;
return false;
}
result = GetInstallationInfoFromFoundInstallation(pluginFiles, newVersion);
return true;
}
[NotNull]
private InstallationInfo GetInstallationInfoFromFoundInstallation(List<VirtualFileSystemPath> pluginFiles, Version newVersion)
{
var parentDirs = pluginFiles.Select(f => f.Directory).Distinct().ToList();
if (parentDirs.Count > 1)
{
myLogger.Warn("Plugin files detected in more than one directory.");
return InstallationInfo.FoundProblemWithExistingPlugins(pluginFiles);
}
if (parentDirs.Count == 0)
{
myLogger.Warn("Plugin files do not have parent directory (?).");
return InstallationInfo.FoundProblemWithExistingPlugins(pluginFiles);
}
var pluginDir = parentDirs[0];
if (pluginFiles.Count == 1 && pluginFiles[0].Name == PluginPathsProvider.BasicPluginDllFile && pluginFiles[0].ExistsFile)
{
try
{
var existingVersion = new Version(FileVersionInfo.GetVersionInfo(pluginFiles[0].FullPath).FileVersion);
// Always update to a debug version, even if the versions match
if (IsDebugVersion(newVersion))
return InstallationInfo.ForceUpdateToDebugVersion(pluginDir, parentDirs, existingVersion);
// If the versions are the same, don't update. Note that this means we will also DOWNGRADE if we
// load the project in an older version of Rider. This is a good thing - always install the version
// of the plugin that the version of Rider is expecting. "Update", not "upgrade"
if (newVersion == existingVersion)
{
myLogger.Verbose($"Plugin v{existingVersion} already installed.");
return InstallationInfo.UpToDate(pluginDir, pluginFiles, existingVersion);
}
return InstallationInfo.ShouldUpdate(pluginDir, pluginFiles, existingVersion);
}
catch (Exception)
{
// file may be in Solution-csproj, but doesn't exist on disk
return InstallationInfo.ForceUpdate(pluginDir, pluginFiles);
}
}
// update from Unity3dRider.cs to dll or both old and new plugins together
return InstallationInfo.ForceUpdate(pluginDir, pluginFiles);
}
private static bool IsDebugVersion(Version newVersion)
{
// Revision is set by the CI, normally. We'll see 9998 if the project is built from the IDE and 9999 if built
// from the gradle scripts (which means 9999 is a more accurate build)
return newVersion.Revision == 9999 || newVersion.Revision == 9998;
}
public class InstallationInfo
{
// Make sure we have four components. The default constructor gives us only major.minor (0.0) and that will
// fail if we try to compare against a full version (0.0.0.0), which we might get from the file version
private static readonly Version ourZeroVersion = new Version(0, 0, 0, 0);
public static readonly InstallationInfo DoNotInstall = new InstallationInfo(InstallReason.DoNotInstall,
VirtualFileSystemPath.GetEmptyPathFor(InteractionContext.SolutionContext), EmptyArray<VirtualFileSystemPath>.Instance, ourZeroVersion);
public readonly InstallReason InstallReason;
public bool ShouldInstallPlugin => !(InstallReason == InstallReason.DoNotInstall || InstallReason == InstallReason.UpToDate);
[NotNull]
public readonly VirtualFileSystemPath PluginDirectory;
[NotNull]
public readonly ICollection<VirtualFileSystemPath> ExistingFiles;
[NotNull]
public readonly Version ExistingVersion;
private InstallationInfo(InstallReason installReason, [NotNull] VirtualFileSystemPath pluginDirectory,
[NotNull] ICollection<VirtualFileSystemPath> existingFiles, [NotNull] Version existingVersion)
{
var logger = Logger.GetLogger<InstallationInfo>();
if (!pluginDirectory.IsAbsolute && ShouldInstallPlugin)
logger.Error($"pluginDirectory ${pluginDirectory} Is Not Absolute ${installReason}, ${existingVersion}, ${existingFiles.Count}");
else
logger.Info($"pluginDirectory ${pluginDirectory} ${installReason}, ${existingVersion}, ${existingFiles.Count}");
InstallReason = installReason;
PluginDirectory = pluginDirectory;
ExistingFiles = existingFiles;
ExistingVersion = existingVersion;
}
public static InstallationInfo FreshInstall(VirtualFileSystemPath installLocation)
{
return new InstallationInfo(InstallReason.FreshInstall, installLocation, EmptyArray<VirtualFileSystemPath>.Instance, ourZeroVersion);
}
public static InstallationInfo UpToDate(VirtualFileSystemPath installLocation,
ICollection<VirtualFileSystemPath> existingPluginFiles, Version existingVersion)
{
return new InstallationInfo(InstallReason.UpToDate, installLocation, existingPluginFiles, existingVersion);
}
public static InstallationInfo ShouldUpdate(VirtualFileSystemPath installLocation,
ICollection<VirtualFileSystemPath> existingPluginFiles, Version existingVersion)
{
return new InstallationInfo(InstallReason.Update, installLocation, existingPluginFiles, existingVersion);
}
public static InstallationInfo ForceUpdate(VirtualFileSystemPath installLocation,
ICollection<VirtualFileSystemPath> existingPluginFiles)
{
return new InstallationInfo(InstallReason.Update, installLocation, existingPluginFiles, ourZeroVersion);
}
public static InstallationInfo ForceUpdateToDebugVersion(VirtualFileSystemPath installLocation,
ICollection<VirtualFileSystemPath> existingPluginFiles, Version existingVersion)
{
return new InstallationInfo(InstallReason.ForceUpdateForDebug, installLocation, existingPluginFiles, existingVersion);
}
public static InstallationInfo FoundProblemWithExistingPlugins(
ICollection<VirtualFileSystemPath> existingPluginFiles)
{
// We've found a weird situation with existing plugins (found in multiple directories, etc.) don't install
return new InstallationInfo(InstallReason.DoNotInstall, VirtualFileSystemPath.GetEmptyPathFor(InteractionContext.SolutionContext), existingPluginFiles, ourZeroVersion);
}
}
public enum InstallReason
{
DoNotInstall,
UpToDate,
FreshInstall,
Update,
ForceUpdateForDebug
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.ComponentModel.DataAnnotations.Tests
{
public class ValidatorTests
{
public static readonly ValidationContext s_estValidationContext = new ValidationContext(new object());
#region TryValidateObject
[Fact]
public static void TryValidateObjectThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null));
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null, validateAllProperties: false));
}
[Fact]
public static void TryValidateObjectThrowsIf_instance_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null));
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null, validateAllProperties: false));
}
// TryValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance
[Fact]
public static void TestTryValidateObjectThrowsIfInstanceNotMatch()
{
Assert.Throws<ArgumentException>(
() => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null));
Assert.Throws<ArgumentException>(
() => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null, validateAllProperties: true));
}
[Fact]
public static void TryValidateObject_returns_true_if_no_errors()
{
var objectToBeValidated = "ToBeValidated";
var validationContext = new ValidationContext(objectToBeValidated);
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null));
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null, validateAllProperties: true));
}
[Fact]
public static void TryValidateObject_returns_false_if_errors()
{
var objectToBeValidated = new ToBeValidated()
{
PropertyToBeTested = "Invalid Value",
PropertyWithRequiredAttribute = "Valid Value"
};
var validationContext = new ValidationContext(objectToBeValidated);
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
// TryValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors()
[Fact]
public static void TestTryValidateObjectSuccessEvenWithOtherErrors()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, false));
var validationResults = new List<ValidationResult>();
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, false));
Assert.Equal(0, validationResults.Count);
}
[Fact]
public static void TryValidateObject_returns_false_if_validateAllProperties_is_true_and_Required_test_fails()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(1, validationResults.Count);
// cannot check error message - not defined on ret builds
}
[Fact]
public static void TryValidateObject_returns_true_if_validateAllProperties_is_true_and_all_attributes_are_valid()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.True(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(0, validationResults.Count);
}
[Fact]
public static void TryValidateObject_returns_false_if_all_properties_are_valid_but_class_is_invalid()
{
var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, null, true));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName, validationResults[0].ErrorMessage);
}
#endregion TryValidateObject
#region ValidateObject
[Fact]
public static void ValidateObjectThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(new object(), validationContext: null));
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(new object(), validationContext: null, validateAllProperties: false));
}
[Fact]
public static void ValidateObjectThrowsIf_instance_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(null, s_estValidationContext));
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateObject(null, s_estValidationContext, false));
}
[Fact]
public static void ValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance()
{
Assert.Throws<ArgumentException>(
() => Validator.ValidateObject(new object(), s_estValidationContext));
Assert.Throws<ArgumentException>(
() => Validator.ValidateObject(new object(), s_estValidationContext, true));
}
[Fact]
public static void ValidateObject_succeeds_if_no_errors()
{
var objectToBeValidated = "ToBeValidated";
var validationContext = new ValidationContext(objectToBeValidated);
Validator.ValidateObject(objectToBeValidated, validationContext);
Validator.ValidateObject(objectToBeValidated, validationContext, true);
}
[Fact]
public static void ValidateObject_throws_ValidationException_if_errors()
{
var objectToBeValidated = new ToBeValidated()
{
PropertyToBeTested = "Invalid Value",
PropertyWithRequiredAttribute = "Valid Value"
};
var validationContext = new ValidationContext(objectToBeValidated);
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateObject(objectToBeValidated, validationContext, true));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
// ValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors
[Fact]
public static void TestValidateObjectNotThrowIfvalidateAllPropertiesFalse()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Validator.ValidateObject(objectToBeValidated, validationContext, false);
}
// ValidateObject_throws_ValidationException_if_validateAllProperties_is_true_and_Required_test_fails
[Fact]
public static void TestValidateObjectThrowsIfRequiredTestFails()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null };
var validationContext = new ValidationContext(objectToBeValidated);
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateObject(objectToBeValidated, validationContext, true));
Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
// cannot check error message - not defined on ret builds
Assert.Null(exception.Value);
}
[Fact]
public static void ValidateObject_succeeds_if_validateAllProperties_is_true_and_all_attributes_are_valid()
{
var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
Validator.ValidateObject(objectToBeValidated, validationContext, true);
}
[Fact]
public static void ValidateObject_throws_ValidationException_if_all_properties_are_valid_but_class_is_invalid()
{
var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" };
var validationContext = new ValidationContext(objectToBeValidated);
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateObject(objectToBeValidated, validationContext, true));
Assert.IsType<ValidClassAttribute>(exception.ValidationAttribute);
Assert.Equal(
"ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName,
exception.ValidationResult.ErrorMessage);
Assert.Equal(objectToBeValidated, exception.Value);
}
#endregion ValidateObject
#region TryValidateProperty
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(new object(), validationContext: null, validationResults: null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_value_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(null, s_estValidationContext, validationResults: null));
}
// TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty()
[Fact]
public static void TestTryValidatePropertyThrowsIfNullOrEmptyValidationContextMemberName()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(null, validationContext, null));
validationContext.MemberName = string.Empty;
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateProperty(null, validationContext, null));
}
// TryValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object()
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NonExist";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(null, validationContext, null));
}
// TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public()
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "InternalProperty";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(null, validationContext, null));
validationContext.MemberName = "ProtectedProperty";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(null, validationContext, null));
validationContext.MemberName = "PrivateProperty";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(null, validationContext, null));
}
// TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer()
[Fact]
public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "Item";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(null, validationContext, validationResults: null));
}
// TryValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property()
[Fact]
public static void TryValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(123, validationContext, validationResults: null));
}
[Fact]
public static void TryValidatePropertyThrowsIf_null_passed_to_non_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
// cannot assign null to a non-value-type property
validationContext.MemberName = "EnumProperty";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(null, validationContext, validationResults: null));
// cannot assign null to a non-nullable property
validationContext.MemberName = "NonNullableProperty";
Assert.Throws<ArgumentException>(
() => Validator.TryValidateProperty(null, validationContext, validationResults: null));
}
[Fact]
public static void TryValidateProperty_returns_true_if_null_passed_to_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NullableProperty";
Assert.True(Validator.TryValidateProperty(null, validationContext, validationResults: null));
}
[Fact]
public static void TryValidateProperty_returns_true_if_no_attributes_to_validate()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Assert.True(
Validator.TryValidateProperty("Any Value", validationContext, validationResults: null));
}
[Fact]
public static void TryValidateProperty_returns_false_if_errors()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
Assert.False(
Validator.TryValidateProperty("Invalid Value", validationContext, null));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateProperty("Invalid Value", validationContext, validationResults));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
[Fact]
public static void TryValidateProperty_returns_false_if_Required_attribute_test_fails()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
Assert.False(
Validator.TryValidateProperty(null, validationContext, null));
var validationResults = new List<ValidationResult>();
Assert.False(
Validator.TryValidateProperty(null, validationContext, validationResults));
Assert.Equal(1, validationResults.Count);
// cannot check error message - not defined on ret builds
}
[Fact]
public static void TryValidateProperty_returns_true_if_all_attributes_are_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
Assert.True(
Validator.TryValidateProperty("Valid Value", validationContext, null));
var validationResults = new List<ValidationResult>();
Assert.True(
Validator.TryValidateProperty("Valid Value", validationContext, validationResults));
Assert.Equal(0, validationResults.Count);
}
#endregion TryValidateProperty
#region ValidateProperty
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(new object(), validationContext: null));
}
[Fact]
public static void ValidatePropertyThrowsIf_value_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(null, s_estValidationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(null, validationContext));
validationContext.MemberName = string.Empty;
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NonExist";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "InternalProperty";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(null, validationContext));
validationContext.MemberName = "ProtectedProperty";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(null, validationContext));
validationContext.MemberName = "PrivateProperty";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "Item";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(123, validationContext));
}
[Fact]
public static void ValidatePropertyThrowsIf_null_passed_to_non_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
// cannot assign null to a non-value-type property
validationContext.MemberName = "EnumProperty";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(null, validationContext));
// cannot assign null to a non-nullable property
validationContext.MemberName = "NonNullableProperty";
Assert.Throws<ArgumentException>(
() => Validator.ValidateProperty(null, validationContext));
}
[Fact]
public static void ValidateProperty_succeeds_if_null_passed_to_nullable_property()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NullableProperty";
Validator.ValidateProperty(null, validationContext);
}
[Fact]
public static void ValidateProperty_succeeds_if_no_attributes_to_validate()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Validator.ValidateProperty("Any Value", validationContext);
}
[Fact]
public static void ValidateProperty_throws_ValidationException_if_errors()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateProperty("Invalid Value", validationContext));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
[Fact]
public static void ValidateProperty_throws_ValidationException_if_Required_attribute_test_fails()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateProperty(null, validationContext));
Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
// cannot check error message - not defined on ret builds
Assert.Null(exception.Value);
}
[Fact]
public static void ValidateProperty_succeeds_if_all_attributes_are_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
Validator.ValidateProperty("Valid Value", validationContext);
}
#endregion ValidateProperty
#region TryValidateValue
[Fact]
public static void TryValidateValueThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateValue(new object(),
validationContext: null, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
}
[Fact]
public static void TryValidateValueThrowsIf_ValidationAttributeEnumerable_is_null()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.TryValidateValue(new object(), validationContext, validationResults: null, validationAttributes: null));
}
[Fact]
public static void TryValidateValue_returns_true_if_no_attributes_to_validate_regardless_of_value()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Assert.True(Validator.TryValidateValue(null, validationContext,
validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
Assert.True(Validator.TryValidateValue(new object(), validationContext,
validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
}
[Fact]
public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_null()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Assert.False(Validator.TryValidateValue(null, validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.False(Validator.TryValidateValue(null, validationContext, validationResults, attributesToValidate));
Assert.Equal(1, validationResults.Count);
// cannot check error message - not defined on ret builds
}
[Fact]
public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_invalid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
[Fact]
public static void TryValidateValue_returns_true_if_Property_has_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(0, validationResults.Count);
}
[Fact]
public static void TryValidateValue_returns_false_if_Property_has_no_RequiredAttribute_and_value_is_invalid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(1, validationResults.Count);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage);
}
[Fact]
public static void TryValidateValue_returns_true_if_Property_has_no_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate));
var validationResults = new List<ValidationResult>();
Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate));
Assert.Equal(0, validationResults.Count);
}
#endregion TryValidateValue
#region ValidateValue
[Fact]
public static void ValidateValueThrowsIf_ValidationContext_is_null()
{
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateValue(new object(),
validationContext: null, validationAttributes: Enumerable.Empty<ValidationAttribute>()));
}
[Fact]
public static void ValidateValueThrowsIf_ValidationAttributeEnumerable_is_null()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = null;
Assert.Throws<ArgumentNullException>(
() => Validator.ValidateValue(new object(), validationContext, validationAttributes: null));
}
[Fact]
public static void ValidateValue_succeeds_if_no_attributes_to_validate_regardless_of_value()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "NoAttributesProperty";
Validator.ValidateValue(null, validationContext, Enumerable.Empty<ValidationAttribute>());
Validator.ValidateValue(new object(), validationContext, Enumerable.Empty<ValidationAttribute>());
}
// ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_null()
[Fact]
public static void TestValidateValueThrowsIfNullRequiredAttribute()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateValue(null, validationContext, attributesToValidate));
Assert.IsType<RequiredAttribute>(exception.ValidationAttribute);
// cannot check error message - not defined on ret builds
Assert.Null(exception.Value);
}
// ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_invalid()
[Fact]
public static void TestValidateValueThrowsIfRequiredAttributeInvalid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
[Fact]
public static void ValidateValue_succeeds_if_Property_has_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() };
Validator.ValidateValue("Valid Value", validationContext, attributesToValidate);
}
// ValidateValue_throws_ValidationException_if_Property_has_no_RequiredAttribute_and_value_is_invalid()
[Fact]
public static void TestValidateValueThrowsIfNoRequiredAttribute()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyWithRequiredAttribute";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
var exception = Assert.Throws<ValidationException>(
() => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate));
Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute);
Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage);
Assert.Equal("Invalid Value", exception.Value);
}
[Fact]
public static void ValidateValue_succeeds_if_Property_has_no_RequiredAttribute_and_value_is_valid()
{
var validationContext = new ValidationContext(new ToBeValidated());
validationContext.MemberName = "PropertyToBeTested";
var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() };
Validator.ValidateValue("Valid Value", validationContext, attributesToValidate);
}
#endregion ValidateValue
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidValueStringPropertyAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext _)
{
if (value == null) { return ValidationResult.Success; }
var valueAsString = value as string;
if ("Valid Value".Equals(valueAsString)) { return ValidationResult.Success; }
return new ValidationResult("ValidValueStringPropertyAttribute.IsValid failed for value " + value);
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ValidClassAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext _)
{
if (value == null) { return ValidationResult.Success; }
if (value.GetType().Name.ToLowerInvariant().Contains("invalid"))
{
return new ValidationResult("ValidClassAttribute.IsValid failed for class of type " + value.GetType().FullName);
}
return ValidationResult.Success;
}
}
[ValidClass]
public class ToBeValidated
{
[ValidValueStringProperty]
public string PropertyToBeTested { get; set; }
public string NoAttributesProperty { get; set; }
[Required]
[ValidValueStringProperty]
public string PropertyWithRequiredAttribute { get; set; }
internal string InternalProperty { get; set; }
protected string ProtectedProperty { get; set; }
private string PrivateProperty { get; set; }
public string this[int index]
{
get { return null; }
set { }
}
public TestEnum EnumProperty { get; set; }
public int NonNullableProperty { get; set; }
public int? NullableProperty { get; set; }
}
public enum TestEnum
{
A = 0
}
[ValidClass]
public class InvalidToBeValidated
{
[ValidValueStringProperty]
public string PropertyToBeTested { get; set; }
public string NoAttributesProperty { get; set; }
[Required]
[ValidValueStringProperty]
public string PropertyWithRequiredAttribute { get; set; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace RecurrenceGenerator
{
public enum RecurrenceType { NotSet = -1, Daily = 0, Weekly, Monthly, Yearly };
public class RecurrenceInfo
{
EndDateType endDateType = EndDateType.NotDefined;
int numberOfOccurrences;
int adjustmentValue;
string seriesInfo;
DateTime startDate;
DateTime? endDate = null;
RecurrenceType recurrenceType = RecurrenceType.NotSet;
#region Internal Daily-Specific
DailyRegenType dailyRegenType;
int dailyRegenEveryXDays;
internal void SetDailyRegenEveryXDays(int dailyRegenEveryXDays)
{
this.dailyRegenEveryXDays = dailyRegenEveryXDays;
}
internal void SetDailyRegenType(DailyRegenType dailyRegenType)
{
this.dailyRegenType = dailyRegenType;
}
#endregion //Internal Daily-Specific
#region Public Daily-Specific Fields
public int DailyRegenEveryXDays
{
get
{
return dailyRegenEveryXDays;
}
}
public DailyRegenType DailyRegenType
{
get
{
return dailyRegenType;
}
}
#endregion //Public Daily-Specific Fields
#region Internal Weekly-Specific
SelectedDayOfWeekValues selectedDayOfWeekValues;
WeeklyRegenType weeklyRegenType;
int regenEveryXWeeks;
internal void SetRegenEveryXWeeks(int regenEveryXWeeks)
{
this.regenEveryXWeeks = regenEveryXWeeks;
}
internal void SetWeeklyRegenType(WeeklyRegenType weeklyRegenType)
{
this.weeklyRegenType = weeklyRegenType;
}
internal void SetSelectedDayOfWeekValues(SelectedDayOfWeekValues selectedDayOfWeekValues)
{
this.selectedDayOfWeekValues = selectedDayOfWeekValues;
}
#endregion //Internal Weekly-Specific
#region Public Weekly-Specific
public int WeeklyRegenEveryXWeeks
{
get
{
return regenEveryXWeeks;
}
}
public WeeklyRegenType WeeklyRegenType
{
get
{
return weeklyRegenType;
}
}
public SelectedDayOfWeekValues WeeklySelectedDays
{
get
{
return selectedDayOfWeekValues;
}
}
#endregion //Public Weekly-Specific
#region Internal Monthly-Specific
MonthlyRegenType monthlyRegenType;
MonthlySpecificDatePartOne monthlySpecificDatePartOne;
MonthlySpecificDatePartTwo monthlySpecificDatePartTwo;
int monthlyRegenerateOnSpecificDateDayValue;
int regenEveryXMonths;
internal void SetRegenEveryXMonths(int regenEveryXMonths)
{
this.regenEveryXMonths = regenEveryXMonths;
}
internal void SetMonthlyRegenerateOnSpecificDateDayValue(int monthlyRegenerateOnSpecificDateDayValue)
{
this.monthlyRegenerateOnSpecificDateDayValue = monthlyRegenerateOnSpecificDateDayValue;
}
internal void SetMonthlySpecificDatePartTwo(MonthlySpecificDatePartTwo monthlySpecificDatePartTwo)
{
this.monthlySpecificDatePartTwo = monthlySpecificDatePartTwo;
}
internal void SetMonthlySpecificDatePartOne(MonthlySpecificDatePartOne monthlySpecificDatePartOne)
{
this.monthlySpecificDatePartOne = monthlySpecificDatePartOne;
}
internal void SetMonthlyRegenType(MonthlyRegenType monthlyRegenType)
{
this.monthlyRegenType = monthlyRegenType;
}
#endregion //Internal Monthly-Specific
#region Public Monthly-Specific Fields
/// <summary>
/// What is the interval to generate dates. This is used to skip months in the cycle.
/// </summary>
/// <value>
/// <para>
/// Integer of the interval value. 1 = every month, 2 = every other month, etc.
/// </para>
/// </value>
/// <remarks>
///
/// </remarks>
public int MonthlyRegenEveryXMonths
{
get
{
return regenEveryXMonths;
}
}
/// <summary>
/// Day of month to regenerate when RegenType = specific day of month.
/// </summary>
/// <value>
/// <para>
/// Integer of the day of the month.
/// </para>
/// </value>
/// <remarks>
///
/// </remarks>
public int MonthlyRegenerateOnSpecificDateDayValue
{
get
{
return monthlyRegenerateOnSpecificDateDayValue;
}
}
/// <summary>
/// What is the second part to the Custom date such as which weekday, weekend day, etc.
/// </summary>
/// <value>
/// <para>
///
/// </para>
/// </value>
/// <remarks>
///
/// </remarks>
public MonthlySpecificDatePartTwo MonthlySpecificDatePartTwo
{
get
{
return monthlySpecificDatePartTwo;
}
}
/// <summary>
/// What is the first part to the Custom date such as First, Last.
/// </summary>
/// <value>
/// <para>
///
/// </para>
/// </value>
/// <remarks>
///
/// </remarks>
public MonthlySpecificDatePartOne MonthlySpecificDatePartOne
{
get
{
return monthlySpecificDatePartOne;
}
}
/// <summary>
/// What is the regeneration type such as Specific day of month, custom date, etc.
/// </summary>
/// <value>
/// <para>
///
/// </para>
/// </value>
/// <remarks>
///
/// </remarks>
public MonthlyRegenType MonthlyRegenType
{
get
{
return monthlyRegenType;
}
}
#endregion //Public Monthly-Specific Fields
#region Public Yearly-Specific Fields
public YearlySpecificDatePartOne YearlySpecificDatePartOne
{
get
{
return yearlySpecificDatePartOne;
}
}
public YearlySpecificDatePartTwo YearlySpecificDatePartTwo
{
get
{
return yearlySpecificDatePartTwo;
}
}
public YearlySpecificDatePartThree YearlySpecificDatePartThree
{
get
{
return yearlySpecificDatePartThree;
}
}
public YearlyRegenType YearlyRegenType
{
get
{
return yearlyRegenType;
}
}
public int SpecificDateDayValue
{
get
{
return specificDateDayValue;
}
}
public int SpecificDateMonthValue
{
get
{
return specificDateMonthValue;
}
}
#endregion //Yearly Public Fields
#region Internal Yearly-Specific
int specificDateDayValue;
int specificDateMonthValue;
YearlyRegenType yearlyRegenType = YearlyRegenType.NotSet;
YearlySpecificDatePartOne yearlySpecificDatePartOne = YearlySpecificDatePartOne.NotSet;
YearlySpecificDatePartTwo yearlySpecificDatePartTwo = YearlySpecificDatePartTwo.NotSet;
YearlySpecificDatePartThree yearlySpecificDatePartThree = YearlySpecificDatePartThree.NotSet;
internal void SetSpecificDateDayValue(int specificDateDayValue)
{
this.specificDateDayValue = specificDateDayValue;
}
internal void SetSpecificDateMonthValue(int specificDateMonthValue)
{
this.specificDateMonthValue = specificDateMonthValue;
}
internal void SetYearlyRegenType(YearlyRegenType yearlyRegenType)
{
this.yearlyRegenType = yearlyRegenType;
}
internal void SetYearlySpecificDatePartOne(YearlySpecificDatePartOne yearlySpecificDatePartOne)
{
this.yearlySpecificDatePartOne = yearlySpecificDatePartOne;
}
internal void SetYearlySpecificDatePartTwo(YearlySpecificDatePartTwo yearlySpecificDatePartTwo)
{
this.yearlySpecificDatePartTwo = yearlySpecificDatePartTwo;
}
internal void SetYearlySpecificDatePartThree(YearlySpecificDatePartThree yearlySpecificDatePartThree)
{
this.yearlySpecificDatePartThree = yearlySpecificDatePartThree;
}
#endregion //Internal Yearly-Specific
#region Internal Global Setters
internal void SetSeriesInfo(string seriesInfo)
{
this.seriesInfo = seriesInfo;
}
internal void SetAdjustmentValue(int adjustmentValue)
{
this.adjustmentValue = adjustmentValue;
}
internal void SetEndDateType(EndDateType endDateType)
{
this.endDateType = endDateType;
}
internal void SetNumberOfOccurrences(int numberOfOccurrences)
{
this.numberOfOccurrences = numberOfOccurrences;
}
internal void SetStartDate(DateTime startDate)
{
this.startDate = startDate;
}
internal void SetEndDate(DateTime? endDate)
{
this.endDate = endDate;
}
internal void SetRecurrenceType(RecurrenceType recurrenceType)
{
this.recurrenceType = recurrenceType;
}
#endregion //Internal Gloal Setters
#region Constructors
internal RecurrenceInfo()
{
}
#endregion //Constructors
#region Public Global Fields
public string SeriesInfo
{
get
{
return seriesInfo;
}
}
public int AdjustmentValue
{
get
{
return adjustmentValue;
}
}
public RecurrenceType RecurrenceType
{
get
{
return recurrenceType;
}
}
public bool HasEndDate
{
get
{
return endDate.HasValue;
}
}
public DateTime? EndDate
{
get
{
if (endDate.HasValue)
return endDate.Value;
return null;
}
}
public DateTime StartDate
{
get
{
return startDate;
}
}
public int NumberOfOccurrences
{
get
{
return numberOfOccurrences;
}
}
public EndDateType EndDateType
{
get
{
return endDateType;
}
}
#endregion //Public Global Fields
}
}
| |
// 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 BinaryNullableSubtractTests
{
#region Test methods
[Fact]
public static void CheckNullableByteSubtractTest()
{
byte?[] array = { 0, 1, byte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableByteSubtract(array[i], array[j]);
}
}
}
[Fact]
public static void CheckNullableSByteSubtractTest()
{
sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSByteSubtract(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortSubtractTest(bool useInterpreter)
{
ushort?[] array = { 0, 1, ushort.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortSubtract(array[i], array[j], useInterpreter);
VerifyNullableUShortSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortSubtractTest(bool useInterpreter)
{
short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortSubtract(array[i], array[j], useInterpreter);
VerifyNullableShortSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntSubtractTest(bool useInterpreter)
{
uint?[] array = { 0, 1, uint.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntSubtract(array[i], array[j], useInterpreter);
VerifyNullableUIntSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntSubtractTest(bool useInterpreter)
{
int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntSubtract(array[i], array[j], useInterpreter);
VerifyNullableIntSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongSubtractTest(bool useInterpreter)
{
ulong?[] array = { 0, 1, ulong.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongSubtract(array[i], array[j], useInterpreter);
VerifyNullableULongSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongSubtractTest(bool useInterpreter)
{
long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongSubtract(array[i], array[j], useInterpreter);
VerifyNullableLongSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatSubtractTest(bool useInterpreter)
{
float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatSubtract(array[i], array[j], useInterpreter);
VerifyNullableFloatSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoubleSubtractTest(bool useInterpreter)
{
double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoubleSubtract(array[i], array[j], useInterpreter);
VerifyNullableDoubleSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalSubtractTest(bool useInterpreter)
{
decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalSubtract(array[i], array[j], useInterpreter);
VerifyNullableDecimalSubtractOvf(array[i], array[j], useInterpreter);
}
}
}
[Fact]
public static void CheckNullableCharSubtractTest()
{
char?[] array = { '\0', '\b', 'A', '\uffff', null };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharSubtract(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableByteSubtract(byte? a, byte? b)
{
Expression aExp = Expression.Constant(a, typeof(byte?));
Expression bExp = Expression.Constant(b, typeof(byte?));
Assert.Throws<InvalidOperationException>(() => Expression.Subtract(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.SubtractChecked(aExp, bExp));
}
private static void VerifyNullableSByteSubtract(sbyte? a, sbyte? b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte?));
Expression bExp = Expression.Constant(b, typeof(sbyte?));
Assert.Throws<InvalidOperationException>(() => Expression.Subtract(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.SubtractChecked(aExp, bExp));
}
private static void VerifyNullableUShortSubtract(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Subtract(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort?)(a - b)), f());
}
private static void VerifyNullableUShortSubtractOvf(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
ushort? expected;
try
{
expected = checked((ushort?)(a - b));
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableShortSubtract(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Subtract(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short?)(a - b)), f());
}
private static void VerifyNullableShortSubtractOvf(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
short? expected;
try
{
expected = checked((short?)(a - b));
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableUIntSubtract(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Subtract(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifyNullableUIntSubtractOvf(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
uint? expected;
try
{
expected = checked(a - b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableIntSubtract(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Subtract(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifyNullableIntSubtractOvf(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
int? expected;
try
{
expected = checked(a - b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableULongSubtract(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Subtract(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifyNullableULongSubtractOvf(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
ulong? expected;
try
{
expected = checked(a - b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableLongSubtract(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Subtract(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a - b), f());
}
private static void VerifyNullableLongSubtractOvf(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
long? expected;
try
{
expected = checked(a - b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyNullableFloatSubtract(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Subtract(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a - b, f());
}
private static void VerifyNullableFloatSubtractOvf(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
Assert.Equal(a - b, f());
}
private static void VerifyNullableDoubleSubtract(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Subtract(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a - b, f());
}
private static void VerifyNullableDoubleSubtractOvf(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
Assert.Equal(a - b, f());
}
private static void VerifyNullableDecimalSubtract(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Subtract(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
{
decimal? expected;
try
{
expected = a - b;
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
else
Assert.Null(f());
}
private static void VerifyNullableDecimalSubtractOvf(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.SubtractChecked(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
{
decimal? expected;
try
{
expected = a - b;
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
else
Assert.Null(f());
}
private static void VerifyNullableCharSubtract(char? a, char? b)
{
Expression aExp = Expression.Constant(a, typeof(char?));
Expression bExp = Expression.Constant(b, typeof(char?));
Assert.Throws<InvalidOperationException>(() => Expression.Subtract(aExp, bExp));
Assert.Throws<InvalidOperationException>(() => Expression.SubtractChecked(aExp, bExp));
}
#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.
==================================================================== */
using NPOI.SS.UserModel;
using System.Text.RegularExpressions;
using NPOI.OpenXmlFormats.Spreadsheet;
using System;
using System.Text;
using System.Collections.Generic;
using NPOI.XSSF.Model;
namespace NPOI.XSSF.UserModel
{
/**
* Rich text unicode string. These strings can have fonts applied to arbitary parts of the string.
*
* <p>
* Most strings in a workbook have formatting applied at the cell level, that is, the entire string in the cell has the
* same formatting applied. In these cases, the formatting for the cell is stored in the styles part,
* and the string for the cell can be shared across the workbook. The following code illustrates the example.
* </p>
*
* <blockquote>
* <pre>
* cell1.SetCellValue(new XSSFRichTextString("Apache POI"));
* cell2.SetCellValue(new XSSFRichTextString("Apache POI"));
* cell3.SetCellValue(new XSSFRichTextString("Apache POI"));
* </pre>
* </blockquote>
* In the above example all three cells will use the same string cached on workbook level.
*
* <p>
* Some strings in the workbook may have formatting applied at a level that is more granular than the cell level.
* For instance, specific characters within the string may be bolded, have coloring, italicizing, etc.
* In these cases, the formatting is stored along with the text in the string table, and is treated as
* a unique entry in the workbook. The following xml and code snippet illustrate this.
* </p>
*
* <blockquote>
* <pre>
* XSSFRichTextString s1 = new XSSFRichTextString("Apache POI");
* s1.ApplyFont(boldArial);
* cell1.SetCellValue(s1);
*
* XSSFRichTextString s2 = new XSSFRichTextString("Apache POI");
* s2.ApplyFont(italicCourier);
* cell2.SetCellValue(s2);
* </pre>
* </blockquote>
*
*
* @author Yegor Kozlov
*/
public class XSSFRichTextString : IRichTextString
{
private static Regex utfPtrn = new Regex("_x([0-9A-F]{4})_");
private CT_Rst st;
private StylesTable styles;
/**
* Create a rich text string
*/
public XSSFRichTextString(String str)
{
st = new CT_Rst();
st.t = str;
PreserveSpaces(st.t);
}
public void SetStylesTableReference(StylesTable stylestable)
{
this.styles = stylestable;
if (st.sizeOfRArray() > 0)
{
foreach (CT_RElt r in st.r)
{
CT_RPrElt pr = r.rPr;
if (pr != null && pr.SizeOfRFontArray() > 0)
{
String fontName = pr.GetRFontArray(0).val;
if (fontName.StartsWith("#"))
{
int idx = int.Parse(fontName.Substring(1));
XSSFFont font = styles.GetFontAt(idx);
pr.rFont = null;
SetRunAttributes(font.GetCTFont(), pr);
}
}
}
}
}
/**
* Create empty rich text string and Initialize it with empty string
*/
public XSSFRichTextString()
{
st = new CT_Rst();
}
/**
* Create a rich text string from the supplied XML bean
*/
public XSSFRichTextString(CT_Rst st)
{
this.st = st;
}
/**
* Applies a font to the specified characters of a string.
*
* @param startIndex The start index to apply the font to (inclusive)
* @param endIndex The end index to apply the font to (exclusive)
* @param fontIndex The font to use.
*/
public void ApplyFont(int startIndex, int endIndex, short fontIndex)
{
XSSFFont font;
if (styles == null)
{
//style table is not Set, remember fontIndex and Set the run properties later,
//when SetStylesTableReference is called
font = new XSSFFont();
font.FontName = ("#" + fontIndex);
}
else
{
font = styles.GetFontAt(fontIndex);
}
ApplyFont(startIndex, endIndex, font);
}
internal void ApplyFont(SortedDictionary<int, CT_RPrElt> formats, int startIndex, int endIndex, CT_RPrElt fmt)
{
// delete format runs that fit between startIndex and endIndex
// runs intersecting startIndex and endIndex remain
//int runStartIdx = 0;
List<int> toRemoveKeys=new List<int>();
for (SortedDictionary<int, CT_RPrElt>.KeyCollection.Enumerator it = formats.Keys.GetEnumerator(); it.MoveNext(); )
{
int runIdx = it.Current;
if (runIdx >= startIndex && runIdx < endIndex)
{
toRemoveKeys.Add(runIdx);
}
}
foreach (int key in toRemoveKeys)
{
formats.Remove(key);
}
if (startIndex > 0 && !formats.ContainsKey(startIndex))
{
// If there's a format that starts later in the string, make it start now
foreach (KeyValuePair<int, CT_RPrElt> entry in formats)
{
if (entry.Key > startIndex)
{
formats[startIndex] = entry.Value;
break;
}
}
}
formats[endIndex] = fmt;
// assure that the range [startIndex, endIndex] consists if a single run
// there can be two or three runs depending whether startIndex or endIndex
// intersected existing format runs
//SortedMap<int, CT_RPrElt> sub = formats.subMap(startIndex, endIndex);
//while(sub.size() > 1) sub.remove(sub.lastKey());
}
/**
* Applies a font to the specified characters of a string.
*
* @param startIndex The start index to apply the font to (inclusive)
* @param endIndex The end index to apply to font to (exclusive)
* @param font The index of the font to use.
*/
public void ApplyFont(int startIndex, int endIndex, IFont font)
{
if (startIndex > endIndex)
throw new ArgumentException("Start index must be less than end index, but had " + startIndex + " and " + endIndex);
if (startIndex < 0 || endIndex > Length)
throw new ArgumentException("Start and end index not in range, but had " + startIndex + " and " + endIndex);
if (startIndex == endIndex)
return;
if (st.sizeOfRArray() == 0 && st.IsSetT())
{
//convert <t>string</t> into a text Run: <r><t>string</t></r>
st.AddNewR().t = (st.t);
st.unsetT();
}
String text = this.String;
XSSFFont xssfFont = (XSSFFont)font;
SortedDictionary<int, CT_RPrElt> formats = GetFormatMap(st);
CT_RPrElt fmt = new CT_RPrElt();
SetRunAttributes(xssfFont.GetCTFont(), fmt);
ApplyFont(formats, startIndex, endIndex, fmt);
CT_Rst newSt = buildCTRst(text, formats);
st.Set(newSt);
}
internal SortedDictionary<int, CT_RPrElt> GetFormatMap(CT_Rst entry)
{
int length = 0;
SortedDictionary<int, CT_RPrElt> formats = new SortedDictionary<int, CT_RPrElt>();
foreach (CT_RElt r in entry.r)
{
String txt = r.t;
CT_RPrElt fmt = r.rPr;
length += txt.Length;
formats[length] = fmt;
}
return formats;
}
/**
* Sets the font of the entire string.
* @param font The font to use.
*/
public void ApplyFont(IFont font)
{
String text = this.String;
ApplyFont(0, text.Length, font);
}
/**
* Applies the specified font to the entire string.
*
* @param fontIndex the font to Apply.
*/
public void ApplyFont(short fontIndex)
{
XSSFFont font;
if (styles == null)
{
font = new XSSFFont();
font.FontName = ("#" + fontIndex);
}
else
{
font = styles.GetFontAt(fontIndex);
}
String text = this.String;
ApplyFont(0, text.Length, font);
}
/**
* Append new text to this text run and apply the specify font to it
*
* @param text the text to append
* @param font the font to apply to the Appended text or <code>null</code> if no formatting is required
*/
public void Append(String text, XSSFFont font)
{
if (st.sizeOfRArray() == 0 && st.IsSetT())
{
//convert <t>string</t> into a text Run: <r><t>string</t></r>
CT_RElt lt = st.AddNewR();
lt.t = st.t;
PreserveSpaces(lt.t);
st.unsetT();
}
CT_RElt lt2 = st.AddNewR();
lt2.t= (text);
PreserveSpaces(lt2.t);
CT_RPrElt pr = lt2.AddNewRPr();
if (font != null) SetRunAttributes(font.GetCTFont(), pr);
}
/**
* Append new text to this text run
*
* @param text the text to append
*/
public void Append(String text)
{
Append(text, null);
}
/**
* Copy font attributes from CTFont bean into CTRPrElt bean
*/
private void SetRunAttributes(CT_Font ctFont, CT_RPrElt pr)
{
if (ctFont.SizeOfBArray() > 0) pr.AddNewB().val = (ctFont.GetBArray(0).val);
if (ctFont.sizeOfUArray() > 0) pr.AddNewU().val =(ctFont.GetUArray(0).val);
if (ctFont.sizeOfIArray() > 0) pr.AddNewI().val =(ctFont.GetIArray(0).val);
if (ctFont.sizeOfColorArray() > 0)
{
CT_Color c1 = ctFont.GetColorArray(0);
CT_Color c2 = pr.AddNewColor();
if (c1.IsSetAuto())
{
c2.auto = (c1.auto);
c2.autoSpecified = true;
}
if (c1.IsSetIndexed())
{
c2.indexed = (c1.indexed);
c2.indexedSpecified = true;
}
if (c1.IsSetRgb())
{
c2.SetRgb(c1.rgb);
c2.rgbSpecified = true;
}
if (c1.IsSetTheme())
{
c2.theme = (c1.theme);
c2.themeSpecified = true;
}
if (c1.IsSetTint())
{
c2.tint = (c1.tint);
c2.tintSpecified = true;
}
}
if (ctFont.sizeOfSzArray() > 0) pr.AddNewSz().val = (ctFont.GetSzArray(0).val);
if (ctFont.sizeOfNameArray() > 0) pr.AddNewRFont().val = (ctFont.name.val);
if (ctFont.sizeOfFamilyArray() > 0) pr.AddNewFamily().val =(ctFont.GetFamilyArray(0).val);
if (ctFont.sizeOfSchemeArray() > 0) pr.AddNewScheme().val = (ctFont.GetSchemeArray(0).val);
if (ctFont.sizeOfCharsetArray() > 0) pr.AddNewCharset().val = (ctFont.GetCharsetArray(0).val);
if (ctFont.sizeOfCondenseArray() > 0) pr.AddNewCondense().val = (ctFont.GetCondenseArray(0).val);
if (ctFont.sizeOfExtendArray() > 0) pr.AddNewExtend().val = (ctFont.GetExtendArray(0).val);
if (ctFont.sizeOfVertAlignArray() > 0) pr.AddNewVertAlign().val = (ctFont.GetVertAlignArray(0).val);
if (ctFont.sizeOfOutlineArray() > 0) pr.AddNewOutline().val =(ctFont.GetOutlineArray(0).val);
if (ctFont.sizeOfShadowArray() > 0) pr.AddNewShadow().val =(ctFont.GetShadowArray(0).val);
if (ctFont.sizeOfStrikeArray() > 0) pr.AddNewStrike().val = (ctFont.GetStrikeArray(0).val);
}
/**
* Removes any formatting that may have been applied to the string.
*/
public void ClearFormatting()
{
String text = this.String;
st.r = (null);
st.t= (text);
}
/**
* The index within the string to which the specified formatting run applies.
*
* @param index the index of the formatting run
* @return the index within the string.
*/
public int GetIndexOfFormattingRun(int index)
{
if (st.sizeOfRArray() == 0) return 0;
int pos = 0;
for (int i = 0; i < st.sizeOfRArray(); i++)
{
CT_RElt r = st.GetRArray(i);
if (i == index) return pos;
pos += r.t.Length;
}
return -1;
}
/**
* Returns the number of characters this format run covers.
*
* @param index the index of the formatting run
* @return the number of characters this format run covers
*/
public int GetLengthOfFormattingRun(int index)
{
if (st.sizeOfRArray() == 0 || index >= st.sizeOfRArray())
{
return -1;
}
CT_RElt r = st.GetRArray(index);
return r.t.Length;
}
public String String
{
get
{
if (st.sizeOfRArray() == 0)
{
return UtfDecode(st.t);
}
StringBuilder buf = new StringBuilder();
foreach (CT_RElt r in st.r)
{
buf.Append(r.t);
}
return UtfDecode(buf.ToString());
}
set
{
ClearFormatting();
st.t = value;
PreserveSpaces(st.t);
}
}
/**
* Returns the plain string representation.
*/
public override String ToString()
{
return this.String;
}
/**
* Returns the number of characters in this string.
*/
public int Length
{
get
{
return this.String.Length;
}
}
/**
* @return The number of formatting Runs used.
*/
public int NumFormattingRuns
{
get
{
return st.sizeOfRArray();
}
}
/**
* Gets a copy of the font used in a particular formatting Run.
*
* @param index the index of the formatting run
* @return A copy of the font used or null if no formatting is applied to the specified text Run.
*/
public IFont GetFontOfFormattingRun(int index)
{
if (st.sizeOfRArray() == 0 || index >= st.sizeOfRArray()) return null;
CT_RElt r = st.GetRArray(index);
if (r.rPr != null)
{
XSSFFont fnt = new XSSFFont(ToCTFont(r.rPr));
fnt.SetThemesTable(GetThemesTable());
return fnt;
}
return null;
}
/**
* Return a copy of the font in use at a particular index.
*
* @param index The index.
* @return A copy of the font that's currently being applied at that
* index or null if no font is being applied or the
* index is out of range.
*/
public XSSFFont GetFontAtIndex(int index)
{
if (st.sizeOfRArray() == 0) return null;
int pos = 0;
for (int i = 0; i < st.sizeOfRArray(); i++)
{
CT_RElt r = st.GetRArray(i);
if (index >= pos && index < pos + r.t.Length)
{
XSSFFont fnt = new XSSFFont(ToCTFont(r.rPr));
fnt.SetThemesTable(GetThemesTable());
return fnt;
}
pos += r.t.Length;
}
return null;
}
/**
* Return the underlying xml bean
*/
public CT_Rst GetCTRst()
{
return st;
}
/**
*
* CTRPrElt --> CTFont adapter
*/
protected static CT_Font ToCTFont(CT_RPrElt pr)
{
CT_Font ctFont = new CT_Font();
if (pr.SizeOfBArray() > 0) ctFont.AddNewB().val = (pr.GetBArray(0).val);
if (pr.SizeOfUArray() > 0) ctFont.AddNewU().val = (pr.GetUArray(0).val);
if (pr.SizeOfIArray() > 0) ctFont.AddNewI().val = (pr.GetIArray(0).val);
if (pr.SizeOfColorArray() > 0)
{
CT_Color c1 = pr.GetColorArray(0);
CT_Color c2 = ctFont.AddNewColor();
if (c1.IsSetAuto())
{
c2.auto = (c1.auto);
c2.autoSpecified = true;
}
if (c1.IsSetIndexed())
{
c2.indexed = (c1.indexed);
c2.indexedSpecified = true;
}
if (c1.IsSetRgb())
{
c2.SetRgb(c1.GetRgb());
c2.rgbSpecified = true;
}
if (c1.IsSetTheme())
{
c2.theme = (c1.theme);
c2.themeSpecified = true;
}
if (c1.IsSetTint())
{
c2.tint = (c1.tint);
c2.tintSpecified = true;
}
}
if (pr.SizeOfSzArray() > 0) ctFont.AddNewSz().val = (pr.GetSzArray(0).val);
if (pr.SizeOfRFontArray() > 0) ctFont.AddNewName().val = (pr.GetRFontArray(0).val);
if (pr.SizeOfFamilyArray() > 0) ctFont.AddNewFamily().val = (pr.GetFamilyArray(0).val);
if (pr.sizeOfSchemeArray() > 0) ctFont.AddNewScheme().val = (pr.GetSchemeArray(0).val);
if (pr.sizeOfCharsetArray() > 0) ctFont.AddNewCharset().val = (pr.GetCharsetArray(0).val);
if (pr.sizeOfCondenseArray() > 0) ctFont.AddNewCondense().val = (pr.GetCondenseArray(0).val);
if (pr.sizeOfExtendArray() > 0) ctFont.AddNewExtend().val = (pr.GetExtendArray(0).val);
if (pr.sizeOfVertAlignArray() > 0) ctFont.AddNewVertAlign().val = (pr.GetVertAlignArray(0).val);
if (pr.sizeOfOutlineArray() > 0) ctFont.AddNewOutline().val = (pr.GetOutlineArray(0).val);
if (pr.sizeOfShadowArray() > 0) ctFont.AddNewShadow().val = (pr.GetShadowArray(0).val);
if (pr.sizeOfStrikeArray() > 0) ctFont.AddNewStrike().val = (pr.GetStrikeArray(0).val);
return ctFont;
}
///**
// * Add the xml:spaces="preserve" attribute if the string has leading or trailing spaces
// *
// * @param xs the string to check
// */
protected static void PreserveSpaces(string xs)
{
String text = xs;
if (text != null && text.Length > 0)
{
char firstChar = text[0];
char lastChar = text[text.Length - 1];
if (Char.IsWhiteSpace(firstChar) || Char.IsWhiteSpace(lastChar))
{
//XmlCursor c = xs.newCursor();
//c.ToNextToken();
//c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
//c.dispose();
}
}
}
/**
* For all characters which cannot be represented in XML as defined by the XML 1.0 specification,
* the characters are escaped using the Unicode numerical character representation escape character
* format _xHHHH_, where H represents a hexadecimal character in the character's value.
* <p>
* Example: The Unicode character 0D is invalid in an XML 1.0 document,
* so it shall be escaped as <code>_x000D_</code>.
* </p>
* See section 3.18.9 in the OOXML spec.
*
* @param value the string to decode
* @return the decoded string
*/
static String UtfDecode(String value)
{
if (value == null) return null;
StringBuilder buf = new StringBuilder();
MatchCollection mc = utfPtrn.Matches(value);
int idx = 0;
for (int i = 0; i < mc.Count;i++ )
{
int pos = mc[i].Index;
if (pos > idx)
{
buf.Append(value.Substring(idx, pos-idx));
}
String code = mc[i].Groups[1].Value;
int icode = Int32.Parse(code, System.Globalization.NumberStyles.AllowHexSpecifier);
buf.Append((char)icode);
idx = mc[i].Index+mc[i].Length;
}
buf.Append(value.Substring(idx));
return buf.ToString();
}
public int GetLastKey(SortedDictionary<int, CT_RPrElt>.KeyCollection keys)
{
int i=0;
foreach (int key in keys)
{
if (i == keys.Count - 1)
return key;
i++;
}
throw new ArgumentOutOfRangeException("GetLastKey failed");
}
CT_Rst buildCTRst(String text, SortedDictionary<int, CT_RPrElt> formats)
{
if (text.Length != GetLastKey(formats.Keys))
{
throw new ArgumentException("Text length was " + text.Length +
" but the last format index was " + GetLastKey(formats.Keys));
}
CT_Rst st = new CT_Rst();
int runStartIdx = 0;
for (SortedDictionary<int, CT_RPrElt>.KeyCollection.Enumerator it = formats.Keys.GetEnumerator(); it.MoveNext(); )
{
int runEndIdx = it.Current;
CT_RElt run = st.AddNewR();
String fragment = text.Substring(runStartIdx, runEndIdx - runStartIdx);
run.t = (fragment);
PreserveSpaces(run.t);
CT_RPrElt fmt = formats[runEndIdx];
if (fmt != null)
run.rPr = (fmt);
runStartIdx = runEndIdx;
}
return st;
}
private ThemesTable GetThemesTable()
{
if (styles == null) return null;
return styles.GetTheme();
}
}
}
| |
// 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: List for exceptions.
**
**
===========================================================*/
namespace System.Collections
{
/// This is a simple implementation of IDictionary using a singly linked list. This
/// will be smaller and faster than a Hashtable if the number of elements is 10 or less.
/// This should not be used if performance is important for large numbers of elements.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
// Needs to be public to support binary serialization compatibility
public class ListDictionaryInternal : IDictionary
{
private DictionaryNode head; // Do not rename (binary serialization)
private int version; // Do not rename (binary serialization)
private int count; // Do not rename (binary serialization)
[NonSerialized]
private Object _syncRoot;
public ListDictionaryInternal()
{
}
public Object this[Object key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
DictionaryNode node = head;
while (node != null)
{
if (node.key.Equals(key))
{
return node.value;
}
node = node.next;
}
return null;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next)
{
if (node.key.Equals(key))
{
break;
}
last = node;
}
if (node != null)
{
// Found it
node.value = value;
return;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null)
{
last.next = newNode;
}
else
{
head = newNode;
}
count++;
}
}
public int Count
{
get
{
return count;
}
}
public ICollection Keys
{
get
{
return new NodeKeyValueCollection(this, true);
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
public ICollection Values
{
get
{
return new NodeKeyValueCollection(this, false);
}
}
public void Add(Object key, Object value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next)
{
if (node.key.Equals(key))
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, node.key, key));
}
last = node;
}
if (node != null)
{
// Found it
node.value = value;
return;
}
// Not found, so add a new one
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
if (last != null)
{
last.next = newNode;
}
else
{
head = newNode;
}
count++;
}
public void Clear()
{
count = 0;
head = null;
version++;
}
public bool Contains(Object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
for (DictionaryNode node = head; node != null; node = node.next)
{
if (node.key.Equals(key))
{
return true;
}
}
return false;
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < this.Count)
throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index));
for (DictionaryNode node = head; node != null; node = node.next)
{
array.SetValue(new DictionaryEntry(node.key, node.value), index);
index++;
}
}
public IDictionaryEnumerator GetEnumerator()
{
return new NodeEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeEnumerator(this);
}
public void Remove(Object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
version++;
DictionaryNode last = null;
DictionaryNode node;
for (node = head; node != null; node = node.next)
{
if (node.key.Equals(key))
{
break;
}
last = node;
}
if (node == null)
{
return;
}
if (node == head)
{
head = node.next;
}
else
{
last.next = node.next;
}
count--;
}
private class NodeEnumerator : IDictionaryEnumerator
{
private ListDictionaryInternal list;
private DictionaryNode current;
private int version;
private bool start;
public NodeEnumerator(ListDictionaryInternal list)
{
this.list = list;
version = list.version;
start = true;
current = null;
}
public Object Current
{
get
{
return Entry;
}
}
public DictionaryEntry Entry
{
get
{
if (current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(current.key, current.value);
}
}
public Object Key
{
get
{
if (current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return current.key;
}
}
public Object Value
{
get
{
if (current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return current.value;
}
}
public bool MoveNext()
{
if (version != list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (start)
{
current = list.head;
start = false;
}
else
{
if (current != null)
{
current = current.next;
}
}
return (current != null);
}
public void Reset()
{
if (version != list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
start = true;
current = null;
}
}
private class NodeKeyValueCollection : ICollection
{
private ListDictionaryInternal list;
private bool isKeys;
public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys)
{
this.list = list;
this.isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < list.Count)
throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index));
for (DictionaryNode node = list.head; node != null; node = node.next)
{
array.SetValue(isKeys ? node.key : node.value, index);
index++;
}
}
int ICollection.Count
{
get
{
int count = 0;
for (DictionaryNode node = list.head; node != null; node = node.next)
{
count++;
}
return count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
Object ICollection.SyncRoot
{
get
{
return list.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new NodeKeyValueEnumerator(list, isKeys);
}
private class NodeKeyValueEnumerator : IEnumerator
{
private ListDictionaryInternal list;
private DictionaryNode current;
private int version;
private bool isKeys;
private bool start;
public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys)
{
this.list = list;
this.isKeys = isKeys;
version = list.version;
start = true;
current = null;
}
public Object Current
{
get
{
if (current == null)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return isKeys ? current.key : current.value;
}
}
public bool MoveNext()
{
if (version != list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
if (start)
{
current = list.head;
start = false;
}
else
{
if (current != null)
{
current = current.next;
}
}
return (current != null);
}
public void Reset()
{
if (version != list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
start = true;
current = null;
}
}
}
[Serializable]
private class DictionaryNode
{
public Object key;
public Object value;
public DictionaryNode next;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertToVector128Int64Int16()
{
var test = new SimpleUnaryOpTest__ConvertToVector128Int64Int16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToVector128Int64Int16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector128<Int16> _clsVar;
private Vector128<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int64, Int16> _dataTable;
static SimpleUnaryOpTest__ConvertToVector128Int64Int16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ConvertToVector128Int64Int16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int16>(_data, new Int64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.ConvertToVector128Int64(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.ConvertToVector128Int64(
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.ConvertToVector128Int64(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.ConvertToVector128Int64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr);
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse41.ConvertToVector128Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector128Int64Int16();
var result = Sse41.ConvertToVector128Int64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.ConvertToVector128Int64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
if (result[0] != firstOp[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.ConvertToVector128Int64)}<Int64>(Vector128<Int16>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="NavigationPropertyEmitter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.CodeDom;
using System.Collections.Generic;
using System.Data.Metadata.Edm;
using System.Data.Services.Design;
using System.Diagnostics;
namespace System.Data.EntityModel.Emitters
{
/// <summary>
/// Summary description for NavigationPropertyEmitter.
/// </summary>
internal sealed class NavigationPropertyEmitter : PropertyEmitterBase
{
private const string ValuePropertyName = "Value";
/// <summary>
///
/// </summary>
/// <param name="generator"></param>
/// <param name="navigationProperty"></param>
public NavigationPropertyEmitter(ClientApiGenerator generator, NavigationProperty navigationProperty, bool declaringTypeUsesStandardBaseType)
: base(generator, navigationProperty, declaringTypeUsesStandardBaseType)
{
}
/// <summary>
/// Generate the navigation property
/// </summary>
/// <param name="typeDecl">The type to add the property to.</param>
protected override void EmitProperty(CodeTypeDeclaration typeDecl)
{
EmitNavigationProperty(typeDecl);
}
/// <summary>
/// Generate the navigation property specified
/// </summary>
/// <param name="typeDecl">The type to add the property to.</param>
private void EmitNavigationProperty(CodeTypeDeclaration typeDecl)
{
// create a regular property
CodeMemberProperty property = EmitNavigationProperty(Item.ToEndMember);
typeDecl.Members.Add(property);
EmitField(typeDecl, GetReturnType(Item.ToEndMember), Item.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many);
}
private void EmitField(CodeTypeDeclaration typeDecl, CodeTypeReference fieldType, bool hasDefault)
{
CodeMemberField memberField = new CodeMemberField(fieldType, Utils.FieldNameFromPropName(Item.Name));
memberField.Attributes = MemberAttributes.Private;
AttributeEmitter.AddGeneratedCodeAttribute(memberField);
if (hasDefault)
{
if (this.Generator.UseDataServiceCollection)
{
// new DataServiceCollection<T>(null, System.Data.Services.Client.TrackingMode.None, null, null, null);
// declare type is DataServiceCollection<T>
Debug.Assert(fieldType.TypeArguments.Count == 1, "Declare type is non generic.");
// new DataServiceCollection<[type]>(null, TrackingMode.None)
memberField.InitExpression = new CodeObjectCreateExpression(
fieldType,
new CodePrimitiveExpression(null),
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(System.Data.Services.Client.TrackingMode)),
"None"));
}
else
{
memberField.InitExpression = new CodeObjectCreateExpression(fieldType);
}
}
typeDecl.Members.Add(memberField);
}
/// <summary>
/// Generate a navigation property
/// </summary>
/// <param name="target">the other end</param>
/// <param name="referenceProperty">True to emit Reference navigation property</param>
/// <returns>the generated property</returns>
private CodeMemberProperty EmitNavigationProperty(RelationshipEndMember target)
{
CodeTypeReference typeRef = GetReturnType(target);
// raise the PropertyGenerated event
PropertyGeneratedEventArgs eventArgs = new PropertyGeneratedEventArgs(Item,
null, // no backing field
typeRef);
this.Generator.RaisePropertyGeneratedEvent(eventArgs);
// [System.ComponentModel.Browsable(false)]
// public TargetType TargetName
// public EntityReference<TargetType> TargetName
// or
// public EntityCollection<targetType> TargetNames
CodeMemberProperty property = new CodeMemberProperty();
// Only reference navigation properties are currently currently supported with XML serialization
// and thus we should use the XmlIgnore and SoapIgnore attributes on other property types.
AttributeEmitter.AddIgnoreAttributes(property);
AttributeEmitter.AddBrowsableAttribute(property);
AttributeEmitter.AddGeneratedCodeAttribute(property);
CommentEmitter.EmitSummaryComments(Item, property.Comments);
property.Name = Item.Name;
if (eventArgs.ReturnType != null && !eventArgs.ReturnType.Equals(typeRef))
{
property.Type = eventArgs.ReturnType;
}
else
{
property.Type = typeRef;
}
property.Attributes = MemberAttributes.Final;
CodeExpression getMethod = EmitGetMethod(target);
CodeExpression getReturnExpression;
if (target.RelationshipMultiplicity != RelationshipMultiplicity.Many)
{
property.Attributes |= AccessibilityFromGettersAndSetters(Item);
// insert user-supplied Set code here, before the assignment
//
List<CodeStatement> additionalSetStatements = eventArgs.AdditionalSetStatements;
if (additionalSetStatements != null && additionalSetStatements.Count > 0)
{
try
{
property.SetStatements.AddRange(additionalSetStatements.ToArray());
}
catch (ArgumentNullException e)
{
Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
EdmSchemaErrorSeverity.Error,
e);
}
}
CodeExpression valueRef = new CodePropertySetValueReferenceExpression();
if (typeRef != eventArgs.ReturnType)
{
// we need to cast to the actual type
valueRef = new CodeCastExpression(typeRef, valueRef);
}
CodeExpression valueProperty = getMethod;
// get
// return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value;
getReturnExpression = valueProperty;
// set
// ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value = value;
property.SetStatements.Add(
new CodeAssignStatement(valueProperty, valueRef));
// setup the accessibility of the navigation property setter and getter
MemberAttributes propertyAccessibility = property.Attributes & MemberAttributes.AccessMask;
PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
PropertyEmitter.GetGetterAccessibility(Item), propertyAccessibility, true);
PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
PropertyEmitter.GetSetterAccessibility(Item), propertyAccessibility, false);
List<CodeStatement> additionalAfterSetStatements = eventArgs.AdditionalAfterSetStatements;
if (additionalAfterSetStatements != null && additionalAfterSetStatements.Count > 0)
{
try
{
property.SetStatements.AddRange(additionalAfterSetStatements.ToArray());
}
catch (ArgumentNullException e)
{
Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
EdmSchemaErrorSeverity.Error,
e);
}
}
}
else
{
property.Attributes |= PropertyEmitter.GetGetterAccessibility(Item);
// get
// return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName");
getReturnExpression = getMethod;
// set
// if (value != null) ==> Only for non-binding scenario
// {
// this =
// this.OnPropertyChanged("")
// }
CodeExpression valueRef = new CodePropertySetValueReferenceExpression();
CodeStatementCollection csc = null;
if (this.Generator.UseDataServiceCollection == true)
{
csc = property.SetStatements;
}
else
{
CodeConditionStatement ccs = new CodeConditionStatement(EmitExpressionDoesNotEqualNull(valueRef));
property.SetStatements.Add(ccs);
csc = ccs.TrueStatements;
}
csc.Add(new CodeAssignStatement(getMethod, valueRef));
if (eventArgs.AdditionalAfterSetStatements != null)
{
try
{
foreach (CodeStatement s in eventArgs.AdditionalAfterSetStatements)
{
csc.Add(s);
}
}
catch (ArgumentNullException e)
{
Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
EdmSchemaErrorSeverity.Error,
e);
}
}
}
// if additional Get statements were specified by the event subscriber, insert them now
//
List<CodeStatement> additionalGetStatements = eventArgs.AdditionalGetStatements;
if (additionalGetStatements != null && additionalGetStatements.Count > 0)
{
try
{
property.GetStatements.AddRange(additionalGetStatements.ToArray());
}
catch (ArgumentNullException ex)
{
Generator.AddError(Strings.InvalidGetStatementSuppliedForProperty(Item.Name),
ModelBuilderErrorCode.InvalidGetStatementSuppliedForProperty,
EdmSchemaErrorSeverity.Error,
ex);
}
}
property.GetStatements.Add(new CodeMethodReturnStatement(getReturnExpression));
return property;
}
internal static bool IsNameAlreadyAMemberName(StructuralType type, string generatedPropertyName, StringComparison comparison)
{
foreach (EdmMember member in type.Members)
{
if (member.DeclaringType == type &&
member.Name.Equals(generatedPropertyName, comparison))
{
return true;
}
}
return false;
}
private string GetFullyQualifiedPropertyName(string propertyName)
{
return Item.DeclaringType.FullName + "." + propertyName;
}
/// <summary>
/// Gives the SchemaElement back cast to the most
/// appropriate type
/// </summary>
private new NavigationProperty Item
{
get
{
return base.Item as NavigationProperty;
}
}
/// <summary>
/// Get the return type for the get method, given the target end
/// </summary>
/// <param name="target"></param>
/// <param name="referenceMethod">true if the is the return type for a reference property</param>
/// <returns>the return type for a target</returns>
private CodeTypeReference GetReturnType(RelationshipEndMember target)
{
CodeTypeReference returnType = Generator.GetLeastPossibleQualifiedTypeReference(GetEntityType(target));
if (target.RelationshipMultiplicity == RelationshipMultiplicity.Many)
{
returnType = TypeReference.FrameworkGenericClass(this.Generator.GetRelationshipMultiplicityManyCollectionTypeName(), returnType);
}
return returnType;
}
private static EntityTypeBase GetEntityType(RelationshipEndMember endMember)
{
Debug.Assert((BuiltInTypeKind.RefType == endMember.TypeUsage.EdmType.BuiltInTypeKind), "not a reference type");
EntityTypeBase type = ((RefType)endMember.TypeUsage.EdmType).ElementType;
return type;
}
/// <summary>
/// Emit the GetRelatedCollection or GetRelatedReference methods
/// </summary>
/// <param name="target">Target end of the relationship</param>
/// <returns>Expression to invoke the appropriate method</returns>
private CodeExpression EmitGetMethod(RelationshipEndMember target)
{
return new CodeFieldReferenceExpression(ThisRef, Utils.FieldNameFromPropName(Item.Name));
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Column.cs" company="Itransition">
// Itransition (c) Copyright. All right reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Data;
using ECM7.Migrator.Framework;
namespace Framework.Migrator.Fluent
{
/// <summary>
/// Provides fluent interface for column building.
/// </summary>
public class Column : IMigrationPart, IColumn
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Column"/> class.
/// </summary>
/// <param name="columnColumnColumnName">Name of the column.</param>
/// <param name="tableColumnName">Name of the table.</param>
public Column(String columnColumnColumnName, String tableColumnName)
{
Name = columnColumnColumnName;
TableName = tableColumnName;
}
/// <summary>
/// Initializes a new instance of the <see cref="Column"/> class.
/// </summary>
/// <param name="columnType">Column type.</param>
/// <param name="columnName">Name of the column.</param>
/// <param name="tableName">Name of the table.</param>
public Column(DbType columnType, String columnName, String tableName) : this(columnName, tableName)
{
ColumnType = columnType;
}
#endregion
#region Properties
/// <summary>
/// Gets the name of the table.
/// </summary>
/// <value>The name of the table.</value>
public String TableName { get; private set; }
/// <summary>
/// Gets the name of column.
/// </summary>
/// <value>The name of column.</value>
public String Name { get; private set; }
/// <summary>
/// Gets the column type.
/// </summary>
/// <value>The column type.</value>
public DbType ColumnType { get; private set; }
/// <summary>
/// Gets the column length.
/// </summary>
/// <value>The column length.</value>
public int? ColumnLength { get; private set; }
/// <summary>
/// Gets the column scale.
/// </summary>
/// <value>The column scale.</value>
public int? ColumnScale { get; private set; }
/// <summary>
/// Gets a value indicating whether the column is nullable.
/// </summary>
/// <value>
/// <c>true</c> if column is nullable; otherwise, <c>false</c>.
/// </value>
public bool IsNullable { get; private set; }
/// <summary>
/// Gets a value indicating whether the column is primary key.
/// </summary>
/// <value>
/// <c>true</c> if the column is primary key; otherwise, <c>false</c>.
/// </value>
public bool IsPrimaryKey { get; private set; }
/// <summary>
/// Gets a value indicating whether the column is identity.
/// </summary>
/// <value>
/// <c>true</c> if the column is identity; otherwise, <c>false</c>.
/// </value>
public bool IsIdentity { get; private set; }
/// <summary>
/// Gets a value indicating whether the column is unique.
/// </summary>
/// <value><c>true</c> if the column is unique; otherwise, <c>false</c>.</value>
public bool IsUnique { get; private set; }
/// <summary>
/// Gets the column default value.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue { get; private set; }
/// <summary>
/// Gets the column properties.
/// </summary>
/// <value>The column properties.</value>
public ColumnProperty ColumnProperties { get; private set; }
#endregion
#region Build methods
/// <summary>
/// Adds column property.
/// </summary>
/// <param name="property">The column property.</param>
/// <returns>column instance.</returns>
public Column AddProperty(ColumnProperty property)
{
ColumnProperties |= property;
return this;
}
/// <summary>
/// Removes column property.
/// </summary>
/// <param name="property">The column property.</param>
/// <returns>column instance.</returns>
public Column RemoveProperty(ColumnProperty property)
{
ColumnProperties &= ~property;
return this;
}
/// <summary>
/// Makes the column nullable.
/// </summary>
/// <returns>column instance.</returns>
public Column Null()
{
IsNullable = true;
return this;
}
/// <summary>
/// Makes the column primary key.
/// </summary>
/// <returns>column instance.</returns>
public Column PrimaryKey()
{
IsPrimaryKey = true;
IsNullable = false;
return this;
}
/// <summary>
/// Makes the column identity.
/// </summary>
/// <returns>column instance.</returns>
public Column Identity()
{
IsIdentity = true;
return this;
}
/// <summary>
/// Makes the column unique.
/// </summary>
/// <returns>column instance.</returns>
public Column Unique()
{
IsUnique = true;
return this;
}
/// <summary>
/// Sets the length for column.
/// </summary>
/// <param name="columnLength">Length of the column.</param>
/// <returns>column instance.</returns>
public Column Length(int columnLength)
{
ColumnLength = columnLength;
return this;
}
/// <summary>
/// Sets the scale for column.
/// </summary>
/// <param name="columnScale">Scale of the column.</param>
/// <returns>column instance.</returns>
public Column Scale(int columnScale)
{
ColumnScale = columnScale;
return this;
}
/// <summary>
/// Sets the column default value.
/// </summary>
/// <param name="columnDefaultValue">The column default value.</param>
/// <returns>column instance.</returns>
public Column Default(Object columnDefaultValue)
{
DefaultValue = columnDefaultValue;
return this;
}
/// <summary>
/// Sets the column type.
/// </summary>
/// <param name="columnType">Type of the column.</param>
/// <returns>column instance.</returns>
public Column Type(DbType columnType)
{
ColumnType = columnType;
return this;
}
/// <summary>
/// Sets column type to Integer (32 bit integer number).
/// </summary>
/// <returns>column instance.</returns>
public Column Integer()
{
return Type(DbType.Int32);
}
/// <summary>
/// Sets column type to Long (64 bit integer number).
/// </summary>
/// <returns>column instance.</returns>
public Column Long()
{
return Type(DbType.Int64);
}
/// <summary>
/// Sets column type to String.
/// </summary>
/// <returns>column instance.</returns>
public Column String()
{
return Type(DbType.String);
}
/// <summary>
/// Sets column type to Text.
/// </summary>
/// <returns>column instance.</returns>
public Column Text()
{
return Type(DbType.String).Length(Defaults.MaxStringLength + 1);
}
/// <summary>
/// Sets column type to DateTime.
/// </summary>
/// <returns>column instance.</returns>
public Column DateTime()
{
return Type(DbType.DateTime);
}
/// <summary>
/// Sets column type to Bool.
/// </summary>
/// <returns>column instance.</returns>
public Column Bool()
{
return Type(DbType.Boolean);
}
/// <summary>
/// Sets column type to Double.
/// </summary>
/// <returns>column instance.</returns>
public Column Double()
{
return Type(DbType.Double);
}
/// <summary>
/// Sets column type to Decimal.
/// </summary>
/// <returns>column instance.</returns>
public Column Decimal()
{
return Type(DbType.Decimal);
}
#endregion
#region IMigrationPart members
/// <summary>
/// Implementation of this method is speicific to operation kind (add column, change column, remove column).
/// </summary>
/// <param name="database">The database.</param>
public virtual void Migrate(ITransformationProvider database)
{
// Do nothing.
}
#endregion
#region IColumn members
/// <summary>
/// Gets the column specification.
/// </summary>
/// <returns>Column specification.</returns>
public ECM7.Migrator.Framework.Column GetColumn()
{
if (IsNullable)
{
AddProperty(ColumnProperty.Null);
RemoveProperty(ColumnProperty.NotNull);
}
else
{
AddProperty(ColumnProperty.NotNull);
RemoveProperty(ColumnProperty.Null);
}
AddProperty(ColumnProperty.PrimaryKey, IsPrimaryKey);
AddProperty(ColumnProperty.Identity, IsIdentity);
AddProperty(ColumnProperty.Unique, IsUnique);
return new ECM7.Migrator.Framework.Column(Name, GetColumnType(), ColumnProperties, DefaultValue);
}
#endregion
#region Helper members
private void AddProperty(ColumnProperty property, bool value)
{
if (value)
{
AddProperty(property);
}
}
private ColumnType GetColumnType()
{
var columnType = new ColumnType(ColumnType);
columnType.Length = ColumnLength ?? Defaults.ColumnSize;
if (ColumnScale != null)
{
columnType.Scale = ColumnScale;
}
return columnType;
}
#endregion
}
}
| |
using System.Collections.Generic;
using SteeringBehaviors;
using UnityEngine;
using Flocking;
using System.Threading;
public class FlockWander : MultipleBirdState
{
int currentFrame = 0;
public Entity anchor;
Flock anchorFlock;
float _cohesionToAnchorWeight = 0.25f;
float _separationFromAnchorWeight = 0f;
float _velMatchToAnchorWeight = 0f;
// separation options
float _separationWeight = 2f;
float _separationAknnVal = 1f;
float _separationDistance = 5f;
int _separationK = 5;
// cohesion options
float _cohesionWeight = 1f;
float _cohesionAknnVal = 1f;
float _cohesionDistance = 30f;
int _cohesionK = 10;
// velocity match options
float _velocityMatchWeight = 0.25f;
float _velocityMatchAknnVal = 25f;
float _velocityMatchDistance = 20f;
int _velocityMatchK = 5;
float _cohesionMinDotProduct = -0.5f;
float _separationMinDotProduct = -0.5f;
float _velMatchMinDotProduct = -0.5f;
public float percentageOfBoidsToUpdate = 0.6f; // percentage of boids to update every frame
System.Diagnostics.Stopwatch kdBuildTimer, updateTimer;
int frameCount = 0;
int current;
public FlockWander()
{
kdBuildTimer = new System.Diagnostics.Stopwatch();
updateTimer = new System.Diagnostics.Stopwatch();
}
/// <summary>
/// Re-calculates the path for each bird
/// </summary>
public override void Init()
{
if (anchor == null)
anchor = GameObject.Find("Player").GetComponent<Starling>();
anchorFlock = new Flock(anchor);
foreach (var entry in entries)
entry.behavior = getDefaultSteering(entry, flock);
}
public override void Update(float dt)
{
if (Time.frameCount == currentFrame) return;
currentFrame = Time.frameCount;
//------------
kdBuildTimer.Start();
flock.RebuildKdTree();
anchorFlock.RebuildKdTree();
kdBuildTimer.Stop();
//------------
updateTimer.Start();
// reset values
for (int i = 0; i < entries.Count; ++i)
{
(((entries[i].behavior as PrioritySteering).Groups[1] as BlendedSteering).Behaviors[0].behaviour as Separation).useOldValues = true;
(((entries[i].behavior as PrioritySteering).Groups[1] as BlendedSteering).Behaviors[1].behaviour as Cohesion).useOldValues = true;
(((entries[i].behavior as PrioritySteering).Groups[1] as BlendedSteering).Behaviors[2].behaviour as VelocityMatch).useOldValues = true;
}
int boidsToUpdate = Mathf.CeilToInt(entries.Count * percentageOfBoidsToUpdate); // make sure at least one boid is updated
int limit = (current + boidsToUpdate < entries.Count ? current + boidsToUpdate : entries.Count);
for (; current < limit; ++current)
{
(((entries[current].behavior as PrioritySteering).Groups[1] as BlendedSteering).Behaviors[0].behaviour as Separation).useOldValues = false;
(((entries[current].behavior as PrioritySteering).Groups[1] as BlendedSteering).Behaviors[1].behaviour as Cohesion).useOldValues = false;
(((entries[current].behavior as PrioritySteering).Groups[1] as BlendedSteering).Behaviors[2].behaviour as VelocityMatch).useOldValues = false;
}
if (current == entries.Count)
current = 0;
// update birds and calculate the center of the flock
for (int i = 0; i < entries.Count; ++i)
UpdateSteering(dt, entries[i]);
updateTimer.Stop();
++frameCount;
}
Steering getDefaultSteering(Entry e, Flock flock)
{
var separation = new Separation(e.bird, flock, _separationDistance, -0.5f);
var cohesion = new Cohesion(e.bird, flock, _cohesionDistance, -0.5f);
var velMatch = new VelocityMatch(e.bird, flock, _velocityMatchDistance, -0.5f);
var anchorCohesion = new Cohesion(e.bird, anchorFlock, float.MaxValue, -1f); // move towards the anchor
var anchorSeparation = new Separation(e.bird, anchorFlock, 25f, -1f);
var anchorVelocityMatch = new VelocityMatch(e.bird, anchorFlock, float.MaxValue, -1f);
separation.aknnApproxVal = _separationAknnVal;
cohesion.aknnApproxVal = _cohesionAknnVal;
velMatch.aknnApproxVal = _velocityMatchAknnVal;
separation.maxNeighborhoodSize = separationK;
cohesion.maxNeighborhoodSize = cohesionK;
velMatch.maxNeighborhoodSize = velocityMatchK;
var obstacleAvoidance = new ObstacleAvoidance(e.bird, 20f, new string[]{"Ground"});
var blended = new BlendedSteering[2];
blended[0] = new BlendedSteering(e.bird, new BehaviorAndWeight(obstacleAvoidance, 1f));
blended[1] = new BlendedSteering(e.bird, new BehaviorAndWeight(separation, _separationWeight), // 0
new BehaviorAndWeight(cohesion, _cohesionWeight), // 1
new BehaviorAndWeight(velMatch, _velocityMatchWeight), // 2
new BehaviorAndWeight(anchorCohesion, _cohesionToAnchorWeight), // 3
new BehaviorAndWeight(anchorSeparation, _separationFromAnchorWeight), // 4
new BehaviorAndWeight(anchorVelocityMatch, _velMatchToAnchorWeight) // 5
);
return new PrioritySteering(1f, blended);
}
public override void Update(float dt, Bird bird) {}
public override void FixedUpdate() {}
public override void onCollisionEnter(Collision other) {}
public override void onCollisionStay(Collision other) {}
public override void onCollisionExit(Collision other) {}
/// <summary>
/// Gets or sets the cohesion to anchor weight.
/// </summary>
public float cohesionToAnchorWeight
{
get { return _cohesionToAnchorWeight; }
set
{
_cohesionToAnchorWeight = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
blendedSteerings.Behaviors[3].weight = _cohesionToAnchorWeight;
}
}
}
public float separationFromAnchorWeight
{
get { return _separationFromAnchorWeight; }
set
{
_separationFromAnchorWeight = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
blendedSteerings.Behaviors[4].weight = _separationFromAnchorWeight;
}
}
}
public float velMatchToAnchorWeight
{
get { return _velMatchToAnchorWeight; }
set
{
_velMatchToAnchorWeight = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
blendedSteerings.Behaviors[5].weight = _velMatchToAnchorWeight;
}
}
}
/// <summary>
/// Gets or sets the separation to the flock weight.
/// </summary>
public float separationWeight
{
get { return _separationWeight; }
set
{
_separationWeight = value;
foreach(var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
blendedSteerings.Behaviors[0].weight = _separationWeight;
}
}
}
/// <summary>
/// Gets or sets the cohesion to the flock weight.
/// </summary>
public float cohesionWeight
{
get { return _cohesionWeight; }
set
{
_cohesionWeight = value;
foreach(var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
blendedSteerings.Behaviors[1].weight = _cohesionWeight;
}
}
}
/// <summary>
/// Gets or sets the velocityMatch to the flock weight.
/// </summary>
public float velocityMatchWeight
{
get { return _velocityMatchWeight; }
set
{
_velocityMatchWeight = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
blendedSteerings.Behaviors[2].weight = _cohesionWeight;
}
}
}
public float separationAknnVal
{
get { return _separationAknnVal; }
set
{
_separationAknnVal = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[0].behaviour as Separation).aknnApproxVal = _separationAknnVal;
}
}
}
public float separationDistance
{
get { return _separationDistance; }
set
{
_separationDistance = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[0].behaviour as Separation).neighborhoodMaxDistance = _separationDistance;
}
}
}
public float cohesionDistance
{
get { return _cohesionDistance; }
set
{
_cohesionDistance = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[1].behaviour as Cohesion).neighborhoodMaxDistance = _cohesionDistance;
}
}
}
public float velocityMatchDistance
{
get { return _velocityMatchDistance; }
set
{
_velocityMatchDistance = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[2].behaviour as VelocityMatch).neighborhoodMaxDistance = _velocityMatchDistance;
}
}
}
/// <summary>
/// Gets or sets the number of neighbors that 'Separation' takes into account
/// </summary>
public int separationK
{
get { return _separationK; }
set
{
_separationK = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[0].behaviour as Separation).maxNeighborhoodSize = _separationK;
}
}
}
/// <summary>
/// Gets or sets the number of neighbors that 'Cohesion' takes into account
/// </summary>
public int cohesionK
{
get { return _cohesionK; }
set
{
_cohesionK = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[1].behaviour as Cohesion).maxNeighborhoodSize = _cohesionK;
}
}
}
/// <summary>
/// Gets or sets the number of neighbors that 'Velocity Match' takes into account
/// </summary>
public int velocityMatchK
{
get { return _velocityMatchK; }
set
{
_velocityMatchK = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[2].behaviour as VelocityMatch).maxNeighborhoodSize = _velocityMatchK;
}
}
}
public float cohesionAknnVal
{
get { return _cohesionAknnVal; }
set
{
_cohesionAknnVal = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[1].behaviour as Cohesion).aknnApproxVal = _cohesionAknnVal;
}
}
}
public float velocityMatchAknnVal
{
get { return _velocityMatchAknnVal; }
set
{
_velocityMatchAknnVal = value;
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[2].behaviour as VelocityMatch).aknnApproxVal = _velocityMatchAknnVal;
}
}
}
public float CohesionAngle
{
get { return Mathf.Acos(_cohesionMinDotProduct) * Mathf.Rad2Deg * 2; }
set
{
_cohesionMinDotProduct = Mathf.Cos((value * 0.5f) * Mathf.Deg2Rad);
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[1].behaviour as Cohesion).neighborhoodMinDotProduct = _cohesionMinDotProduct;
}
}
}
public float SeparationAngle
{
get { return Mathf.Acos(_separationMinDotProduct) * Mathf.Rad2Deg * 2; }
set
{
_separationMinDotProduct = Mathf.Cos((value * 0.5f) * Mathf.Deg2Rad);
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[0].behaviour as Separation).neighborhoodMinDotProduct = _separationMinDotProduct;
}
}
}
public float VelocityMatchAngle
{
get { return Mathf.Acos(_velMatchMinDotProduct) * Mathf.Rad2Deg * 2; }
set
{
_velMatchMinDotProduct = Mathf.Cos((value * 0.5f) * Mathf.Deg2Rad);
foreach (var entry in entries)
{
var prioritySteering = entry.behavior as PrioritySteering;
var blendedSteerings = prioritySteering.Groups[1] as BlendedSteering;
(blendedSteerings.Behaviors[2].behaviour as VelocityMatch).neighborhoodMinDotProduct = _velMatchMinDotProduct;
}
}
}
public override void GetFlockInfo(out Vector3 center, out Vector3 avgVel)
{
Flock.GetNeighborhoodInfo(flock.Boids, out center, out avgVel);
}
public float boidMaxSpeed
{
set
{
foreach (var entry in entries)
entry.bird.maxSpeed = value;
}
get
{
if (entries.Count == 0)
return float.NaN;
return entries[0].bird.maxSpeed;
}
}
}
| |
namespace XLabs.Platform.Services.Media
{
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using UIKit;
/// <summary>
/// Class MediaPicker.
/// </summary>
public class MediaPicker : IMediaPicker
{
/// <summary>
/// The type image
/// </summary>
internal const string TypeImage = "public.image";
/// <summary>
/// The type movie
/// </summary>
internal const string TypeMovie = "public.movie";
/// <summary>
/// The _picker delegate
/// </summary>
private UIImagePickerControllerDelegate _pickerDelegate;
/// <summary>
/// The _popover
/// </summary>
private UIPopoverController _popover;
/// <summary>
/// Initializes a new instance of the <see cref="MediaPicker"/> class.
/// </summary>
public MediaPicker()
{
IsCameraAvailable = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera);
var availableCameraMedia = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.Camera)
?? new string[0];
var availableLibraryMedia =
UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary) ?? new string[0];
foreach (var type in availableCameraMedia.Concat(availableLibraryMedia))
{
if (type == TypeMovie)
{
IsVideosSupported = true;
}
else if (type == TypeImage)
{
IsPhotosSupported = true;
}
}
}
/// <summary>
/// Gets a value indicating whether this instance is camera available.
/// </summary>
/// <value><c>true</c> if this instance is camera available; otherwise, <c>false</c>.</value>
public bool IsCameraAvailable { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is photos supported.
/// </summary>
/// <value><c>true</c> if this instance is photos supported; otherwise, <c>false</c>.</value>
public bool IsPhotosSupported { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is videos supported.
/// </summary>
/// <value><c>true</c> if this instance is videos supported; otherwise, <c>false</c>.</value>
public bool IsVideosSupported { get; private set; }
/// <summary>
/// Event the fires when media has been selected
/// </summary>
/// <value>The on photo selected.</value>
public EventHandler<MediaPickerArgs> OnMediaSelected { get; set; }
/// <summary>
/// Gets or sets the on error.
/// </summary>
/// <value>The on error.</value>
public EventHandler<MediaPickerErrorArgs> OnError { get; set; }
/// <summary>
/// Select a picture from library.
/// </summary>
/// <param name="options">The storage options.</param>
/// <returns>Task<IMediaFile>.</returns>
/// <exception cref="NotSupportedException"></exception>
public Task<MediaFile> SelectPhotoAsync(CameraMediaStorageOptions options)
{
if (!IsPhotosSupported)
{
throw new NotSupportedException();
}
return GetMediaAsync(UIImagePickerControllerSourceType.PhotoLibrary, TypeImage);
}
/// <summary>
/// Takes the picture.
/// </summary>
/// <param name="options">The storage options.</param>
/// <returns>Task<IMediaFile>.</returns>
/// <exception cref="NotSupportedException">
/// </exception>
public Task<MediaFile> TakePhotoAsync(CameraMediaStorageOptions options)
{
if (!IsPhotosSupported)
{
throw new NotSupportedException();
}
if (!IsCameraAvailable)
{
throw new NotSupportedException();
}
VerifyCameraOptions(options);
return GetMediaAsync(UIImagePickerControllerSourceType.Camera, TypeImage, options);
}
/// <summary>
/// Selects the video asynchronous.
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task<IMediaFile>.</returns>
/// <exception cref="NotSupportedException"></exception>
public Task<MediaFile> SelectVideoAsync(VideoMediaStorageOptions options)
{
if (!IsPhotosSupported)
{
throw new NotSupportedException();
}
return GetMediaAsync(UIImagePickerControllerSourceType.PhotoLibrary, TypeMovie);
}
/// <summary>
/// Takes the video asynchronous.
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task<IMediaFile>.</returns>
/// <exception cref="NotSupportedException">
/// </exception>
public Task<MediaFile> TakeVideoAsync(VideoMediaStorageOptions options)
{
if (!IsVideosSupported)
{
throw new NotSupportedException();
}
if (!IsCameraAvailable)
{
throw new NotSupportedException();
}
//VerifyCameraOptions (options);
return GetMediaAsync(UIImagePickerControllerSourceType.Camera, TypeMovie, options);
}
/// <summary>
/// Gets the media asynchronous.
/// </summary>
/// <param name="sourceType">Type of the source.</param>
/// <param name="mediaType">Type of the media.</param>
/// <param name="options">The options.</param>
/// <returns>Task<MediaFile>.</returns>
/// <exception cref="InvalidOperationException">
/// There's no current active window
/// or
/// Could not find current view controller
/// or
/// Only one operation can be active at at time
/// </exception>
private Task<MediaFile> GetMediaAsync(
UIImagePickerControllerSourceType sourceType,
string mediaType,
MediaStorageOptions options = null)
{
var window = UIApplication.SharedApplication.KeyWindow;
if (window == null)
{
throw new InvalidOperationException("There's no current active window");
}
var viewController = window.RootViewController;
#if __IOS_10__
if (viewController == null || (viewController.PresentedViewController != null && viewController.PresentedViewController.GetType() == typeof(UIAlertController)))
{
window =
UIApplication.SharedApplication.Windows.OrderByDescending(w => w.WindowLevel)
.FirstOrDefault(w => w.RootViewController != null);
if (window == null)
{
throw new InvalidOperationException("Could not find current view controller");
}
viewController = window.RootViewController;
}
#endif
while (viewController.PresentedViewController != null)
{
viewController = viewController.PresentedViewController;
}
var ndelegate = new MediaPickerDelegate(viewController, sourceType, options);
var od = Interlocked.CompareExchange(ref _pickerDelegate, ndelegate, null);
if (od != null)
{
throw new InvalidOperationException("Only one operation can be active at at time");
}
var picker = SetupController(ndelegate, sourceType, mediaType, options);
if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad
&& sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
{
ndelegate.Popover = new UIPopoverController(picker)
{
Delegate = new MediaPickerPopoverDelegate(ndelegate, picker)
};
ndelegate.DisplayPopover();
}
else
{
viewController.PresentViewController(picker, true, null);
}
return ndelegate.Task.ContinueWith(
t =>
{
if (_popover != null)
{
_popover.Dispose();
_popover = null;
}
Interlocked.Exchange(ref _pickerDelegate, null);
return t;
}).Unwrap();
}
/// <summary>
/// Setups the controller.
/// </summary>
/// <param name="mpDelegate">The mp delegate.</param>
/// <param name="sourceType">Type of the source.</param>
/// <param name="mediaType">Type of the media.</param>
/// <param name="options">The options.</param>
/// <returns>MediaPickerController.</returns>
private static MediaPickerController SetupController(
MediaPickerDelegate mpDelegate,
UIImagePickerControllerSourceType sourceType,
string mediaType,
MediaStorageOptions options = null)
{
var picker = new MediaPickerController(mpDelegate) { MediaTypes = new[] { mediaType }, SourceType = sourceType};
if (sourceType == UIImagePickerControllerSourceType.Camera)
{
if (mediaType == TypeImage && options is CameraMediaStorageOptions)
{
picker.CameraDevice = GetCameraDevice(((CameraMediaStorageOptions)options).DefaultCamera);
picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
}
else if (mediaType == TypeMovie && options is VideoMediaStorageOptions)
{
var voptions = (VideoMediaStorageOptions)options;
picker.CameraDevice = GetCameraDevice (voptions.DefaultCamera);
picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video;
picker.VideoQuality = GetQuailty(voptions.Quality);
picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds;
}
}
return picker;
}
/// <summary>
/// Gets the UI camera device.
/// </summary>
/// <param name="device">The device.</param>
/// <returns>UIImagePickerControllerCameraDevice.</returns>
/// <exception cref="NotSupportedException"></exception>
private static UIImagePickerControllerCameraDevice GetCameraDevice(CameraDevice device)
{
switch (device)
{
case CameraDevice.Front:
return UIImagePickerControllerCameraDevice.Front;
case CameraDevice.Rear:
return UIImagePickerControllerCameraDevice.Rear;
default:
throw new NotSupportedException();
}
}
/// <summary>
/// Gets the quailty.
/// </summary>
/// <param name="quality">The quality.</param>
/// <returns>UIImagePickerControllerQualityType.</returns>
private static UIImagePickerControllerQualityType GetQuailty(VideoQuality quality)
{
switch (quality)
{
case VideoQuality.Low:
return UIImagePickerControllerQualityType.Low;
case VideoQuality.Medium:
return UIImagePickerControllerQualityType.Medium;
default:
return UIImagePickerControllerQualityType.High;
}
}
/// <summary>
/// Verifies the options.
/// </summary>
/// <param name="options">The options.</param>
/// <exception cref="ArgumentNullException">options</exception>
/// <exception cref="ArgumentException">options.Directory must be a relative path;options</exception>
private static void VerifyOptions(MediaStorageOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
if (options.Directory != null && Path.IsPathRooted(options.Directory))
{
throw new ArgumentException("options.Directory must be a relative path", "options");
}
}
/// <summary>
/// Verifies the camera options.
/// </summary>
/// <param name="options">The options.</param>
/// <exception cref="ArgumentException">options.Camera is not a member of CameraDevice</exception>
private static void VerifyCameraOptions(CameraMediaStorageOptions options)
{
VerifyOptions(options);
if (!Enum.IsDefined(typeof(CameraDevice), options.DefaultCamera))
{
throw new ArgumentException("options.Camera is not a member of CameraDevice");
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedAdapter
{
using System;
using System.Collections.Generic;
using Microsoft.Protocols.TestSuites.Common;
/// <summary>
/// This class specifies a kind of request.
/// </summary>
public class FsshttpbCellRequest : IFSSHTTPBSerializable
{
/// <summary>
/// This user agent guid is used by the test suite.
/// </summary>
public static readonly Guid UserAgentGuid = new Guid("E731B87E-DD45-44AA-AB80-0C75FBD1530E");
/// <summary>
/// Initializes a new instance of the FsshttpbCellRequest class
/// </summary>
public FsshttpbCellRequest()
{
this.IsRequestHashingOptionsUsed = false;
}
/// <summary>
/// Gets or sets Protocol Version (2bytes): An unsigned integer that specifies the protocol schema version number used in this request. This value MUST be 12.
/// </summary>
public ushort ProtocolVersion { get; set; }
/// <summary>
/// Gets or sets Minimum Version (2 bytes): An unsigned integer that specifies the oldest version of the protocol schema that this schema is compatible with. This value MUST be 11.
/// </summary>
public ushort MinimumVersion { get; set; }
/// <summary>
/// Gets or sets Signature (8 bytes): An unsigned integer that specifies a constant signature, to identify this as a request. This MUST be set to 0x9B069439F329CF9C.
/// </summary>
public ulong Signature { get; set; }
/// <summary>
/// Gets or sets GUID (16 bytes): A GUID that specifies the user agent.
/// </summary>
public System.Guid GUID { get; set; }
/// <summary>
/// Gets or sets Version (4 bytes): An unsigned integer that specifies the version of the client.
/// </summary>
public uint Version { get; set; }
/// <summary>
/// Gets or sets Request Hashing Schema: A compact unsigned 64-bit integer that specifies the Hashing Schema being requested that must be set to 1 indicating Content Information Data Structure Version 1.0 as specified in [MS-PCCRC].
/// If the IsRequestHashingOptionsUsed is false, this property will be ignored.
/// </summary>
public Compact64bitInt RequestHashingSchema { get; set; }
/// <summary>
/// Gets or sets Reserved (1 bit): A reserved bit that MUST be set to zero and MUST be ignored.
/// If the IsRequestHashingOptionsUsed is false, this property will be ignored.
/// </summary>
public int Reserve1 { get; set; }
/// <summary>
/// Gets or sets Reserved (1 bit): A reserved bit that MUST be set to zero and MUST be ignored.
/// If the IsRequestHashingOptionsUsed is false, this property will be ignored.
/// </summary>
public int Reserve2 { get; set; }
/// <summary>
/// Gets or sets Request Data Element Hashes Instead of Data (1 bit): If set, a bit that specifies to exclude object data and instead return data element hashes; otherwise, object data is included.
/// If the IsRequestHashingOptionsUsed is false, this property will be ignored.
/// </summary>
public int RequestDataElementHashesInsteadofData { get; set; }
/// <summary>
/// Gets or sets Request Data Element Hashes (1 bit): If set, a bit that specifies to include data element hashes (if available) when returning data elements; otherwise data element hashes should not be returned. If data element hashes are returned they MUST be encoded in the schema specified by Request Hashing Schema.
/// If the IsRequestHashingOptionsUsed is false, this property will be ignored.
/// </summary>
public int RequestDataElementHashes { get; set; }
/// <summary>
/// Gets or sets Reserved (4 bits): A reserved bit that MUST be set to zero and MUST be ignored.
/// If the IsRequestHashingOptionsUsed is false, this property will be ignored.
/// </summary>
public int Reserve3 { get; set; }
/// <summary>
/// Gets or sets Sub-requests
/// </summary>
public List<FsshttpbCellSubRequest> SubRequests { get; set; }
/// <summary>
/// Gets or sets Data Element Package
/// </summary>
public DataElementPackage DataElementPackage { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the request hash options declaration is specified.
/// </summary>
public bool IsRequestHashingOptionsUsed { get; set; }
/// <summary>
/// Gets or sets Cell Request End
/// </summary>
internal StreamObjectHeaderEnd16bit CellRequestEnd { get; set; }
/// <summary>
/// Gets or sets Request Start (4 bytes): A 32-bit stream object header that specifies a request start.
/// </summary>
internal StreamObjectHeaderStart32bit RequestStart { get; set; }
/// <summary>
/// Gets or sets User Agent Start (4 bytes): A 32-bit stream object header that specifies a user agent start.
/// </summary>
internal StreamObjectHeaderStart32bit UserAgentStart { get; set; }
/// <summary>
/// Gets or sets User Agent GUID (4 bytes): A 32-bit stream object header that specifies a user agent GUID.
/// </summary>
internal StreamObjectHeaderStart32bit UserAgentGUID { get; set; }
/// <summary>
/// Gets or sets User Agent Version (4 bytes): A 32-bit stream object header that specifies a user agent version.
/// </summary>
internal StreamObjectHeaderStart32bit UserAgentVersion { get; set; }
/// <summary>
/// Gets or sets User Agent End (2 bytes): A 16-bit stream object header that specifies a user agent end.
/// </summary>
internal StreamObjectHeaderEnd16bit UserAgentEnd { get; set; }
/// <summary>
/// Gets or sets Request Hashing Options Declaration: A 32-bit stream object header that specifies a request hashing options declaration.
/// </summary>
internal StreamObjectHeaderStart RequestHashingOptionsDeclaration { get; set; }
/// <summary>
/// This method is used to convert the element into a byte List
/// </summary>
/// <returns>Return the Byte List</returns>
public List<byte> SerializeToByteList()
{
this.RequestStart = new StreamObjectHeaderStart32bit(StreamObjectTypeHeaderStart.Request, 0);
this.UserAgentStart = new StreamObjectHeaderStart32bit(StreamObjectTypeHeaderStart.UserAgent, 0);
this.UserAgentGUID = new StreamObjectHeaderStart32bit(StreamObjectTypeHeaderStart.UserAgentGUID, 16);
this.UserAgentVersion = new StreamObjectHeaderStart32bit(StreamObjectTypeHeaderStart.UserAgentversion, 4);
this.UserAgentEnd = new StreamObjectHeaderEnd16bit((int)StreamObjectTypeHeaderEnd.UserAgent);
this.CellRequestEnd = new StreamObjectHeaderEnd16bit((int)StreamObjectTypeHeaderEnd.Request);
List<byte> byteList = new List<byte>();
// Protocol Version
byteList.AddRange(LittleEndianBitConverter.GetBytes(this.ProtocolVersion));
// Minimum Version
byteList.AddRange(LittleEndianBitConverter.GetBytes(this.MinimumVersion));
// Signature
byteList.AddRange(LittleEndianBitConverter.GetBytes(this.Signature));
// Request Start
byteList.AddRange(this.RequestStart.SerializeToByteList());
// User Agent Start
byteList.AddRange(this.UserAgentStart.SerializeToByteList());
// User Agent GUID
byteList.AddRange(this.UserAgentGUID.SerializeToByteList());
// GUID
byteList.AddRange(this.GUID.ToByteArray());
// User Agent Version
byteList.AddRange(this.UserAgentVersion.SerializeToByteList());
// Version
byteList.AddRange(LittleEndianBitConverter.GetBytes(this.Version));
// User Agent End
byteList.AddRange(this.UserAgentEnd.SerializeToByteList());
if (this.IsRequestHashingOptionsUsed)
{
List<byte> hashSchemaList = this.RequestHashingSchema.SerializeToByteList();
this.RequestHashingOptionsDeclaration = new StreamObjectHeaderStart32bit(StreamObjectTypeHeaderStart.RequestHashOptions, hashSchemaList.Count + 1);
// Request Hashing Options Declaration
byteList.AddRange(this.RequestHashingOptionsDeclaration.SerializeToByteList());
// Request Hashing Schema
byteList.AddRange(hashSchemaList);
// Reserve
BitWriter bw = new BitWriter(1);
bw.AppendInit32(this.Reserve1, 1);
bw.AppendInit32(this.Reserve2, 1);
bw.AppendInit32(this.RequestDataElementHashesInsteadofData, 1);
bw.AppendInit32(this.RequestDataElementHashes, 1);
bw.AppendInit32(this.Reserve3, 4);
byteList.AddRange(bw.Bytes);
}
// Sub-requests
if (this.SubRequests != null && this.SubRequests.Count != 0)
{
foreach (FsshttpbCellSubRequest subRequest in this.SubRequests)
{
byteList.AddRange(subRequest.SerializeToByteList());
}
}
else
{
throw new InvalidOperationException("MUST contain sub request in request structure which is defined in the MS-FSSHTTPB.");
}
// Data Element Package
if (this.DataElementPackage != null)
{
byteList.AddRange(this.DataElementPackage.SerializeToByteList());
}
// Cell Request End
byteList.AddRange(this.CellRequestEnd.SerializeToByteList());
return byteList;
}
/// <summary>
/// This method is used to retrieve the Base64 encoding string.
/// </summary>
/// <returns>Return the Base64 string</returns>
public string ToBase64()
{
return System.Convert.ToBase64String(this.SerializeToByteList().ToArray());
}
/// <summary>
/// Used to add the sub request
/// </summary>
/// <param name="subRequest">Sub request</param>
/// <param name="dataElement">Date elements list</param>
public void AddSubRequest(FsshttpbCellSubRequest subRequest, List<DataElement> dataElement)
{
if (this.SubRequests == null)
{
this.SubRequests = new List<FsshttpbCellSubRequest>();
}
this.SubRequests.Add(subRequest);
// Add the sub-request mapping for further validation usage.
MsfsshttpbSubRequestMapping.Add((int)subRequest.RequestID, subRequest.GetType(), SharedContext.Current.Site);
if (dataElement != null)
{
if (this.DataElementPackage == null)
{
this.DataElementPackage = new DataElementPackage();
}
this.DataElementPackage.DataElements.AddRange(dataElement);
}
}
}
}
| |
// Copyright (c) 2007-2012 Michael Chapman
// http://ipaddresscontrollib.googlecode.com
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Drawing;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace IPAddressControlLib
{
internal class FieldControl : TextBox
{
#region Public Constants
public const byte MinimumValue = 0;
public const byte MaximumValue = 255;
#endregion // Public Constants
#region Public Events
public event EventHandler<CedeFocusEventArgs> CedeFocusEvent;
public event EventHandler<PasteEventArgs> PasteEvent;
public event EventHandler<TextChangedEventArgs> TextChangedEvent;
#endregion // Public Events
#region Public Properties
public bool Blank
{
get { return ( TextLength == 0 ); }
}
public int FieldIndex
{
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public override Size MinimumSize
{
get
{
Graphics g = Graphics.FromHwnd( Handle );
Size minimumSize = TextRenderer.MeasureText( g,
Properties.Resources.FieldMeasureText, Font, Size,
_textFormatFlags );
g.Dispose();
return minimumSize;
}
}
public byte RangeLower
{
get { return _rangeLower; }
set
{
if ( value < MinimumValue )
{
_rangeLower = MinimumValue;
}
else if ( value > _rangeUpper )
{
_rangeLower = _rangeUpper;
}
else
{
_rangeLower = value;
}
if ( Value < _rangeLower )
{
Text = _rangeLower.ToString( CultureInfo.InvariantCulture );
}
}
}
public byte RangeUpper
{
get { return _rangeUpper; }
set
{
if ( value < _rangeLower )
{
_rangeUpper = _rangeLower;
}
else if ( value > MaximumValue )
{
_rangeUpper = MaximumValue;
}
else
{
_rangeUpper = value;
}
if ( Value > _rangeUpper )
{
Text = _rangeUpper.ToString( CultureInfo.InvariantCulture );
}
}
}
public byte Value
{
get
{
byte result;
if ( !Byte.TryParse( Text, out result ) )
{
result = RangeLower;
}
return result;
}
}
#endregion // Public Properties
#region Public Methods
public void TakeFocus( Action action )
{
Focus();
switch ( action )
{
case Action.Trim:
if ( TextLength > 0 )
{
int newLength = TextLength - 1;
base.Text = Text.Substring( 0, newLength );
}
SelectionStart = TextLength;
return;
case Action.Home:
SelectionStart = 0;
SelectionLength = 0;
return;
case Action.End:
SelectionStart = TextLength;
return;
}
}
public void TakeFocus( Direction direction, Selection selection )
{
Focus();
if ( selection == Selection.All )
{
SelectionStart = 0;
SelectionLength = TextLength;
}
else
{
SelectionStart = ( direction == Direction.Forward ) ? 0 : TextLength;
}
}
public override string ToString()
{
return Value.ToString( CultureInfo.InvariantCulture );
}
#endregion // Public Methods
#region Constructors
public FieldControl()
{
BorderStyle = BorderStyle.None;
MaxLength = 3;
Size = MinimumSize;
TabStop = false;
TextAlign = HorizontalAlignment.Center;
}
#endregion //Constructors
#region Protected Methods
protected override void OnKeyDown( KeyEventArgs e )
{
if ( null == e ) { throw new ArgumentNullException( "e" ); }
base.OnKeyDown( e );
switch ( e.KeyCode )
{
case Keys.Home:
SendCedeFocusEvent( Action.Home );
return;
case Keys.End:
SendCedeFocusEvent( Action.End );
return;
}
if ( IsCedeFocusKey( e ) )
{
SendCedeFocusEvent( Direction.Forward, Selection.All );
e.SuppressKeyPress = true;
return;
}
else if ( IsForwardKey( e ) )
{
if ( e.Control )
{
SendCedeFocusEvent( Direction.Forward, Selection.All );
return;
}
else if ( SelectionLength == 0 && SelectionStart == TextLength )
{
SendCedeFocusEvent( Direction.Forward, Selection.None );
return;
}
}
else if ( IsReverseKey( e ) )
{
if ( e.Control )
{
SendCedeFocusEvent( Direction.Reverse, Selection.All );
return;
}
else if ( SelectionLength == 0 && SelectionStart == 0 )
{
SendCedeFocusEvent( Direction.Reverse, Selection.None );
return;
}
}
else if ( IsBackspaceKey( e ) )
{
HandleBackspaceKey( e );
}
else if ( !IsNumericKey( e ) &&
!IsEditKey( e ) &&
!IsEnterKey( e ) )
{
e.SuppressKeyPress = true;
}
}
protected override void OnParentBackColorChanged( EventArgs e )
{
base.OnParentBackColorChanged( e );
BackColor = Parent.BackColor;
}
protected override void OnParentForeColorChanged( EventArgs e )
{
base.OnParentForeColorChanged( e );
ForeColor = Parent.ForeColor;
}
protected override void OnSizeChanged( EventArgs e )
{
base.OnSizeChanged( e );
Size = MinimumSize;
}
protected override void OnTextChanged( EventArgs e )
{
base.OnTextChanged( e );
if ( !Blank )
{
int value;
if ( !Int32.TryParse( Text, out value ) )
{
base.Text = String.Empty;
}
else
{
if ( value > RangeUpper )
{
base.Text = RangeUpper.ToString( CultureInfo.InvariantCulture );
SelectionStart = 0;
}
else if ( ( TextLength == MaxLength ) && ( value < RangeLower ) )
{
base.Text = RangeLower.ToString( CultureInfo.InvariantCulture );
SelectionStart = 0;
}
else
{
int originalLength = TextLength;
int newSelectionStart = SelectionStart;
base.Text = value.ToString( CultureInfo.InvariantCulture );
if ( TextLength < originalLength )
{
newSelectionStart -= ( originalLength - TextLength );
SelectionStart = Math.Max( 0, newSelectionStart );
}
}
}
}
if ( null != TextChangedEvent )
{
TextChangedEventArgs args = new TextChangedEventArgs();
args.FieldIndex = FieldIndex;
args.Text = Text;
TextChangedEvent( this, args );
}
if ( TextLength == MaxLength && Focused && SelectionStart == TextLength )
{
SendCedeFocusEvent( Direction.Forward, Selection.All );
}
}
protected override void OnValidating( System.ComponentModel.CancelEventArgs e )
{
base.OnValidating( e );
if ( !Blank )
{
if ( Value < RangeLower )
{
Text = RangeLower.ToString( CultureInfo.InvariantCulture );
}
}
}
protected override void WndProc( ref Message m )
{
switch ( m.Msg )
{
case 0x0302: // WM_PASTE
if ( OnPaste() )
{
return;
}
break;
}
base.WndProc( ref m );
}
#endregion // Protected Methods
#region Private Methods
private void HandleBackspaceKey( KeyEventArgs e )
{
if ( !ReadOnly && ( TextLength == 0 || ( SelectionStart == 0 && SelectionLength == 0 ) ) )
{
SendCedeFocusEvent( Action.Trim );
e.SuppressKeyPress = true;
}
}
private static bool IsBackspaceKey( KeyEventArgs e )
{
if ( e.KeyCode == Keys.Back )
{
return true;
}
return false;
}
private bool IsCedeFocusKey( KeyEventArgs e )
{
if ( e.KeyCode == Keys.OemPeriod ||
e.KeyCode == Keys.Decimal ||
e.KeyCode == Keys.Space )
{
if ( TextLength != 0 && SelectionLength == 0 && SelectionStart != 0 )
{
return true;
}
}
return false;
}
private static bool IsEditKey( KeyEventArgs e )
{
if ( e.KeyCode == Keys.Back ||
e.KeyCode == Keys.Delete )
{
return true;
}
else if ( e.Modifiers == Keys.Control &&
( e.KeyCode == Keys.C ||
e.KeyCode == Keys.V ||
e.KeyCode == Keys.X ) )
{
return true;
}
return false;
}
private static bool IsEnterKey( KeyEventArgs e )
{
if ( e.KeyCode == Keys.Enter ||
e.KeyCode == Keys.Return )
{
return true;
}
return false;
}
private static bool IsForwardKey( KeyEventArgs e )
{
if ( e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down )
{
return true;
}
return false;
}
private static bool IsInteger( string text )
{
Match match = Regex.Match( text, @"^[0-9]+$" );
return match.Success;
}
private static bool IsNumericKey( KeyEventArgs e )
{
if ( e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 )
{
if ( e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9 )
{
return false;
}
}
return true;
}
private static bool IsReverseKey( KeyEventArgs e )
{
if ( e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Up )
{
return true;
}
return false;
}
private bool OnPaste()
{
if ( Clipboard.ContainsText() )
{
string text = Clipboard.GetText();
if ( IsInteger( text ) )
{
return false; // handle locally
}
else
{
if ( null != PasteEvent )
{
PasteEventArgs args = new PasteEventArgs();
args.FieldIndex = FieldIndex;
args.Text = text;
PasteEvent( this, args );
return true; // let parent handle it
}
}
}
return false;
}
private void SendCedeFocusEvent( Action action )
{
if ( null != CedeFocusEvent )
{
CedeFocusEventArgs args = new CedeFocusEventArgs();
args.FieldIndex = FieldIndex;
args.Action = action;
CedeFocusEvent( this, args );
}
}
private void SendCedeFocusEvent( Direction direction, Selection selection )
{
if ( null != CedeFocusEvent )
{
CedeFocusEventArgs args = new CedeFocusEventArgs();
args.FieldIndex = FieldIndex;
args.Action = Action.None;
args.Direction = direction;
args.Selection = selection;
CedeFocusEvent( this, args );
}
}
#endregion // Private Methods
#region Private Data
private int _fieldIndex = -1;
private byte _rangeLower; // = MinimumValue; // this is removed for FxCop approval
private byte _rangeUpper = MaximumValue;
private TextFormatFlags _textFormatFlags = TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine | TextFormatFlags.NoPadding;
#endregion // Private Data
}
internal enum Direction
{
Forward,
Reverse
}
internal enum Selection
{
None,
All
}
internal enum Action
{
None,
Trim,
Home,
End
}
internal class CedeFocusEventArgs : EventArgs
{
private int _fieldIndex;
private Action _action;
private Direction _direction;
private Selection _selection;
public int FieldIndex
{
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public Action Action
{
get { return _action; }
set { _action = value; }
}
public Direction Direction
{
get { return _direction; }
set { _direction = value; }
}
public Selection Selection
{
get { return _selection; }
set { _selection = value; }
}
}
internal class PasteEventArgs : EventArgs
{
private int _fieldIndex;
private String _text;
public int FieldIndex
{
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "FieldIndex may be useful if an error callout is displayed in the future." )]
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public String Text
{
get { return _text; }
set { _text = value; }
}
}
internal class TextChangedEventArgs : EventArgs
{
private int _fieldIndex;
private String _text;
public int FieldIndex
{
get { return _fieldIndex; }
set { _fieldIndex = value; }
}
public String Text
{
get { return _text; }
set { _text = value; }
}
}
}
| |
// Copyright 2006 Herre Kuijpers - <herre@xs4all.nl>
//
// This source file(s) may be redistributed, altered and customized
// by any means PROVIDING the authors name and all copyright
// notices remain intact.
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO
// LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE.
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace Xnlab.SQLMon.Controls.OutlookGrid
{
#region implementation of the OutlookGrid!
public partial class OutlookGrid : DataGridView
{
#region OutlookGrid constructor
public OutlookGrid()
{
InitializeComponent();
// very important, this indicates that a new default row class is going to be used to fill the grid
// in this case our custom OutlookGridRow class
base.RowTemplate = new OutlookGridRow();
this._groupTemplate = new OutlookgGridDefaultGroup();
}
#endregion OutlookGrid constructor
#region OutlookGrid property definitions
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new DataGridViewRow RowTemplate
{
get { return base.RowTemplate;}
}
private IOutlookGridGroup _groupTemplate;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IOutlookGridGroup GroupTemplate
{
get
{
return _groupTemplate;
}
set
{
_groupTemplate = value;
}
}
private Image _iconCollapse;
[Category("Appearance")]
public Image CollapseIcon
{
get { return _iconCollapse; }
set { _iconCollapse = value; }
}
private Image _iconExpand;
[Category("Appearance")]
public Image ExpandIcon
{
get { return _iconExpand; }
set { _iconExpand = value; }
}
private DataSourceManager _dataSource;
public new object DataSource
{
get
{
if (_dataSource == null) return null;
// special case, datasource is bound to itself.
// for client it must look like no binding is set,so return null in this case
if (_dataSource.DataSource.Equals(this)) return null;
// return the origional datasource.
return _dataSource.DataSource;
}
}
#endregion OutlookGrid property definitions
#region OutlookGrid new methods
public void CollapseAll()
{
SetGroupCollapse(true);
}
public void ExpandAll()
{
SetGroupCollapse(false);
}
public void ClearGroups()
{
_dataSource = null;
_groupTemplate.Column = null; //reset
//FillGrid(null);
}
public void BindData(object dataSource, string dataMember)
{
this.DataMember = DataMember;
if (dataSource == null)
{
this._dataSource = null;
Columns.Clear();
}
else
{
this._dataSource = new DataSourceManager(dataSource, dataMember);
SetupColumns();
FillGrid(null);
}
}
public override void Sort(IComparer comparer)
{
if (_dataSource == null) // if no datasource is set, then bind to the grid itself
_dataSource = new DataSourceManager(this, null);
_dataSource.Sort(comparer);
FillGrid(_groupTemplate);
}
public override void Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction)
{
if (dataGridViewColumn == null)
return;
if (_dataSource == null) // if no datasource is set, then bind to the grid itself
_dataSource = new DataSourceManager(this, null);
_dataSource.Sort(new OutlookGridRowComparer(dataGridViewColumn.Index, direction));
FillGrid(_groupTemplate);
}
#endregion OutlookGrid new methods
#region OutlookGrid event handlers
protected override void OnCellBeginEdit(DataGridViewCellCancelEventArgs e)
{
var row = (OutlookGridRow)base.Rows[e.RowIndex];
if (row.IsGroupRow)
e.Cancel = true;
else
base.OnCellBeginEdit(e);
}
protected override void OnCellDoubleClick(DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
var row = (OutlookGridRow)base.Rows[e.RowIndex];
if (row.IsGroupRow)
{
row.Group.Collapsed = !row.Group.Collapsed;
//this is a workaround to make the grid re-calculate it's contents and backgroun bounds
// so the background is updated correctly.
// this will also invalidate the control, so it will redraw itself
row.Visible = false;
row.Visible = true;
return;
}
}
base.OnCellClick(e);
}
// the OnCellMouseDown is overriden so the control can check to see if the
// user clicked the + or - sign of the group-row
protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex < 0)
{
base.OnCellMouseDown(e);
return;
}
var row = (OutlookGridRow)base.Rows[e.RowIndex];
if (row.IsGroupRow && row.IsIconHit(e))
{
Debug.WriteLine("OnCellMouseDown " + DateTime.Now.Ticks.ToString());
row.Group.Collapsed = !row.Group.Collapsed;
//this is a workaround to make the grid re-calculate it's contents and backgroun bounds
// so the background is updated correctly.
// this will also invalidate the control, so it will redraw itself
row.Visible = false;
row.Visible = true;
}
else
base.OnCellMouseDown(e);
}
#endregion OutlookGrid event handlers
#region Grid Fill functions
private void SetGroupCollapse(bool collapsed)
{
if (Rows.Count == 0) return;
if (_groupTemplate == null) return;
// set the default grouping style template collapsed property
_groupTemplate.Collapsed = collapsed;
// loop through all rows to find the GroupRows
foreach (OutlookGridRow row in Rows)
{
if (row.IsGroupRow)
row.Group.Collapsed = collapsed;
}
// workaround, make the grid refresh properly
Rows[0].Visible = !Rows[0].Visible;
Rows[0].Visible = !Rows[0].Visible;
}
private void SetupColumns()
{
ArrayList list;
// clear all columns, this is a somewhat crude implementation
// refinement may be welcome.
Columns.Clear();
// start filling the grid
if (_dataSource == null)
return;
else
list = _dataSource.Rows;
if (list.Count <= 0) return;
foreach (string c in _dataSource.Columns)
{
int index;
var column = Columns[c];
if (column == null)
index = Columns.Add(c, c);
else
index = column.Index;
Columns[index].SortMode = DataGridViewColumnSortMode.Programmatic; // always programmatic!
}
}
/// <summary>
/// the fill grid method fills the grid with the data from the DataSourceManager
/// It takes the grouping style into account, if it is set.
/// </summary>
private void FillGrid(IOutlookGridGroup groupingStyle)
{
ArrayList list;
OutlookGridRow row;
this.Rows.Clear();
// start filling the grid
if (_dataSource == null)
return;
else
list = _dataSource.Rows;
if (list.Count <= 0) return;
// this block is used of grouping is turned off
// this will simply list all attributes of each object in the list
if (groupingStyle == null)
{
foreach (DataSourceRow r in list)
{
row = (OutlookGridRow) this.RowTemplate.Clone();
foreach (var val in r)
{
DataGridViewCell cell = new DataGridViewTextBoxCell();
cell.Value = val.ToString();
row.Cells.Add(cell);
}
Rows.Add(row);
}
}
// this block is used when grouping is used
// items in the list must be sorted, and then they will automatically be grouped
else
{
IOutlookGridGroup groupCur = null;
object result = null;
var counter = 0; // counts number of items in the group
foreach (DataSourceRow r in list)
{
row = (OutlookGridRow)this.RowTemplate.Clone();
result = r[groupingStyle.Column.Index];
if (groupCur != null && groupCur.CompareTo(result) == 0) // item is part of the group
{
row.Group = groupCur;
counter++;
}
else // item is not part of the group, so create new group
{
if (groupCur != null)
groupCur.ItemCount = counter;
groupCur = (IOutlookGridGroup)groupingStyle.Clone(); // init
groupCur.Value = result;
row.Group = groupCur;
row.IsGroupRow = true;
row.Height = groupCur.Height;
row.CreateCells(this, groupCur.Value);
Rows.Add(row);
// add content row after this
row = (OutlookGridRow)this.RowTemplate.Clone();
row.Group = groupCur;
counter = 1; // reset counter for next group
}
foreach (var obj in r)
{
DataGridViewCell cell = new DataGridViewTextBoxCell();
cell.Value = obj.ToString();
row.Cells.Add(cell);
}
Rows.Add(row);
groupCur.ItemCount = counter;
}
}
}
#endregion Grid Fill functions
}
#endregion implementation of the OutlookGrid!
}
| |
using UnityEngine;
using System.Collections;
public class Gamescript : MonoBehaviour
{
#region holder
// if (Input.GetKey (KeyCode.P)) {
// clone = Instantiate (projectile, new Vector3 (-24, 1, z1), transform.rotation) as Rigidbody;
// clone.rigidbody.AddForce (transform.right * Random.Range (8000, 9000));
// clone = Instantiate (projectile, new Vector3 (24, 1, z1), transform.rotation) as Rigidbody;
// clone.rigidbody.AddForce (-transform.right * Random.Range (8000, 9000));
// if (scoreUp) {
// GameObject other = GameObject.Find ("ball(Clone)");
// Destroy (other);
// } else {
// Destroy (clone.gameObject, removeTime);
// }
// }
// if (Input.GetKey (KeyCode.O)) {
// // Destroy(clone.gameObject);
// GameObject other = GameObject.Find ("ball(Clone)");
// Destroy (other);
// }
#endregion
string gameState = mainmenu.gameState;
bool Master = LanMasterGui.Master;
bool Slave = LanMasterGui.Slave;
public GameObject ball, schieter1, schieter2, driehoek, ster;
public Rigidbody projectile;
Rigidbody clone;
float removeTime = 5f;
int Ammo1 = 5;
int Ammo2 = 5;
bool Ammo1empty;
bool Ammo2empty;
int score;
public GameObject[] clones;
int score1 = 0;
int score2 = 0;
float schieterSpeed = 0.2f;
public GUIText AmmoDisplay1, AmmoDisplay2, ScoreDisplay;
bool has1Fired = false;
bool has2Fired = false;
bool scoreUp = false;
float z1 = 0;
float z2 = 0;
public void ResetOnScore ()
{
if (score == 1)
score1++;
if (score == 2)
score2++;
z1 = 0;
z2 = 0;
ster.transform.position = new Vector3 (0f, 0.6f, 8f);
ster.transform.rotation = Quaternion.Euler (0f, 0f, 0f);
ster.rigidbody.velocity = Vector3.zero;
ster.rigidbody.angularVelocity = Vector3.zero;
driehoek.transform.position = new Vector3 (0f, 0.6f, -8f);
driehoek.transform.rotation = Quaternion.Euler (-90f, -30f, 0f);
driehoek.rigidbody.velocity = Vector3.zero;
driehoek.rigidbody.angularVelocity = Vector3.zero;
score = 0;
}
void PlayerControl ()
{
#region PlayerOne
schieter1.transform.position = new Vector3 (-22.5f, 0.25f, z1);
if (Input.GetKey (KeyCode.W)) {
z1 += schieterSpeed;
}
if (Input.GetKey (KeyCode.S)) {
z1 -= schieterSpeed;
}
if (Ammo1empty == false) {
if (has1Fired == false) {
if (Input.GetKeyDown (KeyCode.D)) {
clone = Instantiate (projectile, new Vector3 (-24, 1, z1), transform.rotation) as Rigidbody;
clone.rigidbody.AddForce (transform.right * Random.Range (8000, 9000));
if (scoreUp) {
Destroy (clone.gameObject);
} else {
Destroy (clone.gameObject, removeTime);
}
has1Fired = true;
}
}
if (Input.GetKeyUp (KeyCode.D)) {
has1Fired = false;
Ammo1--;
}
if (Ammo1 == 0) {
Ammo1empty = true;
}
if (Ammo1 < 5) {
if (Input.GetKeyDown (KeyCode.A)) {
Ammo1 += 1;
Ammo1empty = false;
}
}
}
#endregion
#region OfflinePlay
if (gameState == "OfflinePlay") {
schieter2.transform.position = new Vector3 (22.5f, 0.25f, z2);
if (Input.GetKey (KeyCode.UpArrow)) {
z2 += schieterSpeed;
}
if (Input.GetKey (KeyCode.DownArrow)) {
z2 -= schieterSpeed;
}
if (Ammo2empty == false) {
if (has2Fired == false) {
if (Input.GetKeyDown (KeyCode.LeftArrow)) {
clone = Instantiate (projectile, new Vector3 (24, 1, z2), transform.rotation) as Rigidbody;
clone.rigidbody.AddForce (-transform.right * Random.Range (8000, 9000));
if (scoreUp) {
Destroy (clone.gameObject);
} else {
Destroy (clone.gameObject, removeTime);
}
has2Fired = true;
}
}
if (Input.GetKeyUp (KeyCode.LeftArrow)) {
has2Fired = false;
Ammo2--;
}
}
if (Ammo2 == 0) {
Ammo2empty = true;
}
if (Ammo2 < 5) {
if (Input.GetKeyDown (KeyCode.RightArrow)) {
Ammo2 += 1;
Ammo2empty = false;
}
}
}
#endregion
#region MovementBoundarys
if (z1 > 11.5) {
z1 -= schieterSpeed;
}
if (z1 < -11.5) {
z1 += schieterSpeed;
}
if (z2 > 11.5) {
z2 -= schieterSpeed;
}
if (z2 < -11.5) {
z2 += schieterSpeed;
}
#endregion
}
void Interface ()
{
if (Input.GetKey (KeyCode.Escape)) {
Application.LoadLevel ("MainMenu");
}
AmmoDisplay1.text = "" + Ammo1;
AmmoDisplay2.text = "" + Ammo2;
ScoreDisplay.text = score1 + " - " + score2;
}
void Update ()
{
PlayerControl ();
Interface ();
bool Master = LanMasterGui.Master;
bool Slave = LanMasterGui.Slave;
//////////LANPLAY//////////
if (Master == true) {
schieter1.transform.position = new Vector3 (-22.5f, 0.25f, z1);
if (Input.GetKey (KeyCode.W)) {
z1 += schieterSpeed;
}
if (Input.GetKey (KeyCode.S)) {
z1 -= schieterSpeed;
}
if (Ammo1 == 0) {
Ammo1empty = true;
}
if (Ammo1 < 5) {
if (Input.GetKeyDown (KeyCode.RightArrow)) {
Ammo1 += 1;
Ammo1empty = false;
}
}
}
if (Slave == true) {
schieter2.transform.position = new Vector3 (22.5f, 0.25f, z2);
if (Input.GetKey (KeyCode.UpArrow)) {
z2 += schieterSpeed;
}
if (Input.GetKey (KeyCode.DownArrow)) {
z2 -= schieterSpeed;
}
if (Ammo2 == 0) {
Ammo2empty = true;
}
if (Ammo2 < 5) {
if (Input.GetKeyDown (KeyCode.RightArrow)) {
Ammo2 += 1;
Ammo2empty = false;
}
}
}
if (Input.GetKey (KeyCode.P)) {
clone = Instantiate (projectile, new Vector3 (-24, 1, z1), transform.rotation) as Rigidbody;
clone.rigidbody.AddForce (transform.right * Random.Range (8000, 9000));
clone = Instantiate (projectile, new Vector3 (24, 1, z1), transform.rotation) as Rigidbody;
clone.rigidbody.AddForce (-transform.right * Random.Range (8000, 9000));
if (scoreUp) {
GameObject other = GameObject.Find ("ball(Clone)");
Destroy (other);
} else {
Destroy (clone.gameObject, removeTime);
}
if (driehoek.transform.position.x > 20f || ster.transform.position.x > 20.5f) {
score = 1;
ResetOnScore ();
}
if (driehoek.transform.position.x < -20f || ster.transform.position.x < -20.5f) {
score = 2;
ResetOnScore ();
}
}
}
}
| |
using System;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Linq;
using Marten.Schema.Identity;
using Marten.Services;
using Marten.Services.Deletes;
using Marten.Util;
using Npgsql;
using NpgsqlTypes;
namespace Marten.Schema
{
public class Resolver<T> : IResolver<T>, IDocumentStorage, IDocumentUpsert where T : class
{
private readonly string _deleteSql;
private readonly Func<T, object> _identity;
private readonly string _loadArraySql;
private readonly string _loaderSql;
private readonly ISerializer _serializer;
private readonly DocumentMapping _mapping;
private readonly FunctionName _upsertName;
private readonly Action<SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid> _sprocWriter;
public Resolver(ISerializer serializer, DocumentMapping mapping)
{
_serializer = serializer;
_mapping = mapping;
IdType = TypeMappings.ToDbType(mapping.IdMember.GetMemberType());
_loaderSql =
$"select {_mapping.SelectFields().Join(", ")} from {_mapping.Table.QualifiedName} as d where id = :id";
_deleteSql = $"delete from {_mapping.Table.QualifiedName} where id = :id";
_loadArraySql =
$"select {_mapping.SelectFields().Join(", ")} from {_mapping.Table.QualifiedName} as d where id = ANY(:ids)";
_identity = LambdaBuilder.Getter<T, object>(mapping.IdMember);
_sprocWriter = buildSprocWriter(mapping);
_upsertName = mapping.UpsertFunction;
if (mapping.DeleteStyle == DeleteStyle.Remove)
{
DeleteByIdSql = $"delete from {_mapping.Table.QualifiedName} where id = ?";
DeleteByWhereSql = $"delete from {_mapping.Table.QualifiedName} as d where ?";
}
else
{
DeleteByIdSql = $"update {_mapping.Table.QualifiedName} set {DocumentMapping.DeletedColumn} = True, {DocumentMapping.DeletedAtColumn} = now() where id = ?";
DeleteByWhereSql = $"update {_mapping.Table.QualifiedName} as d set {DocumentMapping.DeletedColumn} = True, {DocumentMapping.DeletedAtColumn} = now() where ?";
}
}
public string DeleteByWhereSql { get; }
public string DeleteByIdSql { get; }
private Action<SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid> buildSprocWriter(DocumentMapping mapping)
{
var call = Expression.Parameter(typeof(SprocCall), "call");
var doc = Expression.Parameter(typeof(T), "doc");
var batch = Expression.Parameter(typeof(UpdateBatch), "batch");
var mappingParam = Expression.Parameter(typeof(DocumentMapping), "mapping");
var currentVersion = Expression.Parameter(typeof(Guid?), "currentVersion");
var newVersion = Expression.Parameter(typeof(Guid), "newVersion");
var arguments = new UpsertFunction(mapping).OrderedArguments().Select(x =>
{
return x.CompileUpdateExpression(_serializer.EnumStorage, call, doc, batch, mappingParam, currentVersion, newVersion);
});
var block = Expression.Block(arguments);
var lambda = Expression.Lambda<Action<SprocCall, T, UpdateBatch, DocumentMapping, Guid?, Guid>>(block,
new ParameterExpression[]
{
call, doc, batch, mappingParam, currentVersion, newVersion
});
return lambda.Compile();
}
public Type DocumentType => _mapping.DocumentType;
public NpgsqlDbType IdType { get; }
public virtual T Resolve(int startingIndex, DbDataReader reader, IIdentityMap map)
{
if (reader.IsDBNull(startingIndex)) return null;
var json = reader.GetString(startingIndex);
var id = reader[startingIndex + 1];
var version = reader.GetFieldValue<Guid>(startingIndex + 2);
return map.Get<T>(id, json, version);
}
public virtual async Task<T> ResolveAsync(int startingIndex, DbDataReader reader, IIdentityMap map,
CancellationToken token)
{
if (await reader.IsDBNullAsync(startingIndex, token).ConfigureAwait(false)) return null;
var json = await reader.GetFieldValueAsync<string>(startingIndex, token).ConfigureAwait(false);
var id = await reader.GetFieldValueAsync<object>(startingIndex + 1, token).ConfigureAwait(false);
var version = await reader.GetFieldValueAsync<Guid>(startingIndex + 2, token).ConfigureAwait(false);
return map.Get<T>(id, json, version);
}
public T Resolve(IIdentityMap map, ILoader loader, object id)
{
return map.Get(id, () => loader.LoadDocument<T>(id));
}
public Task<T> ResolveAsync(IIdentityMap map, ILoader loader, CancellationToken token, object id)
{
return map.GetAsync(id, async tk => await loader.LoadDocumentAsync<T>(id, tk).ConfigureAwait(false), token);
}
public virtual FetchResult<T> Fetch(DbDataReader reader, ISerializer serializer)
{
var found = reader.Read();
if (!found) return null;
var json = reader.GetString(0);
var doc = serializer.FromJson<T>(json);
var version = reader.GetFieldValue<Guid>(2);
return new FetchResult<T>(doc, json, version);
}
public virtual async Task<FetchResult<T>> FetchAsync(DbDataReader reader, ISerializer serializer, CancellationToken token)
{
var found = await reader.ReadAsync(token).ConfigureAwait(false);
if (!found) return null;
var json = await reader.GetFieldValueAsync<string>(0, token).ConfigureAwait(false);
var doc = serializer.FromJson<T>(json);
var version = await reader.GetFieldValueAsync<Guid>(2, token).ConfigureAwait(false);
return new FetchResult<T>(doc, json, version);
}
public NpgsqlCommand LoaderCommand(object id)
{
return new NpgsqlCommand(_loaderSql).With("id", id);
}
public NpgsqlCommand DeleteCommandForId(object id)
{
return new NpgsqlCommand(_deleteSql).With("id", id);
}
public NpgsqlCommand DeleteCommandForEntity(object entity)
{
return DeleteCommandForId(_identity((T) entity));
}
public NpgsqlCommand LoadByArrayCommand<TKey>(TKey[] ids)
{
return new NpgsqlCommand(_loadArraySql).With("ids", ids);
}
public object Identity(object document)
{
return _identity((T) document);
}
public void RegisterUpdate(UpdateBatch batch, object entity)
{
var json = batch.Serializer.ToJson(entity);
RegisterUpdate(batch, entity, json);
}
public void RegisterUpdate(UpdateBatch batch, object entity, string json)
{
var newVersion = CombGuidIdGeneration.NewGuid();
var currentVersion = batch.Versions.Version<T>(Identity(entity));
ICallback callback = null;
if (_mapping.UseOptimisticConcurrency)
{
callback = new OptimisticConcurrencyCallback<T>(Identity(entity), batch.Versions, newVersion, currentVersion);
}
var call = batch.Sproc(_upsertName, callback);
_sprocWriter(call, (T) entity, batch, _mapping, currentVersion, newVersion);
}
public void Remove(IIdentityMap map, object entity)
{
var id = Identity(entity);
map.Remove<T>(id);
}
public void Delete(IIdentityMap map, object id)
{
map.Remove<T>(id);
}
public void Store(IIdentityMap map, object id, object entity)
{
map.Store<T>(id, (T) entity);
}
public IStorageOperation DeletionForId(object id)
{
return new DeleteById(DeleteByIdSql, this, id);
}
public IStorageOperation DeletionForEntity(object entity)
{
return new DeleteById(DeleteByIdSql, this, Identity(entity), entity);
}
public IStorageOperation DeletionForWhere(IWhereFragment @where)
{
return new DeleteWhere(typeof(T), DeleteByWhereSql, @where);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public class MutexTests : RemoteExecutorTestBase
{
private const int FailedWaitTimeout = 30000;
[Fact]
public void Ctor_ConstructWaitRelease()
{
using (Mutex m = new Mutex())
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(false))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
}
using (Mutex m = new Mutex(true))
{
Assert.True(m.WaitOne(FailedWaitTimeout));
m.ReleaseMutex();
m.ReleaseMutex();
}
}
[Fact]
public void Ctor_InvalidName()
{
Assert.Throws<ArgumentException>(() => new Mutex(false, new string('a', 1000)));
}
[Fact]
public void Ctor_ValidName()
{
string name = Guid.NewGuid().ToString("N");
bool createdNew;
using (Mutex m1 = new Mutex(false, name, out createdNew))
{
Assert.True(createdNew);
using (Mutex m2 = new Mutex(false, name, out createdNew))
{
Assert.False(createdNew);
}
}
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore s = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name));
}
}
[Fact]
public void OpenExisting()
{
string name = Guid.NewGuid().ToString("N");
Mutex resultHandle;
Assert.False(Mutex.TryOpenExisting(name, out resultHandle));
using (Mutex m1 = new Mutex(false, name))
{
using (Mutex m2 = Mutex.OpenExisting(name))
{
Assert.True(m1.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m1.ReleaseMutex();
Assert.True(m2.WaitOne(FailedWaitTimeout));
Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
m2.ReleaseMutex();
}
Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
Assert.NotNull(resultHandle);
resultHandle.Dispose();
}
}
[Fact]
public void OpenExisting_InvalidNames()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => Mutex.OpenExisting(null));
Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(string.Empty));
Assert.Throws<ArgumentException>(() => Mutex.OpenExisting(new string('a', 10000)));
}
[Fact]
public void OpenExisting_UnavailableName()
{
string name = Guid.NewGuid().ToString("N");
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
[PlatformSpecific(TestPlatforms.Windows)] // named semaphores aren't supported on Unix
[Fact]
public void OpenExisting_NameUsedByOtherSynchronizationPrimitive_Windows()
{
string name = Guid.NewGuid().ToString("N");
using (Semaphore sema = new Semaphore(1, 1, name))
{
Assert.Throws<WaitHandleCannotBeOpenedException>(() => Mutex.OpenExisting(name));
Mutex ignored;
Assert.False(Mutex.TryOpenExisting(name, out ignored));
}
}
public static IEnumerable<object[]> AbandonExisting_MemberData()
{
var nameGuidStr = Guid.NewGuid().ToString("N");
for (int waitType = 0; waitType < 2; ++waitType) // 0 == WaitOne, 1 == WaitAny
{
yield return new object[] { null, waitType };
foreach (var namePrefix in new[] { string.Empty, "Local\\", "Global\\" })
{
yield return new object[] { namePrefix + nameGuidStr, waitType };
}
}
}
[Theory]
[MemberData(nameof(AbandonExisting_MemberData))]
[ActiveIssue(21151, TargetFrameworkMonikers.Uap)]
public void AbandonExisting(string name, int waitType)
{
using (var m = new Mutex(false, name))
{
Task t = Task.Factory.StartNew(() =>
{
Assert.True(m.WaitOne(FailedWaitTimeout));
// don't release the mutex; abandon it on this thread
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
t.Wait();
switch (waitType)
{
case 0: // WaitOne
Assert.Throws<AbandonedMutexException>(() => m.WaitOne(FailedWaitTimeout));
break;
case 1: // WaitAny
AbandonedMutexException ame = Assert.Throws<AbandonedMutexException>(() => WaitHandle.WaitAny(new[] { m }, FailedWaitTimeout));
Assert.Equal(0, ame.MutexIndex);
Assert.Equal(m, ame.Mutex);
break;
}
}
}
[Theory]
[InlineData("")]
[InlineData("Local\\")]
[InlineData("Global\\")]
[ActiveIssue(21151, TargetFrameworkMonikers.Uap)]
public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix)
{
string mutexName = prefix + Guid.NewGuid().ToString("N");
string fileName = GetTestFilePath();
Func<string, string, int> otherProcess = (m, f) =>
{
using (var mutex = Mutex.OpenExisting(m))
{
mutex.WaitOne();
try { File.WriteAllText(f, "0"); }
finally { mutex.ReleaseMutex(); }
IncrementValueInFileNTimes(mutex, f, 10);
}
return SuccessExitCode;
};
using (var mutex = new Mutex(false, mutexName))
using (var remote = RemoteInvoke(otherProcess, mutexName, $"\"{fileName}\""))
{
SpinWait.SpinUntil(() => File.Exists(fileName));
IncrementValueInFileNTimes(mutex, fileName, 10);
}
Assert.Equal(20, int.Parse(File.ReadAllText(fileName)));
}
private static void IncrementValueInFileNTimes(Mutex mutex, string fileName, int n)
{
for (int i = 0; i < n; i++)
{
mutex.WaitOne();
try
{
int current = int.Parse(File.ReadAllText(fileName));
Thread.Sleep(10);
File.WriteAllText(fileName, (current + 1).ToString());
}
finally { mutex.ReleaseMutex(); }
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Ccr.Core.Extensions;
// ReSharper disable ConvertToAutoPropertyWithPrivateSetter
// ReSharper disable ArrangeAccessorOwnerBody
namespace Ccr.Xaml.Collections
{
public class NotifyCollectionChangedEventArgs<TValue>
: EventArgs
{
private int _newStartingIndex = -1;
private int _oldStartingIndex = -1;
private NotifyCollectionChangedAction _action;
private IList<TValue> _newItems;
private IList<TValue> _oldItems;
/// <summary>Gets the action that caused the event. </summary>
/// <returns>A <see cref="T:System.Collections.Specialized.NotifyCollectionChangedAction" /> value that describes the action that caused the event.</returns>
public NotifyCollectionChangedAction Action
{
get => _action;
}
/// <summary>Gets the list of new items involved in the change.</summary>
/// <returns>The list of new items involved in the change.</returns>
public IList<TValue> NewItems
{
get => _newItems;
}
/// <summary>Gets the list of items affected by a <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" />, Remove, or Move action.</summary>
/// <returns>The list of items affected by a <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" />, Remove, or Move action.</returns>
public IList<TValue> OldItems
{
get => _oldItems;
}
/// <summary>Gets the index at which the change occurred.</summary>
/// <returns>The zero-based index at which the change occurred.</returns>
public int NewStartingIndex
{
get => _newStartingIndex;
}
/// <summary>Gets the index at which a <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Move" />, Remove, or Replace action occurred.</summary>
/// <returns>The zero-based index at which a <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Move" />, Remove, or Replace action occurred.</returns>
public int OldStartingIndex
{
get => _oldStartingIndex;
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" /> change.</summary>
/// <param name="action">The action that caused the event. This must be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" />.</param>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action)
{
if (action != NotifyCollectionChangedAction.Reset)
throw new ArgumentException(
"Wrong Action For Ctor (Reset)",
nameof(action));
InitializeAdd(
action,
null,
-1);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a one-item change.</summary>
/// <param name="action">The action that caused the event. This can be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" />, <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Add" />, or <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Remove" />.</param>
/// <param name="changedItem">The item that is affected by the change.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Reset, Add, or Remove, or if <paramref name="action" /> is Reset and <paramref name="changedItem" /> is not null.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
TValue changedItem)
{
if (action != NotifyCollectionChangedAction.Add
&& action != NotifyCollectionChangedAction.Remove
&& action != NotifyCollectionChangedAction.Reset)
throw new ArgumentException(
"Must Be Reset Add Or Remove Action For Ctor",
nameof(action));
if (action == NotifyCollectionChangedAction.Reset)
{
if (changedItem != null)
throw new ArgumentException(
"ResetActionRequiresNullItem",
nameof(action));
InitializeAdd(
action,
null,
-1);
}
else
InitializeAddOrRemove(
action,
new[] { changedItem },
-1);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a one-item change.</summary>
/// <param name="action">The action that caused the event. This can be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" />, <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Add" />, or <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Remove" />.</param>
/// <param name="changedItem">The item that is affected by the change.</param>
/// <param name="index">The index where the change occurred.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Reset, Add, or Remove, or if <paramref name="action" /> is Reset and either <paramref name="changedItems" /> is not null or <paramref name="index" /> is not -1.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
TValue changedItem,
int index)
{
if (action != NotifyCollectionChangedAction.Add
&& action != NotifyCollectionChangedAction.Remove
&& action != NotifyCollectionChangedAction.Reset)
throw new ArgumentException(
"Must Be Reset Add Or Remove Action For Ctor",
nameof(action));
if (action == NotifyCollectionChangedAction.Reset)
{
if (changedItem != null)
throw new ArgumentException(
"Reset Action Requires Null Item",
nameof(action));
if (index != -1)
throw new ArgumentException(
"Reset Action Requires Index Minus 1",
nameof(action));
InitializeAdd(
action,
null,
-1);
}
else
InitializeAddOrRemove(
action,
new[] { changedItem },
index);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a multi-item change.</summary>
/// <param name="action">The action that caused the event. This can be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" />, <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Add" />, or <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Remove" />.</param>
/// <param name="changedItems">The items that are affected by the change.</param>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
IList<TValue> changedItems)
{
if (action != NotifyCollectionChangedAction.Add
&& action != NotifyCollectionChangedAction.Remove
&& action != NotifyCollectionChangedAction.Reset)
throw new ArgumentException(
"Must Be Reset Add Or Remove Action For Ctor",
nameof(action));
if (action == NotifyCollectionChangedAction.Reset)
{
if (changedItems != null)
throw new ArgumentException(
"Reset Action Requires Null Item",
nameof(action));
InitializeAdd(
action,
null,
-1);
}
else
{
changedItems.IsNotNull(nameof(changedItems));
InitializeAddOrRemove(
action,
changedItems,
-1);
}
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a multi-item change or a <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" /> change.</summary>
/// <param name="action">The action that caused the event. This can be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Reset" />, <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Add" />, or <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Remove" />.</param>
/// <param name="changedItems">The items affected by the change.</param>
/// <param name="startingIndex">The index where the change occurred.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Reset, Add, or Remove, if <paramref name="action" /> is Reset and either <paramref name="changedItems" /> is not null or <paramref name="startingIndex" /> is not -1, or if action is Add or Remove and <paramref name="startingIndex" /> is less than -1.</exception>
/// <exception cref="T:System.ArgumentNullException">If <paramref name="action" /> is Add or Remove and <paramref name="changedItems" /> is null.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
IList<TValue> changedItems,
int startingIndex)
{
if (action != NotifyCollectionChangedAction.Add
&& action != NotifyCollectionChangedAction.Remove
&& action != NotifyCollectionChangedAction.Reset)
throw new ArgumentException(
"Must Be Reset Add Or Remove Action For Ctor",
nameof(action));
if (action == NotifyCollectionChangedAction.Reset)
{
if (changedItems != null)
throw new ArgumentException(
"Reset Action Requires Null Item",
nameof(action));
if (startingIndex != -1)
throw new ArgumentException(
"Reset Action Requires Index Minus 1",
nameof(action));
InitializeAdd(
action,
null,
-1);
}
else
{
if (changedItems == null)
throw new ArgumentNullException(
nameof(changedItems));
if (startingIndex < -1)
throw new ArgumentException(
"Index Cannot Be Negative",
nameof(startingIndex));
InitializeAddOrRemove(
action,
changedItems,
startingIndex);
}
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a one-item <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" /> change.</summary>
/// <param name="action">The action that caused the event. This can only be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" />.</param>
/// <param name="newItem">The new item that is replacing the original item.</param>
/// <param name="oldItem">The original item that is replaced.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Replace.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
TValue newItem,
TValue oldItem)
{
if (action != NotifyCollectionChangedAction.Replace)
throw new ArgumentException(
"Wrong Action For Ctor (Replace)",
nameof(action));
InitializeMoveOrReplace(
action,
new[] { newItem },
new[] { oldItem },
-1,
-1);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a one-item <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" /> change.</summary>
/// <param name="action">The action that caused the event. This can be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" />.</param>
/// <param name="newItem">The new item that is replacing the original item.</param>
/// <param name="oldItem">The original item that is replaced.</param>
/// <param name="index">The index of the item being replaced.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Replace.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
TValue newItem,
TValue oldItem,
int index)
{
if (action != NotifyCollectionChangedAction.Replace)
throw new ArgumentException(
"Wrong Action For Ctor (Replace)",
nameof(action));
var oldStartingIndex = index;
InitializeMoveOrReplace(
action,
new[] { newItem },
new[] { oldItem },
index,
oldStartingIndex);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a multi-item <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" /> change.</summary>
/// <param name="action">The action that caused the event. This can only be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" />.</param>
/// <param name="newItems">The new items that are replacing the original items.</param>
/// <param name="oldItems">The original items that are replaced.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Replace.</exception>
/// <exception cref="T:System.ArgumentNullException">If <paramref name="oldItems" /> or <paramref name="newItems" /> is null.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
IList<TValue> newItems,
IList<TValue> oldItems)
{
if (action != NotifyCollectionChangedAction.Replace)
throw new ArgumentException(
"Wrong Action For Ctor (Replace)",
nameof(action));
newItems.IsNotNull(nameof(newItems));
oldItems.IsNotNull(nameof(oldItems));
InitializeMoveOrReplace(
action,
newItems,
oldItems,
-1,
-1);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a multi-item <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" /> change.</summary>
/// <param name="action">The action that caused the event. This can only be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Replace" />.</param>
/// <param name="newItems">The new items that are replacing the original items.</param>
/// <param name="oldItems">The original items that are replaced.</param>
/// <param name="startingIndex">The index of the first item of the items that are being replaced.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Replace.</exception>
/// <exception cref="T:System.ArgumentNullException">If <paramref name="oldItems" /> or <paramref name="newItems" /> is null.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
IList<TValue> newItems,
IList<TValue> oldItems,
int startingIndex)
{
if (action != NotifyCollectionChangedAction.Replace)
throw new ArgumentException(
"Wrong Action For Ctor (Replace)",
nameof(action));
newItems.IsNotNull(nameof(newItems));
oldItems.IsNotNull(nameof(oldItems));
InitializeMoveOrReplace(
action,
newItems,
oldItems,
startingIndex,
startingIndex);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a one-item <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Move" /> change.</summary>
/// <param name="action">The action that caused the event. This can only be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Move" />.</param>
/// <param name="changedItem">The item affected by the change.</param>
/// <param name="index">The new index for the changed item.</param>
/// <param name="oldIndex">The old index for the changed item.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Move or <paramref name="index" /> is less than 0.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
TValue changedItem,
int index,
int oldIndex)
{
if (action != NotifyCollectionChangedAction.Move)
throw new ArgumentException(
"Wrong Action For Ctor (Move)",
nameof(action));
if (index < 0)
throw new ArgumentException(
"Index Cannot Be Negative",
nameof(index));
var objArray = new[] { changedItem };
InitializeMoveOrReplace(
action,
objArray,
objArray,
index,
oldIndex);
}
/// <summary>Initializes a new instance of the <see cref="T:System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> class that describes a multi-item <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Move" /> change.</summary>
/// <param name="action">The action that caused the event. This can only be set to <see cref="F:System.Collections.Specialized.NotifyCollectionChangedAction.Move" />.</param>
/// <param name="changedItems">The items affected by the change.</param>
/// <param name="index">The new index for the changed items.</param>
/// <param name="oldIndex">The old index for the changed items.</param>
/// <exception cref="T:System.ArgumentException">If <paramref name="action" /> is not Move or <paramref name="index" /> is less than 0.</exception>
public NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
IList<TValue> changedItems,
int index,
int oldIndex)
{
if (action != NotifyCollectionChangedAction.Move)
throw new ArgumentException(
"Wrong Action For Ctor (Move)",
nameof(action));
if (index < 0)
throw new ArgumentException(
"Index Cannot Be Negative",
nameof(index));
InitializeMoveOrReplace(
action,
changedItems,
changedItems,
index,
oldIndex);
}
internal NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action,
IList<TValue> newItems,
IList<TValue> oldItems,
int newIndex,
int oldIndex)
{
_action = action;
_newItems = newItems;
_oldItems = oldItems;
_newStartingIndex = newIndex;
_oldStartingIndex = oldIndex;
}
#region Operators
public static implicit operator NotifyCollectionChangedEventArgs(
NotifyCollectionChangedEventArgs<TValue> @this)
{
switch (@this.Action)
{
case NotifyCollectionChangedAction.Add:
return new NotifyCollectionChangedEventArgs(
@this.Action,
@this.NewItems as IList,
@this.NewStartingIndex);
case NotifyCollectionChangedAction.Replace:
return new NotifyCollectionChangedEventArgs(
@this.Action,
@this.NewItems,
@this.OldItems);
default:
throw new InvalidEnumArgumentException();
}
}
public static implicit operator NotifyCollectionChangedEventArgs<TValue>(
NotifyCollectionChangedEventArgs @this)
{
return new NotifyCollectionChangedEventArgs<TValue>(
@this.Action,
@this.NewItems.Cast<TValue>().ToArray(),
@this.OldItems.Cast<TValue>().ToArray());
}
#endregion
#region Methods
private void InitializeAddOrRemove(
NotifyCollectionChangedAction action,
IList<TValue> changedItems,
int startingIndex)
{
if (action == NotifyCollectionChangedAction.Add)
{
InitializeAdd(
action,
changedItems,
startingIndex);
}
else
{
if (action != NotifyCollectionChangedAction.Remove)
return;
InitializeRemove(
action,
changedItems,
startingIndex);
}
}
private void InitializeAdd(
NotifyCollectionChangedAction action,
IList<TValue> newItems,
int newStartingIndex)
{
_action = action;
_newItems = newItems;
_newStartingIndex = newStartingIndex;
}
private void InitializeRemove(
NotifyCollectionChangedAction action,
IList<TValue> oldItems,
int oldStartingIndex)
{
_action = action;
_oldItems = oldItems;
_oldStartingIndex = oldStartingIndex;
}
private void InitializeMoveOrReplace(
NotifyCollectionChangedAction action,
IList<TValue> newItems,
IList<TValue> oldItems,
int startingIndex,
int oldStartingIndex)
{
InitializeAdd(
action,
newItems,
startingIndex);
InitializeRemove(
action,
oldItems,
oldStartingIndex);
}
#endregion
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using SR = System.Reflection;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public enum ReadingMode {
Immediate = 1,
Deferred = 2,
}
public sealed class ReaderParameters {
ReadingMode reading_mode;
internal IAssemblyResolver assembly_resolver;
internal IMetadataResolver metadata_resolver;
#if !READ_ONLY
internal IMetadataImporterProvider metadata_importer_provider;
internal IReflectionImporterProvider reflection_importer_provider;
#endif
Stream symbol_stream;
ISymbolReaderProvider symbol_reader_provider;
bool read_symbols;
bool projections;
bool in_memory;
bool read_write;
public ReadingMode ReadingMode {
get { return reading_mode; }
set { reading_mode = value; }
}
public bool InMemory {
get { return in_memory; }
set { in_memory = value; }
}
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
set { assembly_resolver = value; }
}
public IMetadataResolver MetadataResolver {
get { return metadata_resolver; }
set { metadata_resolver = value; }
}
#if !READ_ONLY
public IMetadataImporterProvider MetadataImporterProvider {
get { return metadata_importer_provider; }
set { metadata_importer_provider = value; }
}
public IReflectionImporterProvider ReflectionImporterProvider {
get { return reflection_importer_provider; }
set { reflection_importer_provider = value; }
}
#endif
public Stream SymbolStream {
get { return symbol_stream; }
set { symbol_stream = value; }
}
public ISymbolReaderProvider SymbolReaderProvider {
get { return symbol_reader_provider; }
set { symbol_reader_provider = value; }
}
public bool ReadSymbols {
get { return read_symbols; }
set { read_symbols = value; }
}
public bool ReadWrite {
get { return read_write; }
set { read_write = value; }
}
public bool ApplyWindowsRuntimeProjections {
get { return projections; }
set { projections = value; }
}
public ReaderParameters ()
: this (ReadingMode.Deferred)
{
}
public ReaderParameters (ReadingMode readingMode)
{
this.reading_mode = readingMode;
}
}
#if !READ_ONLY
public sealed class ModuleParameters {
ModuleKind kind;
TargetRuntime runtime;
uint? timestamp;
TargetArchitecture architecture;
IAssemblyResolver assembly_resolver;
IMetadataResolver metadata_resolver;
#if !READ_ONLY
IMetadataImporterProvider metadata_importer_provider;
IReflectionImporterProvider reflection_importer_provider;
#endif
public ModuleKind Kind {
get { return kind; }
set { kind = value; }
}
public TargetRuntime Runtime {
get { return runtime; }
set { runtime = value; }
}
public uint? Timestamp {
get { return timestamp; }
set { timestamp = value; }
}
public TargetArchitecture Architecture {
get { return architecture; }
set { architecture = value; }
}
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
set { assembly_resolver = value; }
}
public IMetadataResolver MetadataResolver {
get { return metadata_resolver; }
set { metadata_resolver = value; }
}
#if !READ_ONLY
public IMetadataImporterProvider MetadataImporterProvider {
get { return metadata_importer_provider; }
set { metadata_importer_provider = value; }
}
public IReflectionImporterProvider ReflectionImporterProvider {
get { return reflection_importer_provider; }
set { reflection_importer_provider = value; }
}
#endif
public ModuleParameters ()
{
this.kind = ModuleKind.Dll;
this.Runtime = GetCurrentRuntime ();
this.architecture = TargetArchitecture.I386;
}
static TargetRuntime GetCurrentRuntime ()
{
#if !NET_CORE
return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime ();
#else
var corlib_name = AssemblyNameReference.Parse (typeof (object).Assembly ().FullName);
var corlib_version = corlib_name.Version;
switch (corlib_version.Major) {
case 1:
return corlib_version.Minor == 0
? TargetRuntime.Net_1_0
: TargetRuntime.Net_1_1;
case 2:
return TargetRuntime.Net_2_0;
case 4:
return TargetRuntime.Net_4_0;
default:
throw new NotSupportedException ();
}
#endif
}
}
public sealed class WriterParameters {
uint? timestamp;
Stream symbol_stream;
ISymbolWriterProvider symbol_writer_provider;
bool write_symbols;
#if !NET_CORE
SR.StrongNameKeyPair key_pair;
#endif
public uint? Timestamp {
get { return timestamp; }
set { timestamp = value; }
}
public Stream SymbolStream {
get { return symbol_stream; }
set { symbol_stream = value; }
}
public ISymbolWriterProvider SymbolWriterProvider {
get { return symbol_writer_provider; }
set { symbol_writer_provider = value; }
}
public bool WriteSymbols {
get { return write_symbols; }
set { write_symbols = value; }
}
#if !NET_CORE
public SR.StrongNameKeyPair StrongNameKeyPair {
get { return key_pair; }
set { key_pair = value; }
}
#endif
}
#endif
public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider, ICustomDebugInformationProvider, IDisposable {
internal Image Image;
internal MetadataSystem MetadataSystem;
internal ReadingMode ReadingMode;
internal ISymbolReaderProvider SymbolReaderProvider;
internal ISymbolReader symbol_reader;
internal Disposable<IAssemblyResolver> assembly_resolver;
internal IMetadataResolver metadata_resolver;
internal TypeSystem type_system;
internal readonly MetadataReader reader;
readonly string file_name;
internal string runtime_version;
internal ModuleKind kind;
WindowsRuntimeProjections projections;
MetadataKind metadata_kind;
TargetRuntime runtime;
TargetArchitecture architecture;
ModuleAttributes attributes;
ModuleCharacteristics characteristics;
Guid mvid;
internal uint timestamp;
internal AssemblyDefinition assembly;
MethodDefinition entry_point;
#if !READ_ONLY
internal IReflectionImporter reflection_importer;
internal IMetadataImporter metadata_importer;
#endif
Collection<CustomAttribute> custom_attributes;
Collection<AssemblyNameReference> references;
Collection<ModuleReference> modules;
Collection<Resource> resources;
Collection<ExportedType> exported_types;
TypeDefinitionCollection types;
ResourceDirectory win32ResourceDirectory;
internal byte[] Win32Resources;
internal uint Win32RVA;
internal Collection<CustomDebugInformation> custom_infos;
public bool IsMain {
get { return kind != ModuleKind.NetModule; }
}
public ModuleKind Kind {
get { return kind; }
set { kind = value; }
}
public MetadataKind MetadataKind {
get { return metadata_kind; }
set { metadata_kind = value; }
}
internal WindowsRuntimeProjections Projections {
get {
if (projections == null)
Interlocked.CompareExchange (ref projections, new WindowsRuntimeProjections (this), null);
return projections;
}
}
public TargetRuntime Runtime {
get { return runtime; }
set {
runtime = value;
runtime_version = runtime.RuntimeVersionString ();
}
}
public string RuntimeVersion {
get { return runtime_version; }
set {
runtime_version = value;
runtime = runtime_version.ParseRuntime ();
}
}
public TargetArchitecture Architecture {
get { return architecture; }
set { architecture = value; }
}
public ModuleAttributes Attributes {
get { return attributes; }
set { attributes = value; }
}
public ModuleCharacteristics Characteristics {
get { return characteristics; }
set { characteristics = value; }
}
[Obsolete("Use FileName")]
public string FullyQualifiedName {
get { return file_name; }
}
public string FileName {
get { return file_name; }
}
public Guid Mvid {
get { return mvid; }
set { mvid = value; }
}
internal bool HasImage {
get { return Image != null; }
}
public bool HasSymbols {
get { return symbol_reader != null; }
}
public ISymbolReader SymbolReader {
get { return symbol_reader; }
}
public override MetadataScopeType MetadataScopeType {
get { return MetadataScopeType.ModuleDefinition; }
}
public AssemblyDefinition Assembly {
get { return assembly; }
}
#if !READ_ONLY
internal IReflectionImporter ReflectionImporter {
get {
if (reflection_importer == null)
Interlocked.CompareExchange (ref reflection_importer, new DefaultReflectionImporter (this), null);
return reflection_importer;
}
}
internal IMetadataImporter MetadataImporter {
get {
if (metadata_importer == null)
Interlocked.CompareExchange (ref metadata_importer, new DefaultMetadataImporter (this), null);
return metadata_importer;
}
}
#endif
public IAssemblyResolver AssemblyResolver {
get {
if (assembly_resolver.value == null) {
lock (module_lock) {
assembly_resolver = Disposable.Owned (new DefaultAssemblyResolver () as IAssemblyResolver);
}
}
return assembly_resolver.value;
}
}
public IMetadataResolver MetadataResolver {
get {
if (metadata_resolver == null)
Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null);
return metadata_resolver;
}
}
public TypeSystem TypeSystem {
get {
if (type_system == null)
Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null);
return type_system;
}
}
public bool HasAssemblyReferences {
get {
if (references != null)
return references.Count > 0;
return HasImage && Image.HasTable (Table.AssemblyRef);
}
}
public Collection<AssemblyNameReference> AssemblyReferences {
get {
if (references != null)
return references;
if (HasImage)
return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ());
return references = new Collection<AssemblyNameReference> ();
}
}
public bool HasModuleReferences {
get {
if (modules != null)
return modules.Count > 0;
return HasImage && Image.HasTable (Table.ModuleRef);
}
}
public Collection<ModuleReference> ModuleReferences {
get {
if (modules != null)
return modules;
if (HasImage)
return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ());
return modules = new Collection<ModuleReference> ();
}
}
public bool HasResources {
get {
if (resources != null)
return resources.Count > 0;
if (HasImage)
return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ());
return false;
}
}
public Collection<Resource> Resources {
get {
if (resources != null)
return resources;
if (HasImage)
return Read (ref resources, this, (_, reader) => reader.ReadResources ());
return resources = new Collection<Resource> ();
}
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (this);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); }
}
public bool HasTypes {
get {
if (types != null)
return types.Count > 0;
return HasImage && Image.HasTable (Table.TypeDef);
}
}
public Collection<TypeDefinition> Types {
get {
if (types != null)
return types;
if (HasImage)
return Read (ref types, this, (_, reader) => reader.ReadTypes ());
return types = new TypeDefinitionCollection (this);
}
}
public bool HasExportedTypes {
get {
if (exported_types != null)
return exported_types.Count > 0;
return HasImage && Image.HasTable (Table.ExportedType);
}
}
public Collection<ExportedType> ExportedTypes {
get {
if (exported_types != null)
return exported_types;
if (HasImage)
return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ());
return exported_types = new Collection<ExportedType> ();
}
}
public MethodDefinition EntryPoint {
get {
if (entry_point != null)
return entry_point;
if (HasImage)
return Read (ref entry_point, this, (_, reader) => reader.ReadEntryPoint ());
return entry_point = null;
}
set { entry_point = value; }
}
public bool HasCustomDebugInformations {
get {
return custom_infos != null && custom_infos.Count > 0;
}
}
public Collection<CustomDebugInformation> CustomDebugInformations {
get {
return custom_infos ?? (custom_infos = new Collection<CustomDebugInformation> ());
}
}
internal ModuleDefinition ()
{
this.MetadataSystem = new MetadataSystem ();
this.token = new MetadataToken (TokenType.Module, 1);
}
internal ModuleDefinition (Image image)
: this ()
{
this.Image = image;
this.kind = image.Kind;
this.RuntimeVersion = image.RuntimeVersion;
this.architecture = image.Architecture;
this.attributes = image.Attributes;
this.characteristics = image.Characteristics;
this.file_name = image.FileName;
this.timestamp = image.Timestamp;
this.reader = new MetadataReader (this);
}
public void Dispose ()
{
if (Image != null)
Image.Dispose ();
if (symbol_reader != null)
symbol_reader.Dispose ();
if (assembly_resolver.value != null)
assembly_resolver.Dispose ();
}
public bool HasTypeReference (string fullName)
{
return HasTypeReference (string.Empty, fullName);
}
public bool HasTypeReference (string scope, string fullName)
{
Mixin.CheckFullName (fullName);
if (!HasImage)
return false;
return GetTypeReference (scope, fullName) != null;
}
public bool TryGetTypeReference (string fullName, out TypeReference type)
{
return TryGetTypeReference (string.Empty, fullName, out type);
}
public bool TryGetTypeReference (string scope, string fullName, out TypeReference type)
{
Mixin.CheckFullName (fullName);
if (!HasImage) {
type = null;
return false;
}
return (type = GetTypeReference (scope, fullName)) != null;
}
TypeReference GetTypeReference (string scope, string fullname)
{
return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2));
}
public IEnumerable<TypeReference> GetTypeReferences ()
{
if (!HasImage)
return Empty<TypeReference>.Array;
return Read (this, (_, reader) => reader.GetTypeReferences ());
}
public IEnumerable<MemberReference> GetMemberReferences ()
{
if (!HasImage)
return Empty<MemberReference>.Array;
return Read (this, (_, reader) => reader.GetMemberReferences ());
}
public IEnumerable<CustomAttribute> GetCustomAttributes ()
{
if (!HasImage)
return Empty<CustomAttribute>.Array;
return Read (this, (_, reader) => reader.GetCustomAttributes ());
}
public TypeReference GetType (string fullName, bool runtimeName)
{
return runtimeName
? TypeParser.ParseType (this, fullName)
: GetType (fullName);
}
public TypeDefinition GetType (string fullName)
{
Mixin.CheckFullName (fullName);
var position = fullName.IndexOf ('/');
if (position > 0)
return GetNestedType (fullName);
return ((TypeDefinitionCollection) this.Types).GetType (fullName);
}
public TypeDefinition GetType (string @namespace, string name)
{
Mixin.CheckName (name);
return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name);
}
public IEnumerable<TypeDefinition> GetTypes ()
{
return GetTypes (Types);
}
static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types)
{
for (int i = 0; i < types.Count; i++) {
var type = types [i];
yield return type;
if (!type.HasNestedTypes)
continue;
foreach (var nested in GetTypes (type.NestedTypes))
yield return nested;
}
}
TypeDefinition GetNestedType (string fullname)
{
var names = fullname.Split ('/');
var type = GetType (names [0]);
if (type == null)
return null;
for (int i = 1; i < names.Length; i++) {
var nested_type = type.GetNestedType (names [i]);
if (nested_type == null)
return null;
type = nested_type;
}
return type;
}
internal FieldDefinition Resolve (FieldReference field)
{
return MetadataResolver.Resolve (field);
}
internal MethodDefinition Resolve (MethodReference method)
{
return MetadataResolver.Resolve (method);
}
internal TypeDefinition Resolve (TypeReference type)
{
return MetadataResolver.Resolve (type);
}
#if !READ_ONLY
static void CheckContext (IGenericParameterProvider context, ModuleDefinition module)
{
if (context == null)
return;
if (context.Module != module)
throw new ArgumentException ();
}
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (Type type)
{
return ImportReference (type, null);
}
public TypeReference ImportReference (Type type)
{
return ImportReference (type, null);
}
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (Type type, IGenericParameterProvider context)
{
return ImportReference (type, context);
}
public TypeReference ImportReference (Type type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
CheckContext (context, this);
return ReflectionImporter.ImportReference (type, context);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (SR.FieldInfo field)
{
return ImportReference (field, null);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context)
{
return ImportReference (field, context);
}
public FieldReference ImportReference (SR.FieldInfo field)
{
return ImportReference (field, null);
}
public FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
CheckContext (context, this);
return ReflectionImporter.ImportReference (field, context);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (SR.MethodBase method)
{
return ImportReference (method, null);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (SR.MethodBase method, IGenericParameterProvider context)
{
return ImportReference (method, context);
}
public MethodReference ImportReference (SR.MethodBase method)
{
return ImportReference (method, null);
}
public MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
CheckContext (context, this);
return ReflectionImporter.ImportReference (method, context);
}
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (TypeReference type)
{
return ImportReference (type, null);
}
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (TypeReference type, IGenericParameterProvider context)
{
return ImportReference (type, context);
}
public TypeReference ImportReference (TypeReference type)
{
return ImportReference (type, null);
}
public TypeReference ImportReference (TypeReference type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
if (type.Module == this)
return type;
CheckContext (context, this);
return MetadataImporter.ImportReference (type, context);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (FieldReference field)
{
return ImportReference (field, null);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (FieldReference field, IGenericParameterProvider context)
{
return ImportReference (field, context);
}
public FieldReference ImportReference (FieldReference field)
{
return ImportReference (field, null);
}
public FieldReference ImportReference (FieldReference field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
if (field.Module == this)
return field;
CheckContext (context, this);
return MetadataImporter.ImportReference (field, context);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (MethodReference method)
{
return ImportReference (method, null);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (MethodReference method, IGenericParameterProvider context)
{
return ImportReference (method, context);
}
public MethodReference ImportReference (MethodReference method)
{
return ImportReference (method, null);
}
public MethodReference ImportReference (MethodReference method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
if (method.Module == this)
return method;
CheckContext (context, this);
return MetadataImporter.ImportReference (method, context);
}
#endif
public IMetadataTokenProvider LookupToken (int token)
{
return LookupToken (new MetadataToken ((uint) token));
}
public IMetadataTokenProvider LookupToken (MetadataToken token)
{
return Read (token, (t, reader) => reader.LookupToken (t));
}
readonly object module_lock = new object();
internal object SyncRoot {
get { return module_lock; }
}
internal void Read<TItem> (TItem item, Action<TItem, MetadataReader> read)
{
lock (module_lock) {
var position = reader.position;
var context = reader.context;
read (item, reader);
reader.position = position;
reader.context = context;
}
}
internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read)
{
lock (module_lock) {
var position = reader.position;
var context = reader.context;
var ret = read (item, reader);
reader.position = position;
reader.context = context;
return ret;
}
}
internal TRet Read<TItem, TRet> (ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class
{
lock (module_lock) {
if (variable != null)
return variable;
var position = reader.position;
var context = reader.context;
var ret = read (item, reader);
reader.position = position;
reader.context = context;
return variable = ret;
}
}
public bool HasDebugHeader {
get { return Image != null && Image.DebugHeader != null; }
}
public ResourceDirectory Win32ResourceDirectory
{
get
{
if (win32ResourceDirectory == null)
{
var rsrc = Image != null ? Image.GetSection(".rsrc") : null;
if (rsrc == null)
{
win32ResourceDirectory = new ResourceDirectory();
}
else
{
win32ResourceDirectory = Image.GetReaderAt(rsrc.VirtualAddress, rsrc.SizeOfRawData, (s, reader) => RsrcReader.ReadResourceDirectory(reader.ReadBytes((int)rsrc.SizeOfRawData), rsrc.VirtualAddress));
}
}
return win32ResourceDirectory;
}
set
{
win32ResourceDirectory = value;
}
}
public ImageDebugHeader GetDebugHeader ()
{
return Image.DebugHeader ?? new ImageDebugHeader ();
}
#if !READ_ONLY
public static ModuleDefinition CreateModule (string name, ModuleKind kind)
{
return CreateModule (name, new ModuleParameters { Kind = kind });
}
public static ModuleDefinition CreateModule (string name, ModuleParameters parameters)
{
Mixin.CheckName (name);
Mixin.CheckParameters (parameters);
var module = new ModuleDefinition {
Name = name,
kind = parameters.Kind,
timestamp = parameters.Timestamp ?? Mixin.GetTimestamp (),
Runtime = parameters.Runtime,
architecture = parameters.Architecture,
mvid = Guid.NewGuid (),
Attributes = ModuleAttributes.ILOnly,
Characteristics = (ModuleCharacteristics) 0x8540,
};
if (parameters.AssemblyResolver != null)
module.assembly_resolver = Disposable.NotOwned (parameters.AssemblyResolver);
if (parameters.MetadataResolver != null)
module.metadata_resolver = parameters.MetadataResolver;
#if !READ_ONLY
if (parameters.MetadataImporterProvider != null)
module.metadata_importer = parameters.MetadataImporterProvider.GetMetadataImporter (module);
if (parameters.ReflectionImporterProvider != null)
module.reflection_importer = parameters.ReflectionImporterProvider.GetReflectionImporter (module);
#endif
if (parameters.Kind != ModuleKind.NetModule) {
var assembly = new AssemblyDefinition ();
module.assembly = assembly;
module.assembly.Name = CreateAssemblyName (name);
assembly.main_module = module;
}
module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic));
return module;
}
static AssemblyNameDefinition CreateAssemblyName (string name)
{
if (name.EndsWith (".dll") || name.EndsWith (".exe"))
name = name.Substring (0, name.Length - 4);
return new AssemblyNameDefinition (name, Mixin.ZeroVersion);
}
#endif
public void ReadSymbols ()
{
if (string.IsNullOrEmpty (file_name))
throw new InvalidOperationException ();
var provider = new DefaultSymbolReaderProvider (throwIfNoSymbol: true);
ReadSymbols (provider.GetSymbolReader (this, file_name));
}
public void ReadSymbols (ISymbolReader reader)
{
if (reader == null)
throw new ArgumentNullException ("reader");
symbol_reader = reader;
if (!symbol_reader.ProcessDebugHeader (GetDebugHeader ())) {
symbol_reader = null;
throw new InvalidOperationException ();
}
if (HasImage && ReadingMode == ReadingMode.Immediate) {
var immediate_reader = new ImmediateModuleReader (Image);
immediate_reader.ReadSymbols (this);
}
}
public static ModuleDefinition ReadModule (string fileName)
{
return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred));
}
public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters)
{
var stream = GetFileStream (fileName, FileMode.Open, parameters.ReadWrite ? FileAccess.ReadWrite : FileAccess.Read, FileShare.Read);
if (parameters.InMemory) {
var memory = new MemoryStream (stream.CanSeek ? (int) stream.Length : 0);
using (stream)
stream.CopyTo (memory);
memory.Position = 0;
stream = memory;
}
try {
return ReadModule (Disposable.Owned (stream), fileName, parameters);
} catch (Exception) {
stream.Dispose ();
throw;
}
}
static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share)
{
Mixin.CheckFileName (fileName);
return new FileStream (fileName, mode, access, share);
}
public static ModuleDefinition ReadModule (Stream stream)
{
return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred));
}
public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters)
{
Mixin.CheckStream (stream);
Mixin.CheckReadSeek (stream);
return ReadModule (Disposable.NotOwned (stream), stream.GetFileName (), parameters);
}
static ModuleDefinition ReadModule (Disposable<Stream> stream, string fileName, ReaderParameters parameters)
{
Mixin.CheckParameters (parameters);
return ModuleReader.CreateModule (
ImageReader.ReadImage (stream, fileName),
parameters);
}
#if !READ_ONLY
public void Write (string fileName)
{
Write (fileName, new WriterParameters ());
}
public void Write (string fileName, WriterParameters parameters)
{
Mixin.CheckParameters (parameters);
var file = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
ModuleWriter.WriteModule (this, Disposable.Owned (file), parameters);
}
public void Write ()
{
Write (new WriterParameters ());
}
public void Write (WriterParameters parameters)
{
if (!HasImage)
throw new InvalidOperationException ();
Write (Image.Stream.value, parameters);
}
public void Write (Stream stream)
{
Write (stream, new WriterParameters ());
}
public void Write (Stream stream, WriterParameters parameters)
{
Mixin.CheckStream (stream);
Mixin.CheckWriteSeek (stream);
Mixin.CheckParameters (parameters);
ModuleWriter.WriteModule (this, Disposable.NotOwned (stream), parameters);
}
#endif
}
static partial class Mixin {
public enum Argument {
name,
fileName,
fullName,
stream,
type,
method,
field,
parameters,
module,
modifierType,
eventType,
fieldType,
declaringType,
returnType,
propertyType,
interfaceType,
}
public static void CheckName (object name)
{
if (name == null)
throw new ArgumentNullException (Argument.name.ToString ());
}
public static void CheckName (string name)
{
if (string.IsNullOrEmpty (name))
throw new ArgumentNullOrEmptyException (Argument.name.ToString ());
}
public static void CheckFileName (string fileName)
{
if (string.IsNullOrEmpty (fileName))
throw new ArgumentNullOrEmptyException (Argument.fileName.ToString ());
}
public static void CheckFullName (string fullName)
{
if (string.IsNullOrEmpty (fullName))
throw new ArgumentNullOrEmptyException (Argument.fullName.ToString ());
}
public static void CheckStream (object stream)
{
if (stream == null)
throw new ArgumentNullException (Argument.stream.ToString ());
}
public static void CheckWriteSeek (Stream stream)
{
if (!stream.CanWrite || !stream.CanSeek)
throw new ArgumentException ("Stream must be writable and seekable.");
}
public static void CheckReadSeek (Stream stream)
{
if (!stream.CanRead || !stream.CanSeek)
throw new ArgumentException ("Stream must be readable and seekable.");
}
public static void CheckType (object type)
{
if (type == null)
throw new ArgumentNullException (Argument.type.ToString ());
}
public static void CheckType (object type, Argument argument)
{
if (type == null)
throw new ArgumentNullException (argument.ToString ());
}
public static void CheckField (object field)
{
if (field == null)
throw new ArgumentNullException (Argument.field.ToString ());
}
public static void CheckMethod (object method)
{
if (method == null)
throw new ArgumentNullException (Argument.method.ToString ());
}
public static void CheckParameters (object parameters)
{
if (parameters == null)
throw new ArgumentNullException (Argument.parameters.ToString ());
}
public static uint GetTimestamp ()
{
return (uint) DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1)).TotalSeconds;
}
public static bool HasImage (this ModuleDefinition self)
{
return self != null && self.HasImage;
}
public static string GetFileName (this Stream self)
{
var file_stream = self as FileStream;
if (file_stream == null)
return string.Empty;
return Path.GetFullPath (file_stream.Name);
}
#if !NET_4_0
public static void CopyTo (this Stream self, Stream target)
{
var buffer = new byte [1024 * 8];
int read;
while ((read = self.Read (buffer, 0, buffer.Length)) > 0)
target.Write (buffer, 0, read);
}
#endif
public static TargetRuntime ParseRuntime (this string self)
{
if (string.IsNullOrEmpty (self))
return TargetRuntime.Net_4_0;
switch (self [1]) {
case '1':
return self [3] == '0'
? TargetRuntime.Net_1_0
: TargetRuntime.Net_1_1;
case '2':
return TargetRuntime.Net_2_0;
case '4':
default:
return TargetRuntime.Net_4_0;
}
}
public static string RuntimeVersionString (this TargetRuntime runtime)
{
switch (runtime) {
case TargetRuntime.Net_1_0:
return "v1.0.3705";
case TargetRuntime.Net_1_1:
return "v1.1.4322";
case TargetRuntime.Net_2_0:
return "v2.0.50727";
case TargetRuntime.Net_4_0:
default:
return "v4.0.30319";
}
}
public static bool IsWindowsMetadata (this ModuleDefinition module)
{
return module.MetadataKind != MetadataKind.Ecma335;
}
public static byte [] ReadAll (this Stream self)
{
int read;
var memory = new MemoryStream ((int) self.Length);
var buffer = new byte [1024];
while ((read = self.Read (buffer, 0, buffer.Length)) != 0)
memory.Write (buffer, 0, read);
return memory.ToArray ();
}
public static void Read (object o)
{
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using Pgno = System.UInt32;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_stmt = Sqlite3.Vdbe;
public partial class Sqlite3
{
/*
** 2003 April 6
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the VACUUM command.
**
** Most of the code in this file may be omitted by defining the
** SQLITE_OMIT_VACUUM macro.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include "vdbeInt.h"
#if !SQLITE_OMIT_VACUUM && !SQLITE_OMIT_ATTACH
/*
** Finalize a prepared statement. If there was an error, store the
** text of the error message in *pzErrMsg. Return the result code.
*/
static int vacuumFinalize( sqlite3 db, sqlite3_stmt pStmt, string pzErrMsg )
{
int rc;
rc = sqlite3VdbeFinalize( (Vdbe)pStmt );
if ( rc != 0 )
{
sqlite3SetString( ref pzErrMsg, db, sqlite3_errmsg( db ) );
}
return rc;
}
/*
** Execute zSql on database db. Return an error code.
*/
static int execSql( sqlite3 db, string pzErrMsg, string zSql )
{
sqlite3_stmt pStmt = null;
#if !NDEBUG
int rc;
//VVA_ONLY( int rc; )
#endif
if ( zSql == null )
{
return SQLITE_NOMEM;
}
string Dummy = null;
if ( SQLITE_OK != sqlite3_prepare( db, zSql, -1, ref pStmt, ref Dummy ) )
{
sqlite3SetString( ref pzErrMsg, db, sqlite3_errmsg( db ) );
return sqlite3_errcode( db );
}
#if !NDEBUG
rc = sqlite3_step( pStmt );
//VVA_ONLY( rc = ) sqlite3_step(pStmt);
Debug.Assert( rc != SQLITE_ROW );
#else
sqlite3_step(pStmt);
#endif
return vacuumFinalize( db, pStmt, pzErrMsg );
}
/*
** Execute zSql on database db. The statement returns exactly
** one column. Execute this as SQL on the same database.
*/
static int execExecSql( sqlite3 db, string pzErrMsg, string zSql )
{
sqlite3_stmt pStmt = null;
int rc;
string Dummy = null;
rc = sqlite3_prepare( db, zSql, -1, ref pStmt, ref Dummy );
if ( rc != SQLITE_OK )
return rc;
while ( SQLITE_ROW == sqlite3_step( pStmt ) )
{
rc = execSql( db, pzErrMsg, sqlite3_column_text( pStmt, 0 ) );
if ( rc != SQLITE_OK )
{
vacuumFinalize( db, pStmt, pzErrMsg );
return rc;
}
}
return vacuumFinalize( db, pStmt, pzErrMsg );
}
/*
** The non-standard VACUUM command is used to clean up the database,
** collapse free space, etc. It is modelled after the VACUUM command
** in PostgreSQL.
**
** In version 1.0.x of SQLite, the VACUUM command would call
** gdbm_reorganize() on all the database tables. But beginning
** with 2.0.0, SQLite no longer uses GDBM so this command has
** become a no-op.
*/
static void sqlite3Vacuum( Parse pParse )
{
Vdbe v = sqlite3GetVdbe( pParse );
if ( v != null )
{
sqlite3VdbeAddOp2( v, OP_Vacuum, 0, 0 );
}
return;
}
/*
** This routine implements the OP_Vacuum opcode of the VDBE.
*/
static int sqlite3RunVacuum( ref string pzErrMsg, sqlite3 db )
{
int rc = SQLITE_OK; /* Return code from service routines */
Btree pMain; /* The database being vacuumed */
Btree pTemp; /* The temporary database we vacuum into */
string zSql = ""; /* SQL statements */
int saved_flags; /* Saved value of the db.flags */
int saved_nChange; /* Saved value of db.nChange */
int saved_nTotalChange; /* Saved value of db.nTotalChange */
dxTrace saved_xTrace; //void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
Db pDb = null; /* Database to detach at end of vacuum */
bool isMemDb; /* True if vacuuming a :memory: database */
int nRes; /* Bytes of reserved space at the end of each page */
int nDb; /* Number of attached databases */
if ( 0 == db.autoCommit )
{
sqlite3SetString( ref pzErrMsg, db, "cannot VACUUM from within a transaction" );
return SQLITE_ERROR;
}
if ( db.activeVdbeCnt > 1 )
{
sqlite3SetString( ref pzErrMsg, db, "cannot VACUUM - SQL statements in progress" );
return SQLITE_ERROR;
}
/* Save the current value of the database flags so that it can be
** restored before returning. Then set the writable-schema flag, and
** disable CHECK and foreign key constraints. */
saved_flags = db.flags;
saved_nChange = db.nChange;
saved_nTotalChange = db.nTotalChange;
saved_xTrace = db.xTrace;
db.flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
db.flags &= ~( SQLITE_ForeignKeys | SQLITE_ReverseOrder );
db.xTrace = null;
pMain = db.aDb[0].pBt;
isMemDb = sqlite3PagerIsMemdb( sqlite3BtreePager( pMain ) );
/* Attach the temporary database as 'vacuum_db'. The synchronous pragma
** can be set to 'off' for this file, as it is not recovered if a crash
** occurs anyway. The integrity of the database is maintained by a
** (possibly synchronous) transaction opened on the main database before
** sqlite3BtreeCopyFile() is called.
**
** An optimisation would be to use a non-journaled pager.
** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
** that actually made the VACUUM run slower. Very little journalling
** actually occurs when doing a vacuum since the vacuum_db is initially
** empty. Only the journal header is written. Apparently it takes more
** time to parse and run the PRAGMA to turn journalling off than it does
** to write the journal header file.
*/
nDb = db.nDb;
if ( sqlite3TempInMemory( db ) )
{
zSql = "ATTACH ':memory:' AS vacuum_db;";
}
else
{
zSql = "ATTACH '' AS vacuum_db;";
}
rc = execSql( db, pzErrMsg, zSql );
if ( db.nDb > nDb )
{
pDb = db.aDb[db.nDb - 1];
Debug.Assert( pDb.zName == "vacuum_db" );
}
if ( rc != SQLITE_OK )
goto end_of_vacuum;
pDb = db.aDb[db.nDb - 1];
Debug.Assert( db.aDb[db.nDb - 1].zName == "vacuum_db" );
pTemp = db.aDb[db.nDb - 1].pBt;
/* The call to execSql() to attach the temp database has left the file
** locked (as there was more than one active statement when the transaction
** to read the schema was concluded. Unlock it here so that this doesn't
** cause problems for the call to BtreeSetPageSize() below. */
sqlite3BtreeCommit( pTemp );
nRes = sqlite3BtreeGetReserve( pMain );
/* A VACUUM cannot change the pagesize of an encrypted database. */
#if SQLITE_HAS_CODEC
if ( db.nextPagesize != 0 )
{
//extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
int nKey;
string zKey;
sqlite3CodecGetKey( db, 0, out zKey, out nKey ); // sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey);
if ( nKey != 0 )
db.nextPagesize = 0;
}
#endif
/* Do not attempt to change the page size for a WAL database */
if ( sqlite3PagerGetJournalMode( sqlite3BtreePager( pMain ) )
== PAGER_JOURNALMODE_WAL )
{
db.nextPagesize = 0;
}
if ( sqlite3BtreeSetPageSize( pTemp, sqlite3BtreeGetPageSize( pMain ), nRes, 0 ) != 0
|| ( !isMemDb && sqlite3BtreeSetPageSize( pTemp, db.nextPagesize, nRes, 0 ) != 0 )
//|| NEVER( db.mallocFailed != 0 )
)
{
rc = SQLITE_NOMEM;
goto end_of_vacuum;
}
rc = execSql( db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF" );
if ( rc != SQLITE_OK )
{
goto end_of_vacuum;
}
#if !SQLITE_OMIT_AUTOVACUUM
sqlite3BtreeSetAutoVacuum( pTemp, db.nextAutovac >= 0 ? db.nextAutovac :
sqlite3BtreeGetAutoVacuum( pMain ) );
#endif
/* Begin a transaction */
rc = execSql( db, pzErrMsg, "BEGIN EXCLUSIVE;" );
if ( rc != SQLITE_OK )
goto end_of_vacuum;
/* Query the schema of the main database. Create a mirror schema
** in the temporary database.
*/
rc = execExecSql( db, pzErrMsg,
"SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) " +
" FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" +
" AND rootpage>0"
);
if ( rc != SQLITE_OK )
goto end_of_vacuum;
rc = execExecSql( db, pzErrMsg,
"SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)" +
" FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' " );
if ( rc != SQLITE_OK )
goto end_of_vacuum;
rc = execExecSql( db, pzErrMsg,
"SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) " +
" FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'" );
if ( rc != SQLITE_OK )
goto end_of_vacuum;
/* Loop through the tables in the main database. For each, do
** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
** the contents to the temporary database.
*/
rc = execExecSql( db, pzErrMsg,
"SELECT 'INSERT INTO vacuum_db.' || quote(name) " +
"|| ' SELECT * FROM main.' || quote(name) || ';'" +
"FROM main.sqlite_master " +
"WHERE type = 'table' AND name!='sqlite_sequence' " +
" AND rootpage>0"
);
if ( rc != SQLITE_OK )
goto end_of_vacuum;
/* Copy over the sequence table
*/
rc = execExecSql( db, pzErrMsg,
"SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' " +
"FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
);
if ( rc != SQLITE_OK )
goto end_of_vacuum;
rc = execExecSql( db, pzErrMsg,
"SELECT 'INSERT INTO vacuum_db.' || quote(name) " +
"|| ' SELECT * FROM main.' || quote(name) || ';' " +
"FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
);
if ( rc != SQLITE_OK )
goto end_of_vacuum;
/* Copy the triggers, views, and virtual tables from the main database
** over to the temporary database. None of these objects has any
** associated storage, so all we have to do is copy their entries
** from the SQLITE_MASTER table.
*/
rc = execSql( db, pzErrMsg,
"INSERT INTO vacuum_db.sqlite_master " +
" SELECT type, name, tbl_name, rootpage, sql" +
" FROM main.sqlite_master" +
" WHERE type='view' OR type='trigger'" +
" OR (type='table' AND rootpage=0)"
);
if ( rc != 0 )
goto end_of_vacuum;
/* At this point, unless the main db was completely empty, there is now a
** transaction open on the vacuum database, but not on the main database.
** Open a btree level transaction on the main database. This allows a
** call to sqlite3BtreeCopyFile(). The main database btree level
** transaction is then committed, so the SQL level never knows it was
** opened for writing. This way, the SQL transaction used to create the
** temporary database never needs to be committed.
*/
{
u32 meta = 0;
int i;
/* This array determines which meta meta values are preserved in the
** vacuum. Even entries are the meta value number and odd entries
** are an increment to apply to the meta value after the vacuum.
** The increment is used to increase the schema cookie so that other
** connections to the same database will know to reread the schema.
*/
byte[] aCopy = new byte[] {
BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
BTREE_USER_VERSION, 0, /* Preserve the user version */
};
Debug.Assert( sqlite3BtreeIsInTrans( pTemp ) );
Debug.Assert( sqlite3BtreeIsInTrans( pMain ) );
/* Copy Btree meta values */
for ( i = 0; i < ArraySize( aCopy ); i += 2 )
{
/* GetMeta() and UpdateMeta() cannot fail in this context because
** we already have page 1 loaded into cache and marked dirty. */
sqlite3BtreeGetMeta( pMain, aCopy[i], ref meta );
rc = sqlite3BtreeUpdateMeta( pTemp, aCopy[i], (u32)( meta + aCopy[i + 1] ) );
if ( NEVER( rc != SQLITE_OK ) )
goto end_of_vacuum;
}
rc = sqlite3BtreeCopyFile( pMain, pTemp );
if ( rc != SQLITE_OK )
goto end_of_vacuum;
rc = sqlite3BtreeCommit( pTemp );
if ( rc != SQLITE_OK )
goto end_of_vacuum;
#if !SQLITE_OMIT_AUTOVACUUM
sqlite3BtreeSetAutoVacuum( pMain, sqlite3BtreeGetAutoVacuum( pTemp ) );
#endif
}
Debug.Assert( rc == SQLITE_OK );
rc = sqlite3BtreeSetPageSize( pMain, sqlite3BtreeGetPageSize( pTemp ), nRes, 1 );
end_of_vacuum:
/* Restore the original value of db.flags */
db.flags = saved_flags;
db.nChange = saved_nChange;
db.nTotalChange = saved_nTotalChange;
db.xTrace = saved_xTrace;
sqlite3BtreeSetPageSize( pMain, -1, -1, 1 );
/* Currently there is an SQL level transaction open on the vacuum
** database. No locks are held on any other files (since the main file
** was committed at the btree level). So it safe to end the transaction
** by manually setting the autoCommit flag to true and detaching the
** vacuum database. The vacuum_db journal file is deleted when the pager
** is closed by the DETACH.
*/
db.autoCommit = 1;
if ( pDb != null )
{
sqlite3BtreeClose( ref pDb.pBt );
pDb.pBt = null;
pDb.pSchema = null;
}
/* This both clears the schemas and reduces the size of the db->aDb[]
** array. */
sqlite3ResetInternalSchema( db, -1 );
return rc;
}
#endif // * SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
}
}
| |
/* Copyright (c) 2006-2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Google.GData.Client;
namespace Google.GData.Extensions {
/// <summary>
/// GData schema extension describing a reminder on an event.
/// </summary>
/// <remarks>
/// <para>You can represent a set of reminders where each has a (1) reminder
/// period and (2) notification method. The method can be either "sms",
/// "email", "alert", "none", "all".</para>
///
/// <para>The meaning of this set of reminders differs based on whether you
/// are reading or writing feeds. When reading, the set of reminders
/// returned on an event takes into account both defaults on a
/// parent recurring event (when applicable) as well as the user's
/// defaults on calendar. If there are no gd:reminders returned that
/// means the event has absolutely no reminders. "none" or "all" will
/// not apply in this case.</para>
///
/// <para>Writing is different because we have to be backwards-compatible
/// (see *) with the old way of setting reminders. For easier analysis
/// we describe all the behaviors defined in the table below. (Notice
/// we only include cases for minutes, as the other cases specified in
/// terms of days/hours/absoluteTime can be converted to this case.)</para>
///
/// <para>Notice method is case-sensitive: must be in lowercase!</para>
///
/// <list type="table">
/// <listheader>
/// <term></term>
/// <term>No method or method=all</term>
/// <term>method=none</term>
/// <term>method=email|sms|alert</term>
/// </listheader>
/// <item>
/// <term>No gd:rem</term>
/// <term>*No reminder</term>
/// <term>N/A</term>
/// <term>N/A</term>
/// </item>
/// <item>
/// <term>1 gd:rem</term>
/// <term>*Use user's default settings</term>
/// <term>No reminder</term>
/// <term>InvalidEntryException</term>
/// </item>
/// <item>
/// <term>1 gd:rem min=0</term>
/// <term>*Use user's default settings</term>
/// <term>No reminder</term>
/// <term>InvalidEntryException</term>
/// </item>
/// <item>
/// <term>1 gd:rem min=-1</term>
/// <term>*No reminder</term>
/// <term>No reminder</term>
/// <term>InvalidEntryException</term>
/// </item>
/// <item>
/// <term>1 gd:rem min=+n</term>
/// <term>*Override with no +n for user's selected methods</term>
/// <term>No reminder</term>
/// <term>Set exactly one reminder on event at +n with given method</term>
/// </item>
/// <item>
/// <term>Multiple gd:rem</term>
/// <term>InvalidEntryException</term>
/// <term>InvalidEntryException</term>
/// <term>Copy this set exactly</term>
/// </item>
/// </list>
///
/// <para>Hence, to override an event with a set of reminder time, method
/// pairs, just specify them exactly. To clear an event of all
/// overrides (and go back to inheriting the user's defaults), one can
/// simply specify a single gd:reminder with no extra attributes. To
/// have NO event reminders on an event, either set a single
/// gd:reminder with negative reminder time, or simply update the event
/// with a single gd:reminder method=none.</para>
/// </remarks>
public class Reminder : IExtensionElementFactory
{
/// <summary>
/// the different reminder methods available
/// </summary>
public enum ReminderMethod {
/// <summary>
/// visible alert
/// </summary>
alert,
/// <summary>
/// all alerts
/// </summary>
all,
/// <summary>
/// alert per email
/// </summary>
email,
/// <summary>
/// no aert
/// </summary>
none,
/// <summary>
/// alert per SMS
/// </summary>
sms,
/// <summary>
/// no alert specified (invalid)
/// </summary>
unspecified
};
/// <summary>
/// Number of days before the event.
/// </summary>
private int days;
/// <summary>
/// Number of hours.
/// </summary>
private int hours;
/// <summary>
/// Number of minutes.
/// </summary>
private int minutes;
/// <summary>
/// Absolute time of the reminder.
/// </summary>
private DateTime absoluteTime;
/// <summary>
/// holds the method type
/// </summary>
private ReminderMethod method;
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public Method Method</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public ReminderMethod Method
{
get {return this.method;}
set {this.method = value;}
}
// end of accessor public Method Method
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public Days</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public int Days
{
get { return days;}
set { days = value;}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public Hours</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public int Hours
{
get { return hours;}
set { hours = value;}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public Minutes</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public int Minutes
{
get { return minutes;}
set { minutes = value;}
}
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public absoluteTime</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public DateTime AbsoluteTime
{
get { return absoluteTime;}
set { absoluteTime = value;}
}
#region overloaded from IExtensionElementFactory
//////////////////////////////////////////////////////////////////////
/// <summary>Parses an xml node to create a Reminder object.</summary>
/// <param name="node">the node to parse node</param>
/// <param name="parser">the xml parser to use if we need to dive deeper</param>
/// <returns>the created Reminder object</returns>
//////////////////////////////////////////////////////////////////////
public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
Tracing.TraceCall();
Reminder reminder = null;
if (node != null)
{
object localname = node.LocalName;
if (!localname.Equals(this.XmlName) ||
!node.NamespaceURI.Equals(this.XmlNameSpace))
{
return null;
}
}
reminder = new Reminder();
if (node != null && node.Attributes != null)
{
if (node.Attributes[GDataParserNameTable.XmlAttributeAbsoluteTime] != null)
{
try
{
reminder.AbsoluteTime =
DateTime.Parse(node.Attributes[GDataParserNameTable.XmlAttributeAbsoluteTime].Value);
}
catch (FormatException fe)
{
throw new ArgumentException("Invalid g:reminder/@absoluteTime.", fe);
}
}
if (node.Attributes[GDataParserNameTable.XmlAttributeDays] != null)
{
try
{
reminder.Days = Int32.Parse(node.Attributes[GDataParserNameTable.XmlAttributeDays].Value);
}
catch (FormatException fe)
{
throw new ArgumentException("Invalid g:reminder/@days.", fe);
}
}
if (node.Attributes[GDataParserNameTable.XmlAttributeHours] != null)
{
try
{
reminder.Hours = Int32.Parse(node.Attributes[GDataParserNameTable.XmlAttributeHours].Value);
}
catch (FormatException fe)
{
throw new ArgumentException("Invalid g:reminder/@hours.", fe);
}
}
if (node.Attributes[GDataParserNameTable.XmlAttributeMinutes] != null)
{
try
{
reminder.Minutes = Int32.Parse(node.Attributes[GDataParserNameTable.XmlAttributeMinutes].Value);
}
catch (FormatException fe)
{
throw new ArgumentException("Invalid g:reminder/@minutes.", fe);
}
}
if (node.Attributes[GDataParserNameTable.XmlAttributeMethod] != null)
{
try
{
reminder.Method = (ReminderMethod)Enum.Parse(typeof(ReminderMethod),
node.Attributes[GDataParserNameTable.XmlAttributeMethod].Value,
true);
}
catch (Exception e)
{
throw new ArgumentException("Invalid g:reminder/@method.", e);
}
}
}
return reminder;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public string XmlName
{
get { return GDataParserNameTable.XmlReminderElement;}
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public string XmlNameSpace
{
get { return BaseNameTable.gNamespace; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public string XmlPrefix
{
get { return BaseNameTable.gDataPrefix; }
}
#endregion
/// <summary>
/// Persistence method for the Reminder object
/// </summary>
/// <param name="writer">the xmlwriter to write into</param>
public void Save(XmlWriter writer)
{
writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace);
if (Days > 0)
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeDays, this.Days.ToString());
}
if (Hours > 0)
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHours, this.Hours.ToString());
}
if (Minutes > 0)
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeMinutes, this.Minutes.ToString());
}
if (AbsoluteTime != new DateTime(1, 1, 1))
{
string date = Utilities.LocalDateTimeInUTC(AbsoluteTime);
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeAbsoluteTime, date);
}
if (this.Method != ReminderMethod.unspecified)
{
writer.WriteAttributeString(GDataParserNameTable.XmlAttributeMethod, this.Method.ToString());
}
writer.WriteEndElement();
}
}
}
| |
// 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
using osu.Game.Rulesets.Osu.Utils;
using osuTK;
namespace osu.Game.Rulesets.Osu.Mods
{
/// <summary>
/// Mod that randomises the positions of the <see cref="HitObject"/>s
/// </summary>
public class OsuModRandom : ModRandom, IApplicableToBeatmap
{
public override string Description => "It never gets boring!";
private static readonly float playfield_diagonal = OsuPlayfield.BASE_SIZE.LengthFast;
private static readonly Vector2 playfield_centre = OsuPlayfield.BASE_SIZE / 2;
/// <summary>
/// Number of previous hitobjects to be shifted together when another object is being moved.
/// </summary>
private const int preceding_hitobjects_to_shift = 10;
private Random? rng;
public void ApplyToBeatmap(IBeatmap beatmap)
{
if (!(beatmap is OsuBeatmap osuBeatmap))
return;
var hitObjects = osuBeatmap.HitObjects;
Seed.Value ??= RNG.Next();
rng = new Random((int)Seed.Value);
var randomObjects = randomiseObjects(hitObjects);
applyRandomisation(hitObjects, randomObjects);
}
/// <summary>
/// Randomise the position of each hit object and return a list of <see cref="RandomObjectInfo"/>s describing how each hit object should be placed.
/// </summary>
/// <param name="hitObjects">A list of <see cref="OsuHitObject"/>s to have their positions randomised.</param>
/// <returns>A list of <see cref="RandomObjectInfo"/>s describing how each hit object should be placed.</returns>
private List<RandomObjectInfo> randomiseObjects(IEnumerable<OsuHitObject> hitObjects)
{
Debug.Assert(rng != null, $"{nameof(ApplyToBeatmap)} was not called before randomising objects");
var randomObjects = new List<RandomObjectInfo>();
RandomObjectInfo? previous = null;
float rateOfChangeMultiplier = 0;
foreach (OsuHitObject hitObject in hitObjects)
{
var current = new RandomObjectInfo(hitObject);
randomObjects.Add(current);
// rateOfChangeMultiplier only changes every 5 iterations in a combo
// to prevent shaky-line-shaped streams
if (hitObject.IndexInCurrentCombo % 5 == 0)
rateOfChangeMultiplier = (float)rng.NextDouble() * 2 - 1;
if (previous == null)
{
current.DistanceFromPrevious = (float)(rng.NextDouble() * OsuPlayfield.BASE_SIZE.X / 2);
current.RelativeAngle = (float)(rng.NextDouble() * 2 * Math.PI - Math.PI);
}
else
{
current.DistanceFromPrevious = Vector2.Distance(previous.EndPositionOriginal, current.PositionOriginal);
// The max. angle (relative to the angle of the vector pointing from the 2nd last to the last hit object)
// is proportional to the distance between the last and the current hit object
// to allow jumps and prevent too sharp turns during streams.
// Allow maximum jump angle when jump distance is more than half of playfield diagonal length
current.RelativeAngle = rateOfChangeMultiplier * 2 * (float)Math.PI * Math.Min(1f, current.DistanceFromPrevious / (playfield_diagonal * 0.5f));
}
previous = current;
}
return randomObjects;
}
/// <summary>
/// Reposition the hit objects according to the information in <paramref name="randomObjects"/>.
/// </summary>
/// <param name="hitObjects">The hit objects to be repositioned.</param>
/// <param name="randomObjects">A list of <see cref="RandomObjectInfo"/> describing how each hit object should be placed.</param>
private void applyRandomisation(IReadOnlyList<OsuHitObject> hitObjects, IReadOnlyList<RandomObjectInfo> randomObjects)
{
RandomObjectInfo? previous = null;
for (int i = 0; i < hitObjects.Count; i++)
{
var hitObject = hitObjects[i];
var current = randomObjects[i];
if (hitObject is Spinner)
{
previous = null;
continue;
}
computeRandomisedPosition(current, previous, i > 1 ? randomObjects[i - 2] : null);
// Move hit objects back into the playfield if they are outside of it
Vector2 shift = Vector2.Zero;
switch (hitObject)
{
case HitCircle circle:
shift = clampHitCircleToPlayfield(circle, current);
break;
case Slider slider:
shift = clampSliderToPlayfield(slider, current);
break;
}
if (shift != Vector2.Zero)
{
var toBeShifted = new List<OsuHitObject>();
for (int j = i - 1; j >= i - preceding_hitobjects_to_shift && j >= 0; j--)
{
// only shift hit circles
if (!(hitObjects[j] is HitCircle)) break;
toBeShifted.Add(hitObjects[j]);
}
if (toBeShifted.Count > 0)
applyDecreasingShift(toBeShifted, shift);
}
previous = current;
}
}
/// <summary>
/// Compute the randomised position of a hit object while attempting to keep it inside the playfield.
/// </summary>
/// <param name="current">The <see cref="RandomObjectInfo"/> representing the hit object to have the randomised position computed for.</param>
/// <param name="previous">The <see cref="RandomObjectInfo"/> representing the hit object immediately preceding the current one.</param>
/// <param name="beforePrevious">The <see cref="RandomObjectInfo"/> representing the hit object immediately preceding the <paramref name="previous"/> one.</param>
private void computeRandomisedPosition(RandomObjectInfo current, RandomObjectInfo? previous, RandomObjectInfo? beforePrevious)
{
float previousAbsoluteAngle = 0f;
if (previous != null)
{
Vector2 earliestPosition = beforePrevious?.HitObject.EndPosition ?? playfield_centre;
Vector2 relativePosition = previous.HitObject.Position - earliestPosition;
previousAbsoluteAngle = (float)Math.Atan2(relativePosition.Y, relativePosition.X);
}
float absoluteAngle = previousAbsoluteAngle + current.RelativeAngle;
var posRelativeToPrev = new Vector2(
current.DistanceFromPrevious * (float)Math.Cos(absoluteAngle),
current.DistanceFromPrevious * (float)Math.Sin(absoluteAngle)
);
Vector2 lastEndPosition = previous?.EndPositionRandomised ?? playfield_centre;
posRelativeToPrev = OsuHitObjectGenerationUtils.RotateAwayFromEdge(lastEndPosition, posRelativeToPrev);
current.PositionRandomised = lastEndPosition + posRelativeToPrev;
}
/// <summary>
/// Move the randomised position of a hit circle so that it fits inside the playfield.
/// </summary>
/// <returns>The deviation from the original randomised position in order to fit within the playfield.</returns>
private Vector2 clampHitCircleToPlayfield(HitCircle circle, RandomObjectInfo objectInfo)
{
var previousPosition = objectInfo.PositionRandomised;
objectInfo.EndPositionRandomised = objectInfo.PositionRandomised = clampToPlayfieldWithPadding(
objectInfo.PositionRandomised,
(float)circle.Radius
);
circle.Position = objectInfo.PositionRandomised;
return objectInfo.PositionRandomised - previousPosition;
}
/// <summary>
/// Moves the <see cref="Slider"/> and all necessary nested <see cref="OsuHitObject"/>s into the <see cref="OsuPlayfield"/> if they aren't already.
/// </summary>
/// <returns>The deviation from the original randomised position in order to fit within the playfield.</returns>
private Vector2 clampSliderToPlayfield(Slider slider, RandomObjectInfo objectInfo)
{
var possibleMovementBounds = calculatePossibleMovementBounds(slider);
var previousPosition = objectInfo.PositionRandomised;
// Clamp slider position to the placement area
// If the slider is larger than the playfield, force it to stay at the original position
float newX = possibleMovementBounds.Width < 0
? objectInfo.PositionOriginal.X
: Math.Clamp(previousPosition.X, possibleMovementBounds.Left, possibleMovementBounds.Right);
float newY = possibleMovementBounds.Height < 0
? objectInfo.PositionOriginal.Y
: Math.Clamp(previousPosition.Y, possibleMovementBounds.Top, possibleMovementBounds.Bottom);
slider.Position = objectInfo.PositionRandomised = new Vector2(newX, newY);
objectInfo.EndPositionRandomised = slider.EndPosition;
shiftNestedObjects(slider, objectInfo.PositionRandomised - objectInfo.PositionOriginal);
return objectInfo.PositionRandomised - previousPosition;
}
/// <summary>
/// Decreasingly shift a list of <see cref="OsuHitObject"/>s by a specified amount.
/// The first item in the list is shifted by the largest amount, while the last item is shifted by the smallest amount.
/// </summary>
/// <param name="hitObjects">The list of hit objects to be shifted.</param>
/// <param name="shift">The amount to be shifted.</param>
private void applyDecreasingShift(IList<OsuHitObject> hitObjects, Vector2 shift)
{
for (int i = 0; i < hitObjects.Count; i++)
{
var hitObject = hitObjects[i];
// The first object is shifted by a vector slightly smaller than shift
// The last object is shifted by a vector slightly larger than zero
Vector2 position = hitObject.Position + shift * ((hitObjects.Count - i) / (float)(hitObjects.Count + 1));
hitObject.Position = clampToPlayfieldWithPadding(position, (float)hitObject.Radius);
}
}
/// <summary>
/// Calculates a <see cref="RectangleF"/> which contains all of the possible movements of the slider (in relative X/Y coordinates)
/// such that the entire slider is inside the playfield.
/// </summary>
/// <remarks>
/// If the slider is larger than the playfield, the returned <see cref="RectangleF"/> may have negative width/height.
/// </remarks>
private RectangleF calculatePossibleMovementBounds(Slider slider)
{
var pathPositions = new List<Vector2>();
slider.Path.GetPathToProgress(pathPositions, 0, 1);
float minX = float.PositiveInfinity;
float maxX = float.NegativeInfinity;
float minY = float.PositiveInfinity;
float maxY = float.NegativeInfinity;
// Compute the bounding box of the slider.
foreach (var pos in pathPositions)
{
minX = MathF.Min(minX, pos.X);
maxX = MathF.Max(maxX, pos.X);
minY = MathF.Min(minY, pos.Y);
maxY = MathF.Max(maxY, pos.Y);
}
// Take the circle radius into account.
float radius = (float)slider.Radius;
minX -= radius;
minY -= radius;
maxX += radius;
maxY += radius;
// Given the bounding box of the slider (via min/max X/Y),
// the amount that the slider can move to the left is minX (with the sign flipped, since positive X is to the right),
// and the amount that it can move to the right is WIDTH - maxX.
// Same calculation applies for the Y axis.
float left = -minX;
float right = OsuPlayfield.BASE_SIZE.X - maxX;
float top = -minY;
float bottom = OsuPlayfield.BASE_SIZE.Y - maxY;
return new RectangleF(left, top, right - left, bottom - top);
}
/// <summary>
/// Shifts all nested <see cref="SliderTick"/>s and <see cref="SliderRepeat"/>s by the specified shift.
/// </summary>
/// <param name="slider"><see cref="Slider"/> whose nested <see cref="SliderTick"/>s and <see cref="SliderRepeat"/>s should be shifted</param>
/// <param name="shift">The <see cref="Vector2"/> the <see cref="Slider"/>'s nested <see cref="SliderTick"/>s and <see cref="SliderRepeat"/>s should be shifted by</param>
private void shiftNestedObjects(Slider slider, Vector2 shift)
{
foreach (var hitObject in slider.NestedHitObjects.Where(o => o is SliderTick || o is SliderRepeat))
{
if (!(hitObject is OsuHitObject osuHitObject))
continue;
osuHitObject.Position += shift;
}
}
/// <summary>
/// Clamp a position to playfield, keeping a specified distance from the edges.
/// </summary>
/// <param name="position">The position to be clamped.</param>
/// <param name="padding">The minimum distance allowed from playfield edges.</param>
/// <returns>The clamped position.</returns>
private Vector2 clampToPlayfieldWithPadding(Vector2 position, float padding)
{
return new Vector2(
Math.Clamp(position.X, padding, OsuPlayfield.BASE_SIZE.X - padding),
Math.Clamp(position.Y, padding, OsuPlayfield.BASE_SIZE.Y - padding)
);
}
private class RandomObjectInfo
{
/// <summary>
/// The jump angle from the previous hit object to this one, relative to the previous hit object's jump angle.
/// </summary>
/// <remarks>
/// <see cref="RelativeAngle"/> of the first hit object in a beatmap represents the absolute angle from playfield center to the object.
/// </remarks>
/// <example>
/// If <see cref="RelativeAngle"/> is 0, the player's cursor doesn't need to change its direction of movement when passing
/// the previous object to reach this one.
/// </example>
public float RelativeAngle { get; set; }
/// <summary>
/// The jump distance from the previous hit object to this one.
/// </summary>
/// <remarks>
/// <see cref="DistanceFromPrevious"/> of the first hit object in a beatmap is relative to the playfield center.
/// </remarks>
public float DistanceFromPrevious { get; set; }
public Vector2 PositionOriginal { get; }
public Vector2 PositionRandomised { get; set; }
public Vector2 EndPositionOriginal { get; }
public Vector2 EndPositionRandomised { get; set; }
public OsuHitObject HitObject { get; }
public RandomObjectInfo(OsuHitObject hitObject)
{
PositionRandomised = PositionOriginal = hitObject.Position;
EndPositionRandomised = EndPositionOriginal = hitObject.EndPosition;
HitObject = hitObject;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine.Serialization;
namespace UnityEngine.UI
{
/// <summary>
/// Image is a textured element in the UI hierarchy.
/// </summary>
[AddComponentMenu("UI/Image", 10)]
public class Image : MaskableGraphic, ISerializationCallbackReceiver, ILayoutElement, ICanvasRaycastFilter
{
public enum Type
{
Simple,
Sliced,
Tiled,
Filled
}
public enum FillMethod
{
Horizontal,
Vertical,
Radial90,
Radial180,
Radial360,
}
public enum OriginHorizontal
{
Left,
Right,
}
public enum OriginVertical
{
Bottom,
Top,
}
public enum Origin90
{
BottomLeft,
TopLeft,
TopRight,
BottomRight,
}
public enum Origin180
{
Bottom,
Left,
Top,
Right,
}
public enum Origin360
{
Bottom,
Right,
Top,
Left,
}
[FormerlySerializedAs("m_Frame")]
[SerializeField] private Sprite m_Sprite;
public Sprite sprite { get { return m_Sprite; } set { if (SetPropertyUtility.SetClass(ref m_Sprite, value)) SetAllDirty(); } }
[NonSerialized]
private Sprite m_OverrideSprite;
public Sprite overrideSprite { get { return m_OverrideSprite == null ? sprite : m_OverrideSprite; } set { if (SetPropertyUtility.SetClass(ref m_OverrideSprite, value)) SetAllDirty(); } }
/// How the Image is drawn.
[SerializeField] private Type m_Type = Type.Simple;
public Type type { get { return m_Type; } set { if (SetPropertyUtility.SetStruct(ref m_Type, value)) SetVerticesDirty(); } }
[SerializeField] private bool m_PreserveAspect = false;
public bool preserveAspect { get { return m_PreserveAspect; } set { if (SetPropertyUtility.SetStruct(ref m_PreserveAspect, value)) SetVerticesDirty(); } }
[SerializeField] private bool m_FillCenter = true;
public bool fillCenter { get { return m_FillCenter; } set { if (SetPropertyUtility.SetStruct(ref m_FillCenter, value)) SetVerticesDirty(); } }
/// Filling method for filled sprites.
[SerializeField] private FillMethod m_FillMethod = FillMethod.Radial360;
public FillMethod fillMethod { get { return m_FillMethod; } set { if (SetPropertyUtility.SetStruct(ref m_FillMethod, value)) {SetVerticesDirty(); m_FillOrigin = 0; } } }
/// Amount of the Image shown. 0-1 range with 0 being nothing shown, and 1 being the full Image.
[Range(0, 1)]
[SerializeField] private float m_FillAmount = 1.0f;
public float fillAmount { get { return m_FillAmount; } set { if (SetPropertyUtility.SetStruct(ref m_FillAmount, Mathf.Clamp01(value))) SetVerticesDirty(); } }
/// Whether the Image should be filled clockwise (true) or counter-clockwise (false).
[SerializeField] private bool m_FillClockwise = true;
public bool fillClockwise { get { return m_FillClockwise; } set { if (SetPropertyUtility.SetStruct(ref m_FillClockwise, value)) SetVerticesDirty(); } }
/// Controls the origin point of the Fill process. Value means different things with each fill method.
[SerializeField] private int m_FillOrigin;
public int fillOrigin { get { return m_FillOrigin; } set { if (SetPropertyUtility.SetStruct(ref m_FillOrigin, value)) SetVerticesDirty(); } }
// Not serialized until we support read-enabled sprites better.
private float m_EventAlphaThreshold = 1;
public float eventAlphaThreshold { get { return m_EventAlphaThreshold; } set { m_EventAlphaThreshold = value; } }
protected Image()
{ }
/// <summary>
/// Image's texture comes from the UnityEngine.Image.
/// </summary>
public override Texture mainTexture
{
get
{
return overrideSprite == null ? s_WhiteTexture : overrideSprite.texture;
}
}
/// <summary>
/// Whether the Image has a border to work with.
/// </summary>
public bool hasBorder
{
get
{
if (overrideSprite != null)
{
Vector4 v = overrideSprite.border;
return v.sqrMagnitude > 0f;
}
return false;
}
}
public float pixelsPerUnit
{
get
{
float spritePixelsPerUnit = 100;
if (sprite)
spritePixelsPerUnit = sprite.pixelsPerUnit;
float referencePixelsPerUnit = 100;
if (canvas)
referencePixelsPerUnit = canvas.referencePixelsPerUnit;
return spritePixelsPerUnit / referencePixelsPerUnit;
}
}
public virtual void OnBeforeSerialize() { }
public virtual void OnAfterDeserialize()
{
if (m_FillOrigin < 0)
m_FillOrigin = 0;
else if (m_FillMethod == FillMethod.Horizontal && m_FillOrigin > 1)
m_FillOrigin = 0;
else if (m_FillMethod == FillMethod.Vertical && m_FillOrigin > 1)
m_FillOrigin = 0;
else if (m_FillOrigin > 3)
m_FillOrigin = 0;
m_FillAmount = Mathf.Clamp(m_FillAmount, 0f, 1f);
}
/// Image's dimensions used for drawing. X = left, Y = bottom, Z = right, W = top.
private Vector4 GetDrawingDimensions(bool shouldPreserveAspect)
{
var padding = overrideSprite == null ? Vector4.zero : Sprites.DataUtility.GetPadding(overrideSprite);
var size = overrideSprite == null ? Vector2.zero : new Vector2(overrideSprite.rect.width, overrideSprite.rect.height);
Rect r = GetPixelAdjustedRect();
// Debug.Log(string.Format("r:{2}, size:{0}, padding:{1}", size, padding, r));
int spriteW = Mathf.RoundToInt(size.x);
int spriteH = Mathf.RoundToInt(size.y);
var v = new Vector4(
padding.x / spriteW,
padding.y / spriteH,
(spriteW - padding.z) / spriteW,
(spriteH - padding.w) / spriteH);
if (shouldPreserveAspect && size.sqrMagnitude > 0.0f)
{
var spriteRatio = size.x / size.y;
var rectRatio = r.width / r.height;
if (spriteRatio > rectRatio)
{
var oldHeight = r.height;
r.height = r.width * (1.0f / spriteRatio);
r.y += (oldHeight - r.height) * rectTransform.pivot.y;
}
else
{
var oldWidth = r.width;
r.width = r.height * spriteRatio;
r.x += (oldWidth - r.width) * rectTransform.pivot.x;
}
}
v = new Vector4(
r.x + r.width * v.x,
r.y + r.height * v.y,
r.x + r.width * v.z,
r.y + r.height * v.w
);
return v;
}
public override void SetNativeSize()
{
if (overrideSprite != null)
{
float w = overrideSprite.rect.width / pixelsPerUnit;
float h = overrideSprite.rect.height / pixelsPerUnit;
rectTransform.anchorMax = rectTransform.anchorMin;
rectTransform.sizeDelta = new Vector2(w, h);
SetAllDirty();
}
}
/// <summary>
/// Update the UI renderer mesh.
/// </summary>
protected override void OnFillVBO(List<UIVertex> vbo)
{
if (overrideSprite == null)
{
base.OnFillVBO(vbo);
return;
}
switch (type)
{
case Type.Simple:
GenerateSimpleSprite(vbo, m_PreserveAspect);
break;
case Type.Sliced:
GenerateSlicedSprite(vbo);
break;
case Type.Tiled:
GenerateTiledSprite(vbo);
break;
case Type.Filled:
GenerateFilledSprite(vbo, m_PreserveAspect);
break;
}
}
#region Various fill functions
/// <summary>
/// Generate vertices for a simple Image.
/// </summary>
void GenerateSimpleSprite(List<UIVertex> vbo, bool preserveAspect)
{
var vert = UIVertex.simpleVert;
vert.color = color;
Vector4 v = GetDrawingDimensions(preserveAspect);
var uv = (overrideSprite != null) ? Sprites.DataUtility.GetOuterUV(overrideSprite) : Vector4.zero;
vert.position = new Vector3(v.x, v.y);
vert.uv0 = new Vector2(uv.x, uv.y);
vbo.Add(vert);
vert.position = new Vector3(v.x, v.w);
vert.uv0 = new Vector2(uv.x, uv.w);
vbo.Add(vert);
vert.position = new Vector3(v.z, v.w);
vert.uv0 = new Vector2(uv.z, uv.w);
vbo.Add(vert);
vert.position = new Vector3(v.z, v.y);
vert.uv0 = new Vector2(uv.z, uv.y);
vbo.Add(vert);
}
/// <summary>
/// Generate vertices for a 9-sliced Image.
/// </summary>
static readonly Vector2[] s_VertScratch = new Vector2[4];
static readonly Vector2[] s_UVScratch = new Vector2[4];
void GenerateSlicedSprite(List<UIVertex> vbo)
{
if (!hasBorder)
{
GenerateSimpleSprite(vbo, false);
return;
}
Vector4 outer, inner, padding, border;
if (overrideSprite != null)
{
outer = Sprites.DataUtility.GetOuterUV(overrideSprite);
inner = Sprites.DataUtility.GetInnerUV(overrideSprite);
padding = Sprites.DataUtility.GetPadding(overrideSprite);
border = overrideSprite.border;
}
else
{
outer = Vector4.zero;
inner = Vector4.zero;
padding = Vector4.zero;
border = Vector4.zero;
}
Rect rect = GetPixelAdjustedRect();
border = GetAdjustedBorders(border / pixelsPerUnit, rect);
s_VertScratch[0] = new Vector2(padding.x, padding.y);
s_VertScratch[3] = new Vector2(rect.width - padding.z, rect.height - padding.w);
s_VertScratch[1].x = border.x;
s_VertScratch[1].y = border.y;
s_VertScratch[2].x = rect.width - border.z;
s_VertScratch[2].y = rect.height - border.w;
for (int i = 0; i < 4; ++i)
{
s_VertScratch[i].x += rect.x;
s_VertScratch[i].y += rect.y;
}
s_UVScratch[0] = new Vector2(outer.x, outer.y);
s_UVScratch[1] = new Vector2(inner.x, inner.y);
s_UVScratch[2] = new Vector2(inner.z, inner.w);
s_UVScratch[3] = new Vector2(outer.z, outer.w);
var uiv = UIVertex.simpleVert;
uiv.color = color;
for (int x = 0; x < 3; ++x)
{
int x2 = x + 1;
for (int y = 0; y < 3; ++y)
{
if (!m_FillCenter && x == 1 && y == 1)
{
continue;
}
int y2 = y + 1;
AddQuad(vbo, uiv,
new Vector2(s_VertScratch[x].x, s_VertScratch[y].y),
new Vector2(s_VertScratch[x2].x, s_VertScratch[y2].y),
new Vector2(s_UVScratch[x].x, s_UVScratch[y].y),
new Vector2(s_UVScratch[x2].x, s_UVScratch[y2].y));
}
}
}
/// <summary>
/// Generate vertices for a tiled Image.
/// </summary>
void GenerateTiledSprite(List<UIVertex> vbo)
{
Vector4 outer, inner, border;
Vector2 spriteSize;
if (overrideSprite != null)
{
outer = Sprites.DataUtility.GetOuterUV(overrideSprite);
inner = Sprites.DataUtility.GetInnerUV(overrideSprite);
border = overrideSprite.border;
spriteSize = overrideSprite.rect.size;
}
else
{
outer = Vector4.zero;
inner = Vector4.zero;
border = Vector4.zero;
spriteSize = Vector2.one * 100;
}
Rect rect = GetPixelAdjustedRect();
float tileWidth = (spriteSize.x - border.x - border.z) / pixelsPerUnit;
float tileHeight = (spriteSize.y - border.y - border.w) / pixelsPerUnit;
border = GetAdjustedBorders(border / pixelsPerUnit, rect);
var uvMin = new Vector2(inner.x, inner.y);
var uvMax = new Vector2(inner.z, inner.w);
var v = UIVertex.simpleVert;
v.color = color;
// Min to max max range for tiled region in coordinates relative to lower left corner.
float xMin = border.x;
float xMax = rect.width - border.z;
float yMin = border.y;
float yMax = rect.height - border.w;
// Safety check. Useful so Unity doesn't run out of memory if the sprites are too small.
// Max tiles are 100 x 100.
if ((xMax - xMin) > tileWidth * 100 || (yMax - yMin) > tileHeight * 100)
{
tileWidth = (xMax - xMin) / 100;
tileHeight = (yMax - yMin) / 100;
}
var clipped = uvMax;
if (m_FillCenter)
{
for (float y1 = yMin; y1 < yMax; y1 += tileHeight)
{
float y2 = y1 + tileHeight;
if (y2 > yMax)
{
clipped.y = uvMin.y + (uvMax.y - uvMin.y) * (yMax - y1) / (y2 - y1);
y2 = yMax;
}
clipped.x = uvMax.x;
for (float x1 = xMin; x1 < xMax; x1 += tileWidth)
{
float x2 = x1 + tileWidth;
if (x2 > xMax)
{
clipped.x = uvMin.x + (uvMax.x - uvMin.x) * (xMax - x1) / (x2 - x1);
x2 = xMax;
}
AddQuad(vbo, v, new Vector2(x1, y1) + rect.position, new Vector2(x2, y2) + rect.position, uvMin, clipped);
}
}
}
if (!hasBorder)
return;
// Left and right tiled border
clipped = uvMax;
for (float y1 = yMin; y1 < yMax; y1 += tileHeight)
{
float y2 = y1 + tileHeight;
if (y2 > yMax)
{
clipped.y = uvMin.y + (uvMax.y - uvMin.y) * (yMax - y1) / (y2 - y1);
y2 = yMax;
}
AddQuad(vbo, v,
new Vector2(0, y1) + rect.position,
new Vector2(xMin, y2) + rect.position,
new Vector2(outer.x, uvMin.y),
new Vector2(uvMin.x, clipped.y));
AddQuad(vbo, v,
new Vector2(xMax, y1) + rect.position,
new Vector2(rect.width, y2) + rect.position,
new Vector2(uvMax.x, uvMin.y),
new Vector2(outer.z, clipped.y));
}
// Bottom and top tiled border
clipped = uvMax;
for (float x1 = xMin; x1 < xMax; x1 += tileWidth)
{
float x2 = x1 + tileWidth;
if (x2 > xMax)
{
clipped.x = uvMin.x + (uvMax.x - uvMin.x) * (xMax - x1) / (x2 - x1);
x2 = xMax;
}
AddQuad(vbo, v,
new Vector2(x1, 0) + rect.position,
new Vector2(x2, yMin) + rect.position,
new Vector2(uvMin.x, outer.y),
new Vector2(clipped.x, uvMin.y));
AddQuad(vbo, v,
new Vector2(x1, yMax) + rect.position,
new Vector2(x2, rect.height) + rect.position,
new Vector2(uvMin.x, uvMax.y),
new Vector2(clipped.x, outer.w));
}
// Corners
AddQuad(vbo, v,
new Vector2(0, 0) + rect.position,
new Vector2(xMin, yMin) + rect.position,
new Vector2(outer.x, outer.y),
new Vector2(uvMin.x, uvMin.y));
AddQuad(vbo, v,
new Vector2(xMax, 0) + rect.position,
new Vector2(rect.width, yMin) + rect.position,
new Vector2(uvMax.x, outer.y),
new Vector2(outer.z, uvMin.y));
AddQuad(vbo, v,
new Vector2(0, yMax) + rect.position,
new Vector2(xMin, rect.height) + rect.position,
new Vector2(outer.x, uvMax.y),
new Vector2(uvMin.x, outer.w));
AddQuad(vbo, v,
new Vector2(xMax, yMax) + rect.position,
new Vector2(rect.width, rect.height) + rect.position,
new Vector2(uvMax.x, uvMax.y),
new Vector2(outer.z, outer.w));
}
void AddQuad(List<UIVertex> vbo, UIVertex v, Vector2 posMin, Vector2 posMax, Vector2 uvMin, Vector2 uvMax)
{
v.position = new Vector3(posMin.x, posMin.y, 0);
v.uv0 = new Vector2(uvMin.x, uvMin.y);
vbo.Add(v);
v.position = new Vector3(posMin.x, posMax.y, 0);
v.uv0 = new Vector2(uvMin.x, uvMax.y);
vbo.Add(v);
v.position = new Vector3(posMax.x, posMax.y, 0);
v.uv0 = new Vector2(uvMax.x, uvMax.y);
vbo.Add(v);
v.position = new Vector3(posMax.x, posMin.y, 0);
v.uv0 = new Vector2(uvMax.x, uvMin.y);
vbo.Add(v);
}
Vector4 GetAdjustedBorders(Vector4 border, Rect rect)
{
for (int axis = 0; axis <= 1; axis++)
{
// If the rect is smaller than the combined borders, then there's not room for the borders at their normal size.
// In order to avoid artefacts with overlapping borders, we scale the borders down to fit.
float combinedBorders = border[axis] + border[axis + 2];
if (rect.size[axis] < combinedBorders && combinedBorders != 0)
{
float borderScaleRatio = rect.size[axis] / combinedBorders;
border[axis] *= borderScaleRatio;
border[axis + 2] *= borderScaleRatio;
}
}
return border;
}
/// <summary>
/// Generate vertices for a filled Image.
/// </summary>
static readonly Vector2[] s_Xy = new Vector2[4];
static readonly Vector2[] s_Uv = new Vector2[4];
void GenerateFilledSprite(List<UIVertex> vbo, bool preserveAspect)
{
if (m_FillAmount < 0.001f)
return;
Vector4 v = GetDrawingDimensions(preserveAspect);
Vector4 outer = overrideSprite != null ? Sprites.DataUtility.GetOuterUV(overrideSprite) : Vector4.zero;
UIVertex uiv = UIVertex.simpleVert;
uiv.color = color;
float tx0 = outer.x;
float ty0 = outer.y;
float tx1 = outer.z;
float ty1 = outer.w;
// Horizontal and vertical filled sprites are simple -- just end the Image prematurely
if (m_FillMethod == FillMethod.Horizontal || m_FillMethod == FillMethod.Vertical)
{
if (fillMethod == FillMethod.Horizontal)
{
float fill = (tx1 - tx0) * m_FillAmount;
if (m_FillOrigin == 1)
{
v.x = v.z - (v.z - v.x) * m_FillAmount;
tx0 = tx1 - fill;
}
else
{
v.z = v.x + (v.z - v.x) * m_FillAmount;
tx1 = tx0 + fill;
}
}
else if (fillMethod == FillMethod.Vertical)
{
float fill = (ty1 - ty0) * m_FillAmount;
if (m_FillOrigin == 1)
{
v.y = v.w - (v.w - v.y) * m_FillAmount;
ty0 = ty1 - fill;
}
else
{
v.w = v.y + (v.w - v.y) * m_FillAmount;
ty1 = ty0 + fill;
}
}
}
s_Xy[0] = new Vector2(v.x, v.y);
s_Xy[1] = new Vector2(v.x, v.w);
s_Xy[2] = new Vector2(v.z, v.w);
s_Xy[3] = new Vector2(v.z, v.y);
s_Uv[0] = new Vector2(tx0, ty0);
s_Uv[1] = new Vector2(tx0, ty1);
s_Uv[2] = new Vector2(tx1, ty1);
s_Uv[3] = new Vector2(tx1, ty0);
if (m_FillAmount < 1f)
{
if (fillMethod == FillMethod.Radial90)
{
if (RadialCut(s_Xy, s_Uv, m_FillAmount, m_FillClockwise, m_FillOrigin))
{
for (int i = 0; i < 4; ++i)
{
uiv.position = s_Xy[i];
uiv.uv0 = s_Uv[i];
vbo.Add(uiv);
}
}
return;
}
if (fillMethod == FillMethod.Radial180)
{
for (int side = 0; side < 2; ++side)
{
float fx0, fx1, fy0, fy1;
int even = m_FillOrigin > 1 ? 1 : 0;
if (m_FillOrigin == 0 || m_FillOrigin == 2)
{
fy0 = 0f;
fy1 = 1f;
if (side == even) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
}
else
{
fx0 = 0f;
fx1 = 1f;
if (side == even) { fy0 = 0.5f; fy1 = 1f; }
else { fy0 = 0f; fy1 = 0.5f; }
}
s_Xy[0].x = Mathf.Lerp(v.x, v.z, fx0);
s_Xy[1].x = s_Xy[0].x;
s_Xy[2].x = Mathf.Lerp(v.x, v.z, fx1);
s_Xy[3].x = s_Xy[2].x;
s_Xy[0].y = Mathf.Lerp(v.y, v.w, fy0);
s_Xy[1].y = Mathf.Lerp(v.y, v.w, fy1);
s_Xy[2].y = s_Xy[1].y;
s_Xy[3].y = s_Xy[0].y;
s_Uv[0].x = Mathf.Lerp(tx0, tx1, fx0);
s_Uv[1].x = s_Uv[0].x;
s_Uv[2].x = Mathf.Lerp(tx0, tx1, fx1);
s_Uv[3].x = s_Uv[2].x;
s_Uv[0].y = Mathf.Lerp(ty0, ty1, fy0);
s_Uv[1].y = Mathf.Lerp(ty0, ty1, fy1);
s_Uv[2].y = s_Uv[1].y;
s_Uv[3].y = s_Uv[0].y;
float val = m_FillClockwise ? fillAmount * 2f - side : m_FillAmount * 2f - (1 - side);
if (RadialCut(s_Xy, s_Uv, Mathf.Clamp01(val), m_FillClockwise, ((side + m_FillOrigin + 3) % 4)))
{
for (int i = 0; i < 4; ++i)
{
uiv.position = s_Xy[i];
uiv.uv0 = s_Uv[i];
vbo.Add(uiv);
}
}
}
return;
}
if (fillMethod == FillMethod.Radial360)
{
for (int corner = 0; corner < 4; ++corner)
{
float fx0, fx1, fy0, fy1;
if (corner < 2) { fx0 = 0f; fx1 = 0.5f; }
else { fx0 = 0.5f; fx1 = 1f; }
if (corner == 0 || corner == 3) { fy0 = 0f; fy1 = 0.5f; }
else { fy0 = 0.5f; fy1 = 1f; }
s_Xy[0].x = Mathf.Lerp(v.x, v.z, fx0);
s_Xy[1].x = s_Xy[0].x;
s_Xy[2].x = Mathf.Lerp(v.x, v.z, fx1);
s_Xy[3].x = s_Xy[2].x;
s_Xy[0].y = Mathf.Lerp(v.y, v.w, fy0);
s_Xy[1].y = Mathf.Lerp(v.y, v.w, fy1);
s_Xy[2].y = s_Xy[1].y;
s_Xy[3].y = s_Xy[0].y;
s_Uv[0].x = Mathf.Lerp(tx0, tx1, fx0);
s_Uv[1].x = s_Uv[0].x;
s_Uv[2].x = Mathf.Lerp(tx0, tx1, fx1);
s_Uv[3].x = s_Uv[2].x;
s_Uv[0].y = Mathf.Lerp(ty0, ty1, fy0);
s_Uv[1].y = Mathf.Lerp(ty0, ty1, fy1);
s_Uv[2].y = s_Uv[1].y;
s_Uv[3].y = s_Uv[0].y;
float val = m_FillClockwise ?
m_FillAmount * 4f - ((corner + m_FillOrigin) % 4) :
m_FillAmount * 4f - (3 - ((corner + m_FillOrigin) % 4));
if (RadialCut(s_Xy, s_Uv, Mathf.Clamp01(val), m_FillClockwise, ((corner + 2) % 4)))
{
for (int i = 0; i < 4; ++i)
{
uiv.position = s_Xy[i];
uiv.uv0 = s_Uv[i];
vbo.Add(uiv);
}
}
}
return;
}
}
// Fill the buffer with the quad for the Image
for (int i = 0; i < 4; ++i)
{
uiv.position = s_Xy[i];
uiv.uv0 = s_Uv[i];
vbo.Add(uiv);
}
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static bool RadialCut(Vector2[] xy, Vector2[] uv, float fill, bool invert, int corner)
{
// Nothing to fill
if (fill < 0.001f) return false;
// Even corners invert the fill direction
if ((corner & 1) == 1) invert = !invert;
// Nothing to adjust
if (!invert && fill > 0.999f) return true;
// Convert 0-1 value into 0 to 90 degrees angle in radians
float angle = Mathf.Clamp01(fill);
if (invert) angle = 1f - angle;
angle *= 90f * Mathf.Deg2Rad;
// Calculate the effective X and Y factors
float cos = Mathf.Cos(angle);
float sin = Mathf.Sin(angle);
RadialCut(xy, cos, sin, invert, corner);
RadialCut(uv, cos, sin, invert, corner);
return true;
}
/// <summary>
/// Adjust the specified quad, making it be radially filled instead.
/// </summary>
static void RadialCut(Vector2[] xy, float cos, float sin, bool invert, int corner)
{
int i0 = corner;
int i1 = ((corner + 1) % 4);
int i2 = ((corner + 2) % 4);
int i3 = ((corner + 3) % 4);
if ((corner & 1) == 1)
{
if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i2].x = xy[i1].x;
}
}
else if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i2].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i3].y = xy[i2].y;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (!invert) xy[i3].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
else xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
}
else
{
if (cos > sin)
{
sin /= cos;
cos = 1f;
if (!invert)
{
xy[i1].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
xy[i2].y = xy[i1].y;
}
}
else if (sin > cos)
{
cos /= sin;
sin = 1f;
if (invert)
{
xy[i2].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
xy[i3].x = xy[i2].x;
}
}
else
{
cos = 1f;
sin = 1f;
}
if (invert) xy[i3].y = Mathf.Lerp(xy[i0].y, xy[i2].y, sin);
else xy[i1].x = Mathf.Lerp(xy[i0].x, xy[i2].x, cos);
}
}
#endregion
public virtual void CalculateLayoutInputHorizontal() { }
public virtual void CalculateLayoutInputVertical() { }
public virtual float minWidth { get { return 0; } }
public virtual float preferredWidth
{
get
{
if (overrideSprite == null)
return 0;
if (type == Type.Sliced || type == Type.Tiled)
return Sprites.DataUtility.GetMinSize(overrideSprite).x / pixelsPerUnit;
return overrideSprite.rect.size.x / pixelsPerUnit;
}
}
public virtual float flexibleWidth { get { return -1; } }
public virtual float minHeight { get { return 0; } }
public virtual float preferredHeight
{
get
{
if (overrideSprite == null)
return 0;
if (type == Type.Sliced || type == Type.Tiled)
return Sprites.DataUtility.GetMinSize(overrideSprite).y / pixelsPerUnit;
return overrideSprite.rect.size.y / pixelsPerUnit;
}
}
public virtual float flexibleHeight { get { return -1; } }
public virtual int layoutPriority { get { return 0; } }
public virtual bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
{
if (m_EventAlphaThreshold >= 1)
return true;
Sprite sprite = overrideSprite;
if (sprite == null)
return true;
Vector2 local;
RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPoint, eventCamera, out local);
Rect rect = GetPixelAdjustedRect();
// Convert to have lower left corner as reference point.
local.x += rectTransform.pivot.x * rect.width;
local.y += rectTransform.pivot.y * rect.height;
local = MapCoordinate(local, rect);
// Normalize local coordinates.
Rect spriteRect = sprite.textureRect;
Vector2 normalized = new Vector2(local.x / spriteRect.width, local.y / spriteRect.height);
// Convert to texture space.
float x = Mathf.Lerp(spriteRect.x, spriteRect.xMax, normalized.x) / sprite.texture.width;
float y = Mathf.Lerp(spriteRect.y, spriteRect.yMax, normalized.y) / sprite.texture.height;
try
{
return sprite.texture.GetPixelBilinear(x, y).a >= m_EventAlphaThreshold;
}
catch (UnityException e)
{
Debug.LogError("Using clickAlphaThreshold lower than 1 on Image whose sprite texture cannot be read. " + e.Message + " Also make sure to disable sprite packing for this sprite.", this);
return true;
}
}
private Vector2 MapCoordinate(Vector2 local, Rect rect)
{
Rect spriteRect = sprite.rect;
if (type == Type.Simple || type == Type.Filled)
return new Vector2(local.x * spriteRect.width / rect.width, local.y * spriteRect.height / rect.height);
Vector4 border = sprite.border;
Vector4 adjustedBorder = GetAdjustedBorders(border / pixelsPerUnit, rect);
for (int i = 0; i < 2; i++)
{
if (local[i] <= adjustedBorder[i])
continue;
if (rect.size[i] - local[i] <= adjustedBorder[i + 2])
{
local[i] -= (rect.size[i] - spriteRect.size[i]);
continue;
}
if (type == Type.Sliced)
{
float lerp = Mathf.InverseLerp(adjustedBorder[i], rect.size[i] - adjustedBorder[i + 2], local[i]);
local[i] = Mathf.Lerp(border[i], spriteRect.size[i] - border[i + 2], lerp);
continue;
}
else
{
local[i] -= adjustedBorder[i];
local[i] = Mathf.Repeat(local[i], spriteRect.size[i] - border[i] - border[i + 2]);
local[i] += border[i];
continue;
}
}
return local;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WngCodingTask.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using java.lang;
using java.util;
using org.objectweb.asm;
namespace stab.reflection {
public class ParameterBuilder : ParameterInfo {
private MethodBuilder method;
ParameterBuilder(MethodBuilder method, int position, TypeInfo type)
: super(position, type) {
this.method = method;
this.annotations = new ArrayList<AnnotationValue>();
}
public void setName(String name) {
method.checkCreated();
this.name = name;
}
public AnnotationValueBuilder addAnnotation(TypeInfo type, bool runtimeVisible) {
method.checkCreated();
var result = new AnnotationValueBuilder(type, runtimeVisible);
annotations.add(result);
return result;
}
}
public class MethodBuilder : MethodInfo {
private int modifiers;
private TypeInfo returnType;
private ArrayList<ParameterInfo> parameters;
private ArrayList<TypeInfo> exceptions;
private ArrayList<TypeInfo> genericArguments;
private String descriptor;
private ArrayList<AnnotationValue> annotations;
private CodeGenerator codeGenerator;
private AnnotationValue defaultValue;
MethodBuilder(TypeInfo declaringType, String name)
: super(declaringType, name) {
parameters = new ArrayList<ParameterInfo>();
exceptions = new ArrayList<TypeInfo>();
genericArguments = new ArrayList<TypeInfo>();
annotations = new ArrayList<AnnotationValue>();
codeGenerator = new CodeGenerator(this);
}
public CodeGenerator CodeGenerator {
get {
checkCreated();
return codeGenerator;
}
}
public override TypeInfo ReturnType {
get {
return returnType;
}
}
public void setReturnType(TypeInfo returnType) {
checkCreated();
this.returnType = returnType;
}
public override Iterable<TypeInfo> GenericArguments {
get {
return genericArguments;
}
}
public TypeInfo addGenericArgument(String name) {
checkCreated();
var type = new GenericParameterType(this.DeclaringType.Library, name, null);
genericArguments.add(type);
return type;
}
public void addGenericConstraint(String name, TypeInfo bound) {
checkCreated();
foreach (var arg in genericArguments) {
if (arg.FullName.equals(name)) {
((GenericParameterType)arg).genericParameterBounds.add(bound);
return;
}
}
throw new IllegalStateException("name = " + name);
}
public override Iterable<ParameterInfo> Parameters {
get {
return parameters;
}
}
public ParameterBuilder addParameter(TypeInfo type) {
checkCreated();
var p = new ParameterBuilder(this, parameters.size(), type);
parameters.add(p);
return p;
}
public override Iterable<TypeInfo> Exceptions {
get {
return exceptions;
}
}
public void addException(TypeInfo exception) {
checkCreated();
exceptions.add(exception);
}
public override Iterable<AnnotationValue> Annotations {
get {
return annotations;
}
}
public AnnotationValueBuilder addAnnotation(TypeInfo type, bool runtimeVisible) {
checkCreated();
var result = new AnnotationValueBuilder(type, runtimeVisible);
annotations.add(result);
return result;
}
public override AnnotationArgument DefaultValue {
get {
return defaultValue;
}
}
public void setDefaultValue(AnnotationValue defaultValue) {
checkCreated();
this.defaultValue = defaultValue;
}
public override String Descriptor {
get {
var result = descriptor;
if (this.IsCreated || descriptor == null) {
var sb = new StringBuilder();
sb.append("(");
foreach (var p in this.Parameters) {
sb.append(p.Type.Descriptor);
}
sb.append(")");
sb.append(returnType.Descriptor);
result = sb.toString();
}
if (this.IsCreated && descriptor == null) {
descriptor = result;
}
return result;
}
}
public override String Signature {
get {
var result = signature;
if (this.IsCreated || signature == null) {
result = ReflectionHelper.getMethodTypeSignature(this);
}
if (this.IsCreated && signature == null) {
signature = result;
}
return result;
}
}
public void setAbstract(bool value) {
setModifiers(Opcodes.ACC_ABSTRACT, value);
}
public void setBridge(bool value) {
setModifiers(Opcodes.ACC_BRIDGE, value);
}
public void setFinal(bool value) {
setModifiers(Opcodes.ACC_FINAL, value);
}
public void setNative(bool value) {
setModifiers(Opcodes.ACC_NATIVE, value);
}
public void setPrivate(bool value) {
setModifiers(Opcodes.ACC_PRIVATE, value);
}
public void setProtected(bool value) {
setModifiers(Opcodes.ACC_PROTECTED, value);
}
public void setPublic(bool value) {
setModifiers(Opcodes.ACC_PUBLIC, value);
}
public void setStatic(bool value) {
setModifiers(Opcodes.ACC_STATIC, value);
}
public void setStrict(bool value) {
setModifiers(Opcodes.ACC_STRICT, value);
}
public void setSynchronized(bool value) {
setModifiers(Opcodes.ACC_SYNCHRONIZED, value);
}
public void setSynthetic(bool value) {
setModifiers(Opcodes.ACC_SYNTHETIC, value);
}
public void setVarargs(bool value) {
setModifiers(Opcodes.ACC_VARARGS, value);
}
protected override int Modifiers {
get {
return modifiers;
}
}
private void setModifiers(int modifiers, bool value) {
checkCreated();
if (value) {
this.modifiers |= modifiers;
} else {
this.modifiers &= ~modifiers;
}
}
void accept(MethodVisitor visitor) {
if (defaultValue != null) {
var v = visitor.visitAnnotationDefault();
defaultValue.accept(v);
v.visitEnd();
}
foreach (var p in parameters) {
foreach (var a in p.Annotations) {
a.accept(visitor.visitParameterAnnotation(p.Position, a.Type.Descriptor, a.IsRuntimeVisible));
}
}
foreach (var a in annotations) {
a.accept(visitor.visitAnnotation(a.Type.Descriptor, a.IsRuntimeVisible));
}
codeGenerator.accept(visitor);
visitor.visitEnd();
codeGenerator = null;
}
void checkCreated() {
((TypeBuilder)this.DeclaringType).checkCreated();
}
bool IsCreated {
get {
return ((TypeBuilder)this.DeclaringType).created;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public sealed class CommandLineBuilderTest
{
/*
* Method: AppendSwitchSimple
*
* Just append a simple switch.
*/
[Fact]
public void AppendSwitchSimple()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/a");
c.AppendSwitch("-b");
c.ShouldBe("/a -b");
}
/*
* Method: AppendSwitchWithStringParameter
*
* Append a switch that has a string parameter.
*/
[Fact]
public void AppendSwitchWithStringParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/animal:", "dog");
c.ShouldBe("/animal:dog");
}
/*
* Method: AppendSwitchWithSpacesInParameter
*
* This should trigger implicit quoting.
*/
[Fact]
public void AppendSwitchWithSpacesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/animal:", "dog and pony");
c.ShouldBe("/animal:\"dog and pony\"");
}
/// <summary>
/// Test for AppendSwitchIfNotNull for the ITaskItem version
/// </summary>
[Fact]
public void AppendSwitchWithSpacesInParameterTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/animal:", new TaskItem("dog and pony"));
c.ShouldBe("/animal:\"dog and pony\"");
}
/*
* Method: AppendLiteralSwitchWithSpacesInParameter
*
* Implicit quoting should not happen.
*/
[Fact]
public void AppendLiteralSwitchWithSpacesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchUnquotedIfNotNull("/animal:", "dog and pony");
c.ShouldBe("/animal:dog and pony");
}
/*
* Method: AppendTwoStringsEnsureNoSpace
*
* When appending two comma-delimited strings, there should be no space before the comma.
*/
[Fact]
public void AppendTwoStringsEnsureNoSpace()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "Form1.resx", FileUtilities.FixFilePath("built\\Form1.resources") }, ",");
// There shouldn't be a space before or after the comma
// Tools like resgen require comma-delimited lists to be bumped up next to each other.
c.ShouldBe(FileUtilities.FixFilePath(@"Form1.resx,built\Form1.resources"));
}
/*
* Method: AppendSourcesArray
*
* Append several sources files using JoinAppend
*/
[Fact]
public void AppendSourcesArray()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "Mercury.cs", "Venus.cs", "Earth.cs" }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe(@"Mercury.cs Venus.cs Earth.cs");
}
/*
* Method: AppendSourcesArrayWithDashes
*
* Append several sources files starting with dashes using JoinAppend
*/
[Fact]
public void AppendSourcesArrayWithDashes()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "-Mercury.cs", "-Venus.cs", "-Earth.cs" }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe($".{Path.DirectorySeparatorChar}-Mercury.cs .{Path.DirectorySeparatorChar}-Venus.cs .{Path.DirectorySeparatorChar}-Earth.cs");
}
/// <summary>
/// Test AppendFileNamesIfNotNull, the ITaskItem version
/// </summary>
[Fact]
public void AppendSourcesArrayWithDashesTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { new TaskItem("-Mercury.cs"), null, new TaskItem("Venus.cs"), new TaskItem("-Earth.cs") }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe($".{Path.DirectorySeparatorChar}-Mercury.cs Venus.cs .{Path.DirectorySeparatorChar}-Earth.cs");
}
/*
* Method: JoinAppendEmpty
*
* Append an empty array. Result should be NOP.
*/
[Fact]
public void JoinAppendEmpty()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "" }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe("");
}
/*
* Method: JoinAppendNull
*
* Append an empty array. Result should be NOP.
*/
[Fact]
public void JoinAppendNull()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull((string[])null, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe("");
}
/// <summary>
/// Append a switch with parameter array, quoting
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayQuoting()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchIfNotNull("/switch:", new[] { "Mer cury.cs", "Ve nus.cs", "Ear th.cs" }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:\"Mer cury.cs\",\"Ve nus.cs\",\"Ear th.cs\"");
}
/// <summary>
/// Append a switch with parameter array, quoting, ITaskItem version
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayQuotingTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchIfNotNull("/switch:", new[] { new TaskItem("Mer cury.cs"), null, new TaskItem("Ve nus.cs"), new TaskItem("Ear th.cs") }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:\"Mer cury.cs\",,\"Ve nus.cs\",\"Ear th.cs\"");
}
/// <summary>
/// Append a switch with parameter array, no quoting
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayNoQuoting()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchUnquotedIfNotNull("/switch:", new[] { "Mer cury.cs", "Ve nus.cs", "Ear th.cs" }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:Mer cury.cs,Ve nus.cs,Ear th.cs");
}
/// <summary>
/// Append a switch with parameter array, no quoting, ITaskItem version
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayNoQuotingTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchUnquotedIfNotNull("/switch:", new[] { new TaskItem("Mer cury.cs"), null, new TaskItem("Ve nus.cs"), new TaskItem("Ear th.cs") }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:Mer cury.cs,,Ve nus.cs,Ear th.cs");
}
/// <summary>
/// Appends a single file name
/// </summary>
[Fact]
public void AppendSingleFileName()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendFileNameIfNotNull("-Mercury.cs");
c.AppendFileNameIfNotNull("Mercury.cs");
c.AppendFileNameIfNotNull("Mer cury.cs");
// Managed compilers use this function to append sources files.
c.ShouldBe($"/something .{Path.DirectorySeparatorChar}-Mercury.cs Mercury.cs \"Mer cury.cs\"");
}
/// <summary>
/// Appends a single file name, ITaskItem version
/// </summary>
[Fact]
public void AppendSingleFileNameTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendFileNameIfNotNull(new TaskItem("-Mercury.cs"));
c.AppendFileNameIfNotNull(new TaskItem("Mercury.cs"));
c.AppendFileNameIfNotNull(new TaskItem("Mer cury.cs"));
// Managed compilers use this function to append sources files.
c.ShouldBe($"/something .{Path.DirectorySeparatorChar}-Mercury.cs Mercury.cs \"Mer cury.cs\"");
}
/// <summary>
/// Verify that we throw an exception correctly for the case where we don't have a switch name
/// </summary>
[Fact]
public void AppendSingleFileNameWithQuotes()
{
Should.Throw<ArgumentException>(() =>
{
// Cannot have escaped quotes in a file name
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNameIfNotNull("string with \"quotes\"");
c.ShouldBe("\"string with \\\"quotes\\\"\"");
}
);
}
/// <summary>
/// Trigger escaping of literal quotes.
/// </summary>
[Fact]
public void AppendSwitchWithLiteralQuotesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", "LSYSTEM_COMPATIBLE_ASSEMBLY_NAME=L\"Microsoft.Windows.SystemCompatible\"");
c.ShouldBe("/D\"LSYSTEM_COMPATIBLE_ASSEMBLY_NAME=L\\\"Microsoft.Windows.SystemCompatible\\\"\"");
}
/// <summary>
/// Trigger escaping of literal quotes.
/// </summary>
[Fact]
public void AppendSwitchWithLiteralQuotesInParameter2()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"ASSEMBLY_KEY_FILE=""c:\\foo\\FinalKeyFile.snk""");
c.ShouldBe(@"/D""ASSEMBLY_KEY_FILE=\""c:\\foo\\FinalKeyFile.snk\""""");
}
/// <summary>
/// Trigger escaping of literal quotes. This time, a double set of literal quotes.
/// </summary>
[Fact]
public void AppendSwitchWithLiteralQuotesInParameter3()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"""A B"" and ""C""");
c.ShouldBe(@"/D""\""A B\"" and \""C\""""");
}
/// <summary>
/// When a value contains a backslash, it doesn't normally need escaping.
/// </summary>
[Fact]
public void AppendQuotableSwitchContainingBackslash()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A \B");
c.ShouldBe(@"/D""A \B""");
}
/// <summary>
/// Backslashes before quotes need escaping themselves.
/// </summary>
[Fact]
public void AppendQuotableSwitchContainingBackslashBeforeLiteralQuote()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A"" \""B");
c.ShouldBe(@"/D""A\"" \\\""B""");
}
/// <summary>
/// Don't quote if not asked to
/// </summary>
[Fact]
public void AppendSwitchUnquotedIfNotNull()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchUnquotedIfNotNull("/D", @"A"" \""B");
c.ShouldBe(@"/DA"" \""B");
}
/// <summary>
/// When a value ends with a backslash, that certainly should be escaped if it's
/// going to be quoted.
/// </summary>
[Fact]
public void AppendQuotableSwitchEndingInBackslash()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A B\");
c.ShouldBe(@"/D""A B\\""");
}
/// <summary>
/// Backslashes don't need to be escaped if the string isn't going to get quoted.
/// </summary>
[Fact]
public void AppendNonQuotableSwitchEndingInBackslash()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"AB\");
c.ShouldBe(@"/DAB\");
}
/// <summary>
/// Quoting of hyphens
/// </summary>
[Fact]
public void AppendQuotableSwitchWithHyphen()
{
CommandLineBuilder c = new CommandLineBuilder(/* do not quote hyphens*/);
c.AppendSwitchIfNotNull("/D", @"foo-bar");
c.ShouldBe(@"/Dfoo-bar");
}
/// <summary>
/// Quoting of hyphens 2
/// </summary>
[Fact]
public void AppendQuotableSwitchWithHyphenQuoting()
{
CommandLineBuilder c = new CommandLineBuilder(true /* quote hyphens*/);
c.AppendSwitchIfNotNull("/D", @"foo-bar");
c.ShouldBe(@"/D""foo-bar""");
}
/// <summary>
/// Appends an ITaskItem item spec as a parameter
/// </summary>
[Fact]
public void AppendSwitchTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder(true);
c.AppendSwitchIfNotNull("/D", new TaskItem(@"foo-bar"));
c.ShouldBe(@"/D""foo-bar""");
}
/// <summary>
/// Appends an ITaskItem item spec as a parameter
/// </summary>
[Fact]
public void AppendSwitchUnQuotedTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder(true);
c.AppendSwitchUnquotedIfNotNull("/D", new TaskItem(@"foo-bar"));
c.ShouldBe(@"/Dfoo-bar");
}
/// <summary>
/// Ensure it's not an error to have an odd number of literal quotes. Sometimes
/// it's a mistake on the programmer's side, but we cannot reject odd numbers of
/// quotes in the general case because sometimes that's exactly what's needed (e.g.
/// passing a string with a single embedded double-quote to a compiler).
/// </summary>
[Fact]
public void AppendSwitchWithOddNumberOfLiteralQuotesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A='""'"); // /DA='"'
c.ShouldBe(@"/D""A='\""'"""); // /D"A='\"'"
}
[Fact]
public void UseNewLineSeparators()
{
CommandLineBuilder c = new CommandLineBuilder(quoteHyphensOnCommandLine: false, useNewLineSeparator: true);
c.AppendSwitchIfNotNull("/foo:", "bar");
c.AppendFileNameIfNotNull("18056896847C4FFC9706F1D585C077B4");
c.AppendSwitch("/D:");
c.AppendTextUnquoted("C7E1720B16E5477D8D15733006E68278");
string[] actual = c.ToString().Split(MSBuildConstants.EnvironmentNewLine, StringSplitOptions.None);
string[] expected =
{
"/foo:bar",
"18056896847C4FFC9706F1D585C077B4",
"/D:C7E1720B16E5477D8D15733006E68278"
};
actual.ShouldBe(expected);
}
internal class TestCommandLineBuilder : CommandLineBuilder
{
internal void TestVerifyThrow(string switchName, string parameter)
{
VerifyThrowNoEmbeddedDoubleQuotes(switchName, parameter);
}
protected override void VerifyThrowNoEmbeddedDoubleQuotes(string switchName, string parameter)
{
base.VerifyThrowNoEmbeddedDoubleQuotes(switchName, parameter);
}
}
/// <summary>
/// Test the else of VerifyThrowNOEmbeddedDouble quotes where the switch name is not empty or null
/// </summary>
[Fact]
public void TestVerifyThrowElse()
{
Should.Throw<ArgumentException>(() =>
{
TestCommandLineBuilder c = new TestCommandLineBuilder();
c.TestVerifyThrow("SuperSwitch", @"Parameter");
c.TestVerifyThrow("SuperSwitch", @"Para""meter");
}
);
}
}
internal static class CommandLineBuilderExtensionMethods
{
public static void ShouldBe(this CommandLineBuilder commandLineBuilder, string expected)
{
commandLineBuilder.ToString().ShouldBe(expected);
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using FarseerPhysics.Common.Decomposition;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// Represents a simple non-selfintersecting convex polygon.
/// If you want to have concave polygons, you will have to use the <see cref="BayazitDecomposer"/> or the <see cref="EarclipDecomposer"/>
/// to decompose the concave polygon into 2 or more convex polygons.
/// </summary>
public class PolygonShape : Shape
{
public Vertices Normals;
public Vertices Vertices;
/// <summary>
/// Initializes a new instance of the <see cref="PolygonShape"/> class.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="density">The density.</param>
public PolygonShape(Vertices vertices, float density)
: base(density)
{
ShapeType = ShapeType.Polygon;
Radius = Settings.PolygonRadius;
Set(vertices);
}
public PolygonShape(float density)
: base(density)
{
ShapeType = ShapeType.Polygon;
Radius = Settings.PolygonRadius;
}
internal PolygonShape()
: base(0)
{
ShapeType = ShapeType.Polygon;
Radius = Settings.PolygonRadius;
}
public override int ChildCount
{
get { return 1; }
}
public override Shape Clone()
{
PolygonShape clone = new PolygonShape();
clone.ShapeType = ShapeType;
clone.Radius = Radius;
if (Settings.ConserveMemory)
clone.Vertices = Vertices;
else
clone.Vertices = new Vertices(Vertices);
clone.Normals = Normals;
clone._density = _density;
clone.MassData = MassData;
return clone;
}
/// <summary>
/// Copy vertices. This assumes the vertices define a convex polygon.
/// It is assumed that the exterior is the the right of each edge.
/// </summary>
/// <param name="vertices">The vertices.</param>
public void Set(Vertices vertices)
{
Debug.Assert(vertices.Count >= 2 && vertices.Count <= Settings.MaxPolygonVertices);
if (Settings.ConserveMemory)
Vertices = vertices;
else
// Copy vertices.
Vertices = new Vertices(vertices);
Normals = new Vertices(vertices.Count);
// Compute normals. Ensure the edges have non-zero length.
for (int i = 0; i < vertices.Count; ++i)
{
int i1 = i;
int i2 = i + 1 < vertices.Count ? i + 1 : 0;
Vector2 edge = Vertices[i2] - Vertices[i1];
Debug.Assert(edge.LengthSquared() > Settings.Epsilon*Settings.Epsilon);
Vector2 temp = new Vector2(edge.Y, -edge.X);
temp.Normalize();
Normals.Add(temp);
}
#if DEBUG
// Ensure the polygon is convex and the interior
// is to the left of each edge.
for (int i = 0; i < Vertices.Count; ++i)
{
int i1 = i;
int i2 = i + 1 < Vertices.Count ? i + 1 : 0;
Vector2 edge = Vertices[i2] - Vertices[i1];
for (int j = 0; j < vertices.Count; ++j)
{
// Don't check vertices on the current edge.
if (j == i1 || j == i2)
{
continue;
}
Vector2 r = Vertices[j] - Vertices[i1];
// Your polygon is non-convex (it has an indentation) or
// has colinear edges.
float s = edge.X*r.Y - edge.Y*r.X;
Debug.Assert(s > 0.0f);
}
}
#endif
// Compute the polygon mass data
ComputeProperties();
}
/// <summary>
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin, not the centroid.
/// </summary>
public override void ComputeProperties()
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid.X = (1/mass) * rho * int(x * dA)
// centroid.Y = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
Debug.Assert(Vertices.Count >= 2);
// A line segment has zero mass.
if (Vertices.Count == 2)
{
MassData.Centroid = 0.5f*(Vertices[0] + Vertices[1]);
return;
}
if (_density > 0)
{
Vector2 center = Vector2.Zero;
float area = 0.0f;
float I = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
Vector2 pRef = Vector2.Zero;
#if false
// This code would put the reference point inside the polygon.
for (int i = 0; i < count; ++i)
{
pRef += vs[i];
}
pRef *= 1.0f / count;
#endif
const float inv3 = 1.0f/3.0f;
for (int i = 0; i < Vertices.Count; ++i)
{
// Triangle vertices.
Vector2 p1 = pRef;
Vector2 p2 = Vertices[i];
Vector2 p3 = i + 1 < Vertices.Count ? Vertices[i + 1] : Vertices[0];
Vector2 e1 = p2 - p1;
Vector2 e2 = p3 - p1;
float d;
MathUtils.Cross(ref e1, ref e2, out d);
float triangleArea = 0.5f*d;
area += triangleArea;
// Area weighted centroid
center += triangleArea*inv3*(p1 + p2 + p3);
float px = p1.X, py = p1.Y;
float ex1 = e1.X, ey1 = e1.Y;
float ex2 = e2.X, ey2 = e2.Y;
float intx2 = inv3*(0.25f*(ex1*ex1 + ex2*ex1 + ex2*ex2) + (px*ex1 + px*ex2)) +
0.5f*px*px;
float inty2 = inv3*(0.25f*(ey1*ey1 + ey2*ey1 + ey2*ey2) + (py*ey1 + py*ey2)) +
0.5f*py*py;
I += d*(intx2 + inty2);
}
Debug.Assert(area > Settings.Epsilon);
// We save the area
MassData.Area = area;
// Total mass
MassData.Mass = _density*area;
// Center of mass
Debug.Assert(area > Settings.Epsilon);
center *= 1.0f/area;
MassData.Centroid = center;
// Inertia tensor relative to the local origin.
MassData.Inertia = _density*I;
}
}
/// <summary>
/// Build vertices to represent an axis-aligned box.
/// </summary>
/// <param name="halfWidth">The half-width.</param>
/// <param name="halfHeight">The half-height.</param>
public void SetAsBox(float halfWidth, float halfHeight)
{
Set(PolygonTools.CreateRectangle(halfWidth, halfHeight));
}
/// <summary>
/// Build vertices to represent an oriented box.
/// </summary>
/// <param name="halfWidth">The half-width..</param>
/// <param name="halfHeight">The half-height.</param>
/// <param name="center">The center of the box in local coordinates.</param>
/// <param name="angle">The rotation of the box in local coordinates.</param>
public void SetAsBox(float halfWidth, float halfHeight, Vector2 center, float angle)
{
Set(PolygonTools.CreateRectangle(halfWidth, halfHeight, center, angle));
}
/// <summary>
/// Set this as a single edge.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
public void SetAsEdge(Vector2 start, Vector2 end)
{
Set(PolygonTools.CreateEdge(start, end));
}
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
Vector2 pLocal = MathUtils.MultiplyT(ref transform.R, point - transform.Position);
for (int i = 0; i < Vertices.Count; ++i)
{
float dot = Vector2.Dot(Normals[i], pLocal - Vertices[i]);
if (dot > 0.0f)
{
return false;
}
}
return true;
}
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform,
int childIndex)
{
output = new RayCastOutput();
// Put the ray into the polygon's frame of reference.
Vector2 p1 = MathUtils.MultiplyT(ref transform.R, input.Point1 - transform.Position);
Vector2 p2 = MathUtils.MultiplyT(ref transform.R, input.Point2 - transform.Position);
Vector2 d = p2 - p1;
if (Vertices.Count == 2)
{
Vector2 v1 = Vertices[0];
Vector2 v2 = Vertices[1];
Vector2 normal = Normals[0];
// q = p1 + t * d
// dot(normal, q - v1) = 0
// dot(normal, p1 - v1) + t * dot(normal, d) = 0
float numerator = Vector2.Dot(normal, v1 - p1);
float denominator = Vector2.Dot(normal, d);
if (denominator == 0.0f)
{
return false;
}
float t = numerator/denominator;
if (t < 0.0f || 1.0f < t)
{
return false;
}
Vector2 q = p1 + t*d;
// q = v1 + s * r
// s = dot(q - v1, r) / dot(r, r)
Vector2 r = v2 - v1;
float rr = Vector2.Dot(r, r);
if (rr == 0.0f)
{
return false;
}
float s = Vector2.Dot(q - v1, r)/rr;
if (s < 0.0f || 1.0f < s)
{
return false;
}
output.Fraction = t;
if (numerator > 0.0f)
{
output.Normal = -normal;
}
else
{
output.Normal = normal;
}
return true;
}
float lower = 0.0f, upper = input.MaxFraction;
int index = -1;
for (int i = 0; i < Vertices.Count; ++i)
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float numerator = Vector2.Dot(Normals[i], Vertices[i] - p1);
float denominator = Vector2.Dot(Normals[i], d);
if (denominator == 0.0f)
{
if (numerator < 0.0f)
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if (denominator < 0.0f && numerator < lower*denominator)
{
// Increase lower.
// The segment enters this half-space.
lower = numerator/denominator;
index = i;
}
else if (denominator > 0.0f && numerator < upper*denominator)
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator/denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
//if (upper < lower - b2_epsilon)
if (upper < lower)
{
return false;
}
}
Debug.Assert(0.0f <= lower && lower <= input.MaxFraction);
if (index >= 0)
{
output.Fraction = lower;
output.Normal = MathUtils.Multiply(ref transform.R, Normals[index]);
return true;
}
return false;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Vector2 lower = MathUtils.Multiply(ref transform, Vertices[0]);
Vector2 upper = lower;
for (int i = 1; i < Vertices.Count; ++i)
{
Vector2 v = MathUtils.Multiply(ref transform, Vertices[i]);
lower = Vector2.Min(lower, v);
upper = Vector2.Max(upper, v);
}
Vector2 r = new Vector2(Radius, Radius);
aabb.LowerBound = lower - r;
aabb.UpperBound = upper + r;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text.Utf8;
namespace System.Text.Json.Tests
{
public class TestDom
{
public Object Object { get; set; }
public Array Array { get; set; }
public Value Value { get; set; }
public TestDom this[string index]
{
get
{
if (Object == null) throw new NullReferenceException();
if (Object.Pairs == null) throw new NullReferenceException();
var json = new TestDom();
foreach (var pair in Object.Pairs)
{
if (pair.Name == index)
{
switch (pair.Value.Type)
{
case Value.ValueType.Object:
json.Object = pair.Value.ObjectValue;
break;
case Value.ValueType.Array:
json.Array = pair.Value.ArrayValue;
break;
case Value.ValueType.String:
case Value.ValueType.Number:
case Value.ValueType.False:
case Value.ValueType.True:
case Value.ValueType.Null:
json.Value = pair.Value;
break;
default:
break;
}
return json;
}
}
throw new KeyNotFoundException();
}
}
public TestDom this[int index]
{
get
{
if (Array == null) throw new NullReferenceException();
if (Array.Values == null) throw new NullReferenceException();
List<Value> values = Array.Values;
if (index < 0 || index >= values.Count) throw new IndexOutOfRangeException();
Value value = values[index];
var json = new TestDom();
switch (value.Type)
{
case Value.ValueType.Object:
json.Object = value.ObjectValue;
break;
case Value.ValueType.Array:
json.Array = value.ArrayValue;
break;
case Value.ValueType.String:
case Value.ValueType.Number:
case Value.ValueType.False:
case Value.ValueType.True:
case Value.ValueType.Null:
json.Value = value;
break;
default:
break;
}
return json;
}
}
public static explicit operator string (TestDom json)
{
if (json == null || json.Value == null) throw new NullReferenceException();
if (json.Value.Type == Value.ValueType.String)
{
return json.Value.StringValue;
}
else if (json.Value.Type == Value.ValueType.Null)
{
return json.Value.NullValue.ToString();
}
else
{
throw new InvalidCastException();
}
}
public static explicit operator double (TestDom json)
{
if (json == null || json.Value == null) throw new NullReferenceException();
if (json.Value.Type == Value.ValueType.Number)
{
return json.Value.NumberValue;
}
else
{
throw new InvalidCastException();
}
}
public static explicit operator bool (TestDom json)
{
if (json == null || json.Value == null) throw new NullReferenceException();
if (json.Value.Type == Value.ValueType.True)
{
return json.Value.TrueValue;
}
else if (json.Value.Type == Value.ValueType.False)
{
return json.Value.FalseValue;
}
else
{
throw new InvalidCastException();
}
}
public List<Value> GetValueFromPropertyName(string str)
{
return GetValueFromPropertyName(new Utf8String(str), Object);
}
public List<Value> GetValueFromPropertyName(Utf8String str)
{
return GetValueFromPropertyName(str, Object);
}
public List<Value> GetValueFromPropertyName(string str, Object obj)
{
return GetValueFromPropertyName(new Utf8String(str), obj);
}
public List<Value> GetValueFromPropertyName(Utf8String str, Object obj)
{
var values = new List<Value>();
if (obj == null || obj.Pairs == null) return values;
foreach (var pair in obj.Pairs)
{
if (pair == null || pair.Value == null) return values;
if (pair.Value.Type == Value.ValueType.Object)
{
values.AddRange(GetValueFromPropertyName(str, pair.Value.ObjectValue));
}
if (pair.Value.Type == Value.ValueType.Array)
{
if (pair.Value.ArrayValue == null || pair.Value.ArrayValue.Values == null) return values;
foreach (var value in pair.Value.ArrayValue.Values)
{
if (value != null && value.Type == Value.ValueType.Object)
{
values.AddRange(GetValueFromPropertyName(str, value.ObjectValue));
}
}
}
if (new Utf8String(pair.Name) == str)
{
values.Add(pair.Value);
}
}
return values;
}
public override string ToString()
{
if (Object != null)
{
return OutputObject(Object);
}
if (Array != null)
{
return OutputArray(Array);
}
return "";
}
private string OutputObject(Object obj)
{
var strBuilder = new StringBuilder();
if (obj == null || obj.Pairs == null) return "";
strBuilder.Append("{");
for (var i = 0; i < obj.Pairs.Count; i++)
{
strBuilder.Append(OutputPair(obj.Pairs[i]));
if (i < obj.Pairs.Count - 1)
{
strBuilder.Append(",");
}
}
strBuilder.Append("}");
return strBuilder.ToString();
}
private string OutputPair(Pair pair)
{
var str = "";
if (pair == null) return str;
str += "\"" + pair.Name + "\":";
str += OutputValue(pair.Value);
return str;
}
private string OutputArray(Array array)
{
var strBuilder = new StringBuilder();
if (array == null || array.Values == null) return "";
strBuilder.Append("[");
for (var i = 0; i < array.Values.Count; i++)
{
strBuilder.Append(OutputValue(array.Values[i]));
if (i < array.Values.Count - 1)
{
strBuilder.Append(",");
}
}
strBuilder.Append("]");
return strBuilder.ToString();
}
private string OutputValue(Value value)
{
var str = "";
if (value == null) return str;
var type = value.Type;
switch (type)
{
case Value.ValueType.String:
str += "\"" + value.StringValue + "\"";
break;
case Value.ValueType.Number:
str += value.NumberValue;
break;
case Value.ValueType.Object:
str += OutputObject(value.ObjectValue);
break;
case Value.ValueType.Array:
str += OutputArray(value.ArrayValue);
break;
case Value.ValueType.True:
str += value.TrueValue.ToString().ToLower();
break;
case Value.ValueType.False:
str += value.FalseValue.ToString().ToLower();
break;
case Value.ValueType.Null:
str += value.NullValue.ToString().ToLower();
break;
default:
throw new ArgumentOutOfRangeException();
}
return str;
}
}
public class Object
{
public List<Pair> Pairs { get; set; }
}
public class Pair
{
public string Name { get; set; }
public Value Value { get; set; }
}
public class Array
{
public List<Value> Values { get; set; }
}
public class Value
{
public ValueType Type { get; set; }
public enum ValueType
{
String,
Number,
Object,
Array,
True,
False,
Null
}
public object Raw()
{
switch (Type)
{
case ValueType.String:
return _string;
case ValueType.Number:
return _number;
case ValueType.Object:
return _object;
case ValueType.Array:
return _array;
case ValueType.True:
return True;
case ValueType.False:
return False;
case ValueType.Null:
return null;
default:
throw new ArgumentOutOfRangeException();
}
}
public string StringValue
{
get
{
if (Type == ValueType.String)
{
return _string;
}
throw new TypeAccessException("Value is not of type 'string'.");
}
set
{
if (Type == ValueType.String)
{
_string = value;
}
}
}
public double NumberValue
{
get
{
if (Type == ValueType.Number)
{
return _number;
}
throw new TypeAccessException("Value is not of type 'number'.");
}
set
{
if (Type == ValueType.Number)
{
_number = value;
}
}
}
public Object ObjectValue
{
get
{
if (Type == ValueType.Object)
{
return _object;
}
throw new TypeAccessException("Value is not of type 'object'.");
}
set
{
if (Type == ValueType.Object)
{
_object = value;
}
}
}
public Array ArrayValue
{
get
{
if (Type == ValueType.Array)
{
return _array;
}
throw new TypeAccessException("Value is not of type 'array'.");
}
set
{
if (Type == ValueType.Array)
{
_array = value;
}
}
}
public bool TrueValue
{
get
{
if (Type == ValueType.True)
{
return True;
}
throw new TypeAccessException("Value is not of type 'true'.");
}
}
public bool FalseValue
{
get
{
if (Type == ValueType.False)
{
return False;
}
throw new TypeAccessException("Value is not of type 'false'.");
}
}
public object NullValue
{
get
{
if (Type == ValueType.Null)
{
return Null;
}
throw new TypeAccessException("Value is not of type 'null'.");
}
}
private string _string;
private double _number;
private Object _object;
private Array _array;
private const bool True = true;
private const bool False = false;
private const string Null = "null";
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Godot;
using JetBrains.Annotations;
using Microsoft.Win32;
using Newtonsoft.Json;
using Directory = System.IO.Directory;
using Environment = System.Environment;
using File = System.IO.File;
using Path = System.IO.Path;
using OS = GodotTools.Utils.OS;
// ReSharper disable UnassignedField.Local
// ReSharper disable InconsistentNaming
// ReSharper disable UnassignedField.Global
// ReSharper disable MemberHidesStaticFromOuterClass
namespace GodotTools.Ides.Rider
{
/// <summary>
/// This code is a modified version of the JetBrains resharper-unity plugin listed under Apache License 2.0 license:
/// https://github.com/JetBrains/resharper-unity/blob/master/unity/JetBrains.Rider.Unity.Editor/EditorPlugin/RiderPathLocator.cs
/// </summary>
public static class RiderPathLocator
{
public static RiderInfo[] GetAllRiderPaths()
{
try
{
if (OS.IsWindows)
{
return CollectRiderInfosWindows();
}
if (OS.IsOSX)
{
return CollectRiderInfosMac();
}
if (OS.IsUnixLike)
{
return CollectAllRiderPathsLinux();
}
throw new Exception("Unexpected OS.");
}
catch (Exception e)
{
GD.PushWarning(e.Message);
}
return new RiderInfo[0];
}
private static RiderInfo[] CollectAllRiderPathsLinux()
{
var installInfos = new List<RiderInfo>();
var home = Environment.GetEnvironmentVariable("HOME");
if (!string.IsNullOrEmpty(home))
{
var toolboxRiderRootPath = GetToolboxBaseDir();
installInfos.AddRange(CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider.sh", false)
.Select(a => new RiderInfo(a, true)).ToList());
//$Home/.local/share/applications/jetbrains-rider.desktop
var shortcut = new FileInfo(Path.Combine(home, @".local/share/applications/jetbrains-rider.desktop"));
if (shortcut.Exists)
{
var lines = File.ReadAllLines(shortcut.FullName);
foreach (var line in lines)
{
if (!line.StartsWith("Exec=\""))
continue;
var path = line.Split('"').Where((item, index) => index == 1).SingleOrDefault();
if (string.IsNullOrEmpty(path))
continue;
if (installInfos.Any(a => a.Path == path)) // avoid adding similar build as from toolbox
continue;
installInfos.Add(new RiderInfo(path, false));
}
}
}
// snap install
var snapInstallPath = "/snap/rider/current/bin/rider.sh";
if (new FileInfo(snapInstallPath).Exists)
installInfos.Add(new RiderInfo(snapInstallPath, false));
return installInfos.ToArray();
}
private static RiderInfo[] CollectRiderInfosMac()
{
var installInfos = new List<RiderInfo>();
// "/Applications/*Rider*.app"
// should be combined with "Contents/MacOS/rider"
var folder = new DirectoryInfo("/Applications");
if (folder.Exists)
{
installInfos.AddRange(folder.GetDirectories("*Rider*.app")
.Select(a => new RiderInfo(Path.Combine(a.FullName, "Contents/MacOS/rider"), false))
.ToList());
}
// /Users/user/Library/Application Support/JetBrains/Toolbox/apps/Rider/ch-1/181.3870.267/Rider EAP.app
// should be combined with "Contents/MacOS/rider"
var toolboxRiderRootPath = GetToolboxBaseDir();
var paths = CollectPathsFromToolbox(toolboxRiderRootPath, "", "Rider*.app", true)
.Select(a => new RiderInfo(Path.Combine(a, "Contents/MacOS/rider"), true));
installInfos.AddRange(paths);
return installInfos.ToArray();
}
private static RiderInfo[] CollectRiderInfosWindows()
{
var installInfos = new List<RiderInfo>();
var toolboxRiderRootPath = GetToolboxBaseDir();
var installPathsToolbox = CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider64.exe", false).ToList();
installInfos.AddRange(installPathsToolbox.Select(a => new RiderInfo(a, true)).ToList());
var installPaths = new List<string>();
const string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
CollectPathsFromRegistry(registryKey, installPaths);
const string wowRegistryKey = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
CollectPathsFromRegistry(wowRegistryKey, installPaths);
installInfos.AddRange(installPaths.Select(a => new RiderInfo(a, false)).ToList());
return installInfos.ToArray();
}
private static string GetToolboxBaseDir()
{
if (OS.IsWindows)
{
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return GetToolboxRiderRootPath(localAppData);
}
if (OS.IsOSX)
{
var home = Environment.GetEnvironmentVariable("HOME");
if (string.IsNullOrEmpty(home))
return string.Empty;
var localAppData = Path.Combine(home, @"Library/Application Support");
return GetToolboxRiderRootPath(localAppData);
}
if (OS.IsUnixLike)
{
var home = Environment.GetEnvironmentVariable("HOME");
if (string.IsNullOrEmpty(home))
return string.Empty;
var localAppData = Path.Combine(home, @".local/share");
return GetToolboxRiderRootPath(localAppData);
}
return string.Empty;
}
private static string GetToolboxRiderRootPath(string localAppData)
{
var toolboxPath = Path.Combine(localAppData, @"JetBrains/Toolbox");
var settingsJson = Path.Combine(toolboxPath, ".settings.json");
if (File.Exists(settingsJson))
{
var path = SettingsJson.GetInstallLocationFromJson(File.ReadAllText(settingsJson));
if (!string.IsNullOrEmpty(path))
toolboxPath = path;
}
var toolboxRiderRootPath = Path.Combine(toolboxPath, @"apps/Rider");
return toolboxRiderRootPath;
}
internal static ProductInfo GetBuildVersion(string path)
{
var buildTxtFileInfo = new FileInfo(Path.Combine(path, GetRelativePathToBuildTxt()));
var dir = buildTxtFileInfo.DirectoryName;
if (!Directory.Exists(dir))
return null;
var buildVersionFile = new FileInfo(Path.Combine(dir, "product-info.json"));
if (!buildVersionFile.Exists)
return null;
var json = File.ReadAllText(buildVersionFile.FullName);
return ProductInfo.GetProductInfo(json);
}
internal static Version GetBuildNumber(string path)
{
var file = new FileInfo(Path.Combine(path, GetRelativePathToBuildTxt()));
if (!file.Exists)
return null;
var text = File.ReadAllText(file.FullName);
if (text.Length <= 3)
return null;
var versionText = text.Substring(3);
return Version.TryParse(versionText, out var v) ? v : null;
}
internal static bool IsToolbox(string path)
{
return path.StartsWith(GetToolboxBaseDir());
}
private static string GetRelativePathToBuildTxt()
{
if (OS.IsWindows || OS.IsUnixLike)
return "../../build.txt";
if (OS.IsOSX)
return "Contents/Resources/build.txt";
throw new Exception("Unknown OS.");
}
private static void CollectPathsFromRegistry(string registryKey, List<string> installPaths)
{
using (var key = Registry.CurrentUser.OpenSubKey(registryKey))
{
CollectPathsFromRegistry(installPaths, key);
}
using (var key = Registry.LocalMachine.OpenSubKey(registryKey))
{
CollectPathsFromRegistry(installPaths, key);
}
}
private static void CollectPathsFromRegistry(List<string> installPaths, RegistryKey key)
{
if (key == null) return;
foreach (var subkeyName in key.GetSubKeyNames().Where(a => a.Contains("Rider")))
{
using (var subkey = key.OpenSubKey(subkeyName))
{
var folderObject = subkey?.GetValue("InstallLocation");
if (folderObject == null) continue;
var folder = folderObject.ToString();
var possiblePath = Path.Combine(folder, @"bin\rider64.exe");
if (File.Exists(possiblePath))
installPaths.Add(possiblePath);
}
}
}
private static string[] CollectPathsFromToolbox(string toolboxRiderRootPath, string dirName, string searchPattern,
bool isMac)
{
if (!Directory.Exists(toolboxRiderRootPath))
return new string[0];
var channelDirs = Directory.GetDirectories(toolboxRiderRootPath);
var paths = channelDirs.SelectMany(channelDir =>
{
try
{
// use history.json - last entry stands for the active build https://jetbrains.slack.com/archives/C07KNP99D/p1547807024066500?thread_ts=1547731708.057700&cid=C07KNP99D
var historyFile = Path.Combine(channelDir, ".history.json");
if (File.Exists(historyFile))
{
var json = File.ReadAllText(historyFile);
var build = ToolboxHistory.GetLatestBuildFromJson(json);
if (build != null)
{
var buildDir = Path.Combine(channelDir, build);
var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir);
if (executablePaths.Any())
return executablePaths;
}
}
var channelFile = Path.Combine(channelDir, ".channel.settings.json");
if (File.Exists(channelFile))
{
var json = File.ReadAllText(channelFile).Replace("active-application", "active_application");
var build = ToolboxInstallData.GetLatestBuildFromJson(json);
if (build != null)
{
var buildDir = Path.Combine(channelDir, build);
var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir);
if (executablePaths.Any())
return executablePaths;
}
}
// changes in toolbox json files format may brake the logic above, so return all found Rider installations
return Directory.GetDirectories(channelDir)
.SelectMany(buildDir => GetExecutablePaths(dirName, searchPattern, isMac, buildDir));
}
catch (Exception e)
{
// do not write to Debug.Log, just log it.
Logger.Warn($"Failed to get RiderPath from {channelDir}", e);
}
return new string[0];
})
.Where(c => !string.IsNullOrEmpty(c))
.ToArray();
return paths;
}
private static string[] GetExecutablePaths(string dirName, string searchPattern, bool isMac, string buildDir)
{
var folder = new DirectoryInfo(Path.Combine(buildDir, dirName));
if (!folder.Exists)
return new string[0];
if (!isMac)
return new[] { Path.Combine(folder.FullName, searchPattern) }.Where(File.Exists).ToArray();
return folder.GetDirectories(searchPattern).Select(f => f.FullName)
.Where(Directory.Exists).ToArray();
}
// Disable the "field is never assigned" compiler warning. We never assign it, but Unity does.
// Note that Unity disable this warning in the generated C# projects
#pragma warning disable 0649
[Serializable]
class SettingsJson
{
public string install_location;
[CanBeNull]
public static string GetInstallLocationFromJson(string json)
{
try
{
return JsonConvert.DeserializeObject<SettingsJson>(json).install_location;
}
catch (Exception)
{
Logger.Warn($"Failed to get install_location from json {json}");
}
return null;
}
}
[Serializable]
class ToolboxHistory
{
public List<ItemNode> history;
public static string GetLatestBuildFromJson(string json)
{
try
{
return JsonConvert.DeserializeObject<ToolboxHistory>(json).history.LastOrDefault()?.item.build;
}
catch (Exception)
{
Logger.Warn($"Failed to get latest build from json {json}");
}
return null;
}
}
[Serializable]
class ItemNode
{
public BuildNode item;
}
[Serializable]
class BuildNode
{
public string build;
}
[Serializable]
public class ProductInfo
{
public string version;
public string versionSuffix;
[CanBeNull]
internal static ProductInfo GetProductInfo(string json)
{
try
{
var productInfo = JsonConvert.DeserializeObject<ProductInfo>(json);
return productInfo;
}
catch (Exception)
{
Logger.Warn($"Failed to get version from json {json}");
}
return null;
}
}
// ReSharper disable once ClassNeverInstantiated.Global
[Serializable]
class ToolboxInstallData
{
// ReSharper disable once InconsistentNaming
public ActiveApplication active_application;
[CanBeNull]
public static string GetLatestBuildFromJson(string json)
{
try
{
var toolbox = JsonConvert.DeserializeObject<ToolboxInstallData>(json);
var builds = toolbox.active_application.builds;
if (builds != null && builds.Any())
return builds.First();
}
catch (Exception)
{
Logger.Warn($"Failed to get latest build from json {json}");
}
return null;
}
}
[Serializable]
class ActiveApplication
{
public List<string> builds;
}
#pragma warning restore 0649
public struct RiderInfo
{
// ReSharper disable once NotAccessedField.Global
public bool IsToolbox;
public string Presentation;
public Version BuildNumber;
public ProductInfo ProductInfo;
public string Path;
public RiderInfo(string path, bool isToolbox)
{
BuildNumber = GetBuildNumber(path);
ProductInfo = GetBuildVersion(path);
Path = new FileInfo(path).FullName; // normalize separators
var presentation = $"Rider {BuildNumber}";
if (ProductInfo != null && !string.IsNullOrEmpty(ProductInfo.version))
{
var suffix = string.IsNullOrEmpty(ProductInfo.versionSuffix) ? "" : $" {ProductInfo.versionSuffix}";
presentation = $"Rider {ProductInfo.version}{suffix}";
}
if (isToolbox)
presentation += " (JetBrains Toolbox)";
Presentation = presentation;
IsToolbox = isToolbox;
}
}
private static class Logger
{
internal static void Warn(string message, Exception e = null)
{
throw new Exception(message, e);
}
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif
using UMA;
namespace UMA.Examples
{
public class UMARecipeCrowd : MonoBehaviour
{
public UMAContextBase context;
public UMAGeneratorBase generator;
public RuntimeAnimatorController animationController;
public float atlasScale = 0.5f;
public bool hideWhileGenerating;
public bool stressTest;
public Vector2 crowdSize;
public float space = 1f;
private int spawnX;
private int spawnY;
private bool generating = false;
public bool saveCrowd = false;
private string saveFolderPath;
public SharedColorTable[] sharedColors;
public UMARecipeMixer[] recipeMixers;
public UMADataEvent CharacterCreated;
public UMADataEvent CharacterDestroyed;
public UMADataEvent CharacterUpdated;
void Awake()
{
if (space <= 0)
space = 1f;
if (atlasScale > 1f)
atlasScale = 1f;
if (atlasScale < 0.0625f)
atlasScale = 0.0625f;
if ((crowdSize.x > 0) && (crowdSize.y > 0))
generating = true;
#if UNITY_EDITOR
if (saveCrowd)
{
saveFolderPath = "Saved Crowd " + System.DateTime.Now.ToString().Replace('/', '_');
saveFolderPath = saveFolderPath.Replace(':', '_');
string folderGUID = AssetDatabase.CreateFolder("Assets", saveFolderPath);
saveFolderPath = AssetDatabase.GUIDToAssetPath(folderGUID);
Debug.LogWarning("Saving all generated recipes into: " + saveFolderPath);
}
#endif
}
void Update()
{
if (generator.IsIdle())
{
if (generating)
{
GenerateOneCharacter();
}
else if (stressTest)
{
RandomizeAll();
}
}
}
void CharacterCreatedCallback(UMAData umaData)
{
if (hideWhileGenerating)
{
if (umaData.animator != null)
umaData.animator.enabled = false;
Renderer[] renderers = umaData.GetRenderers();
for (int i = 0; i < renderers.Length; i++)
{
renderers[i].enabled = false;
}
}
}
public GameObject GenerateOneCharacter()
{
if ((recipeMixers == null) || (recipeMixers.Length == 0))
return null;
Vector3 umaPos = new Vector3((spawnX - crowdSize.x / 2f) * space, 0f, (spawnY - crowdSize.y / 2f) * space);
if (spawnY < crowdSize.y)
{
spawnX++;
if (spawnX >= crowdSize.x)
{
spawnX = 0;
spawnY++;
}
}
else
{
if (hideWhileGenerating)
{
UMAData[] generatedCrowd = GetComponentsInChildren<UMAData>();
foreach (UMAData generatedData in generatedCrowd)
{
if (generatedData.animator != null)
generatedData.animator.enabled = true;
Renderer[] renderers = generatedData.GetRenderers();
for (int i = 0; i < renderers.Length; i++)
{
renderers[i].enabled = true;
}
}
}
spawnX = 0;
spawnY = 0;
generating = false;
return null;
}
GameObject newGO = new GameObject("Generated Character");
newGO.transform.parent = transform;
newGO.transform.localPosition = umaPos;
newGO.transform.localRotation = Quaternion.identity;
UMADynamicAvatar umaAvatar = newGO.AddComponent<UMADynamicAvatar>();
umaAvatar.context = context;
umaAvatar.umaGenerator = generator;
umaAvatar.Initialize();
UMAData umaData = umaAvatar.umaData;
umaData.atlasResolutionScale = atlasScale;
umaData.CharacterCreated = new UMADataEvent(CharacterCreated);
umaData.OnCharacterCreated += CharacterCreatedCallback;
umaData.CharacterDestroyed = new UMADataEvent(CharacterDestroyed);
umaData.CharacterUpdated = new UMADataEvent(CharacterUpdated);
RandomizeRecipe(umaData);
RandomizeDNA(umaData);
if (animationController != null)
{
umaAvatar.animationController = animationController;
}
umaAvatar.Show();
return newGO;
}
public void ReplaceAll()
{
if (generating)
{
Debug.LogWarning("Can't replace while generating.");
return;
}
int childCount = gameObject.transform.childCount;
while(--childCount >= 0)
{
Transform child = gameObject.transform.GetChild(childCount);
UMAUtils.DestroySceneObject(child.gameObject);
}
generating = true;
}
public virtual void RandomizeRecipe(UMAData umaData)
{
UMARecipeMixer mixer = recipeMixers[Random.Range(0, recipeMixers.Length)];
mixer.FillUMARecipe(umaData.umaRecipe, context);
OverlayColorData[] recipeColors = umaData.umaRecipe.sharedColors;
if ((recipeColors != null) && (recipeColors.Length > 0))
{
foreach (var sharedColor in sharedColors)
{
if (sharedColor == null) continue;
int index = Random.Range(0, sharedColor.colors.Length);
for (int i = 0; i < recipeColors.Length; i++)
{
if (recipeColors[i].name == sharedColor.sharedColorName)
{
recipeColors[i].color = sharedColor.colors[index].color;
}
}
}
}
// This is a HACK - maybe there should be a clean way
// of removing a conflicting slot via the recipe?
int maleJeansIndex = -1;
int maleLegsIndex = -1;
SlotData[] slots = umaData.umaRecipe.GetAllSlots();
for (int i = 0; i < slots.Length; i++)
{
SlotData slot = slots[i];
if (slot == null) continue;
if (slot.asset.name == null) continue;
if (slot.asset.slotName == "MaleJeans01") maleJeansIndex = i;
else if (slot.asset.slotName == "MaleLegs") maleLegsIndex = i;
}
if ((maleJeansIndex >= 0) && (maleLegsIndex >= 0))
{
umaData.umaRecipe.SetSlot(maleLegsIndex, null);
}
#if UNITY_EDITOR
if (saveCrowd)
{
SaveRecipe(umaData, context);
}
#endif
}
#if UNITY_EDITOR
protected void SaveRecipe(UMAData umaData, UMAContextBase context)
{
string assetPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(saveFolderPath, umaData.umaRecipe.raceData.raceName + ".asset"));
var asset = ScriptableObject.CreateInstance<UMATextRecipe>();
asset.Save(umaData.umaRecipe, context);
AssetDatabase.CreateAsset(asset, assetPath);
AssetDatabase.SaveAssets();
}
#endif
public virtual void RandomizeDNA(UMAData umaData)
{
RaceData race = umaData.umaRecipe.GetRace();
if ((race != null) && (race.dnaRanges != null))
{
foreach (DNARangeAsset dnaRange in race.dnaRanges)
{
dnaRange.RandomizeDNA(umaData);
}
}
}
public virtual void RandomizeDNAGaussian(UMAData umaData)
{
RaceData race = umaData.umaRecipe.GetRace();
if ((race != null) && (race.dnaRanges != null))
{
foreach (DNARangeAsset dnaRange in race.dnaRanges)
{
dnaRange.RandomizeDNAGaussian(umaData);
}
}
}
public void RandomizeAll()
{
if (generating)
{
Debug.LogWarning("Can't randomize while generating.");
return;
}
int childCount = gameObject.transform.childCount;
for (int i = 0; i < childCount; i++)
{
Transform child = gameObject.transform.GetChild(i);
UMADynamicAvatar umaAvatar = child.gameObject.GetComponent<UMADynamicAvatar>();
if (umaAvatar == null) continue;
UMAData umaData = umaAvatar.umaData;
umaData.umaRecipe = new UMAData.UMARecipe();
RandomizeRecipe(umaData);
RandomizeDNA(umaData);
if (animationController != null)
{
umaAvatar.animationController = animationController;
}
umaAvatar.Show();
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the LabMotivoRechazoScreening class.
/// </summary>
[Serializable]
public partial class LabMotivoRechazoScreeningCollection : ActiveList<LabMotivoRechazoScreening, LabMotivoRechazoScreeningCollection>
{
public LabMotivoRechazoScreeningCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>LabMotivoRechazoScreeningCollection</returns>
public LabMotivoRechazoScreeningCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
LabMotivoRechazoScreening o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the LAB_MotivoRechazoScreening table.
/// </summary>
[Serializable]
public partial class LabMotivoRechazoScreening : ActiveRecord<LabMotivoRechazoScreening>, IActiveRecord
{
#region .ctors and Default Settings
public LabMotivoRechazoScreening()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public LabMotivoRechazoScreening(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public LabMotivoRechazoScreening(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public LabMotivoRechazoScreening(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("LAB_MotivoRechazoScreening", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdMotivoRechazoScreening = new TableSchema.TableColumn(schema);
colvarIdMotivoRechazoScreening.ColumnName = "idMotivoRechazoScreening";
colvarIdMotivoRechazoScreening.DataType = DbType.Int32;
colvarIdMotivoRechazoScreening.MaxLength = 0;
colvarIdMotivoRechazoScreening.AutoIncrement = true;
colvarIdMotivoRechazoScreening.IsNullable = false;
colvarIdMotivoRechazoScreening.IsPrimaryKey = true;
colvarIdMotivoRechazoScreening.IsForeignKey = false;
colvarIdMotivoRechazoScreening.IsReadOnly = false;
colvarIdMotivoRechazoScreening.DefaultSetting = @"";
colvarIdMotivoRechazoScreening.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMotivoRechazoScreening);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.String;
colvarDescripcion.MaxLength = 500;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = false;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("LAB_MotivoRechazoScreening",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdMotivoRechazoScreening")]
[Bindable(true)]
public int IdMotivoRechazoScreening
{
get { return GetColumnValue<int>(Columns.IdMotivoRechazoScreening); }
set { SetColumnValue(Columns.IdMotivoRechazoScreening, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varDescripcion)
{
LabMotivoRechazoScreening item = new LabMotivoRechazoScreening();
item.Descripcion = varDescripcion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdMotivoRechazoScreening,string varDescripcion)
{
LabMotivoRechazoScreening item = new LabMotivoRechazoScreening();
item.IdMotivoRechazoScreening = varIdMotivoRechazoScreening;
item.Descripcion = varDescripcion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdMotivoRechazoScreeningColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdMotivoRechazoScreening = @"idMotivoRechazoScreening";
public static string Descripcion = @"descripcion";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
namespace android.location
{
[global::MonoJavaBridge.JavaClass()]
public partial class LocationManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static LocationManager()
{
InitJNI();
}
protected LocationManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getProvider4772;
public virtual global::android.location.LocationProvider getProvider(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.LocationManager._getProvider4772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.location.LocationProvider;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._getProvider4772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.location.LocationProvider;
}
internal static global::MonoJavaBridge.MethodId _getProviders4773;
public virtual global::java.util.List getProviders(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.location.LocationManager._getProviders4773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._getProviders4773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List;
}
internal static global::MonoJavaBridge.MethodId _getProviders4774;
public virtual global::java.util.List getProviders(android.location.Criteria arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.location.LocationManager._getProviders4774, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.util.List;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._getProviders4774, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.util.List;
}
internal static global::MonoJavaBridge.MethodId _getAllProviders4775;
public virtual global::java.util.List getAllProviders()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.location.LocationManager._getAllProviders4775)) as java.util.List;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._getAllProviders4775)) as java.util.List;
}
internal static global::MonoJavaBridge.MethodId _getBestProvider4776;
public virtual global::java.lang.String getBestProvider(android.location.Criteria arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.LocationManager._getBestProvider4776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._getBestProvider4776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _requestLocationUpdates4777;
public virtual void requestLocationUpdates(java.lang.String arg0, long arg1, float arg2, android.location.LocationListener arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._requestLocationUpdates4777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._requestLocationUpdates4777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _requestLocationUpdates4778;
public virtual void requestLocationUpdates(java.lang.String arg0, long arg1, float arg2, android.location.LocationListener arg3, android.os.Looper arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._requestLocationUpdates4778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._requestLocationUpdates4778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _requestLocationUpdates4779;
public virtual void requestLocationUpdates(java.lang.String arg0, long arg1, float arg2, android.app.PendingIntent arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._requestLocationUpdates4779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._requestLocationUpdates4779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _removeUpdates4780;
public virtual void removeUpdates(android.location.LocationListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._removeUpdates4780, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._removeUpdates4780, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeUpdates4781;
public virtual void removeUpdates(android.app.PendingIntent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._removeUpdates4781, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._removeUpdates4781, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addProximityAlert4782;
public virtual void addProximityAlert(double arg0, double arg1, float arg2, long arg3, android.app.PendingIntent arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._addProximityAlert4782, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._addProximityAlert4782, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _removeProximityAlert4783;
public virtual void removeProximityAlert(android.app.PendingIntent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._removeProximityAlert4783, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._removeProximityAlert4783, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isProviderEnabled4784;
public virtual bool isProviderEnabled(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.location.LocationManager._isProviderEnabled4784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._isProviderEnabled4784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getLastKnownLocation4785;
public virtual global::android.location.Location getLastKnownLocation(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.LocationManager._getLastKnownLocation4785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.location.Location;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._getLastKnownLocation4785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.location.Location;
}
internal static global::MonoJavaBridge.MethodId _addTestProvider4786;
public virtual void addTestProvider(java.lang.String arg0, bool arg1, bool arg2, bool arg3, bool arg4, bool arg5, bool arg6, bool arg7, int arg8, int arg9)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._addTestProvider4786, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._addTestProvider4786, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9));
}
internal static global::MonoJavaBridge.MethodId _removeTestProvider4787;
public virtual void removeTestProvider(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._removeTestProvider4787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._removeTestProvider4787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setTestProviderLocation4788;
public virtual void setTestProviderLocation(java.lang.String arg0, android.location.Location arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._setTestProviderLocation4788, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._setTestProviderLocation4788, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _clearTestProviderLocation4789;
public virtual void clearTestProviderLocation(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._clearTestProviderLocation4789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._clearTestProviderLocation4789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setTestProviderEnabled4790;
public virtual void setTestProviderEnabled(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._setTestProviderEnabled4790, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._setTestProviderEnabled4790, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _clearTestProviderEnabled4791;
public virtual void clearTestProviderEnabled(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._clearTestProviderEnabled4791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._clearTestProviderEnabled4791, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setTestProviderStatus4792;
public virtual void setTestProviderStatus(java.lang.String arg0, int arg1, android.os.Bundle arg2, long arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._setTestProviderStatus4792, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._setTestProviderStatus4792, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _clearTestProviderStatus4793;
public virtual void clearTestProviderStatus(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._clearTestProviderStatus4793, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._clearTestProviderStatus4793, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addGpsStatusListener4794;
public virtual bool addGpsStatusListener(android.location.GpsStatus.Listener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.location.LocationManager._addGpsStatusListener4794, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._addGpsStatusListener4794, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeGpsStatusListener4795;
public virtual void removeGpsStatusListener(android.location.GpsStatus.Listener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._removeGpsStatusListener4795, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._removeGpsStatusListener4795, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addNmeaListener4796;
public virtual bool addNmeaListener(android.location.GpsStatus.NmeaListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.location.LocationManager._addNmeaListener4796, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._addNmeaListener4796, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeNmeaListener4797;
public virtual void removeNmeaListener(android.location.GpsStatus.NmeaListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.location.LocationManager._removeNmeaListener4797, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._removeNmeaListener4797, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getGpsStatus4798;
public virtual global::android.location.GpsStatus getGpsStatus(android.location.GpsStatus arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.location.LocationManager._getGpsStatus4798, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.location.GpsStatus;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._getGpsStatus4798, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.location.GpsStatus;
}
internal static global::MonoJavaBridge.MethodId _sendExtraCommand4799;
public virtual bool sendExtraCommand(java.lang.String arg0, java.lang.String arg1, android.os.Bundle arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.location.LocationManager._sendExtraCommand4799, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.location.LocationManager.staticClass, global::android.location.LocationManager._sendExtraCommand4799, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public static global::java.lang.String NETWORK_PROVIDER
{
get
{
return "network";
}
}
public static global::java.lang.String GPS_PROVIDER
{
get
{
return "gps";
}
}
public static global::java.lang.String PASSIVE_PROVIDER
{
get
{
return "passive";
}
}
public static global::java.lang.String KEY_PROXIMITY_ENTERING
{
get
{
return "entering";
}
}
public static global::java.lang.String KEY_STATUS_CHANGED
{
get
{
return "status";
}
}
public static global::java.lang.String KEY_PROVIDER_ENABLED
{
get
{
return "providerEnabled";
}
}
public static global::java.lang.String KEY_LOCATION_CHANGED
{
get
{
return "location";
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.location.LocationManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/LocationManager"));
global::android.location.LocationManager._getProvider4772 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "getProvider", "(Ljava/lang/String;)Landroid/location/LocationProvider;");
global::android.location.LocationManager._getProviders4773 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "getProviders", "(Z)Ljava/util/List;");
global::android.location.LocationManager._getProviders4774 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "getProviders", "(Landroid/location/Criteria;Z)Ljava/util/List;");
global::android.location.LocationManager._getAllProviders4775 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "getAllProviders", "()Ljava/util/List;");
global::android.location.LocationManager._getBestProvider4776 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "getBestProvider", "(Landroid/location/Criteria;Z)Ljava/lang/String;");
global::android.location.LocationManager._requestLocationUpdates4777 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "requestLocationUpdates", "(Ljava/lang/String;JFLandroid/location/LocationListener;)V");
global::android.location.LocationManager._requestLocationUpdates4778 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "requestLocationUpdates", "(Ljava/lang/String;JFLandroid/location/LocationListener;Landroid/os/Looper;)V");
global::android.location.LocationManager._requestLocationUpdates4779 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "requestLocationUpdates", "(Ljava/lang/String;JFLandroid/app/PendingIntent;)V");
global::android.location.LocationManager._removeUpdates4780 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "removeUpdates", "(Landroid/location/LocationListener;)V");
global::android.location.LocationManager._removeUpdates4781 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "removeUpdates", "(Landroid/app/PendingIntent;)V");
global::android.location.LocationManager._addProximityAlert4782 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "addProximityAlert", "(DDFJLandroid/app/PendingIntent;)V");
global::android.location.LocationManager._removeProximityAlert4783 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "removeProximityAlert", "(Landroid/app/PendingIntent;)V");
global::android.location.LocationManager._isProviderEnabled4784 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "isProviderEnabled", "(Ljava/lang/String;)Z");
global::android.location.LocationManager._getLastKnownLocation4785 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "getLastKnownLocation", "(Ljava/lang/String;)Landroid/location/Location;");
global::android.location.LocationManager._addTestProvider4786 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "addTestProvider", "(Ljava/lang/String;ZZZZZZZII)V");
global::android.location.LocationManager._removeTestProvider4787 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "removeTestProvider", "(Ljava/lang/String;)V");
global::android.location.LocationManager._setTestProviderLocation4788 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "setTestProviderLocation", "(Ljava/lang/String;Landroid/location/Location;)V");
global::android.location.LocationManager._clearTestProviderLocation4789 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "clearTestProviderLocation", "(Ljava/lang/String;)V");
global::android.location.LocationManager._setTestProviderEnabled4790 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "setTestProviderEnabled", "(Ljava/lang/String;Z)V");
global::android.location.LocationManager._clearTestProviderEnabled4791 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "clearTestProviderEnabled", "(Ljava/lang/String;)V");
global::android.location.LocationManager._setTestProviderStatus4792 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "setTestProviderStatus", "(Ljava/lang/String;ILandroid/os/Bundle;J)V");
global::android.location.LocationManager._clearTestProviderStatus4793 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "clearTestProviderStatus", "(Ljava/lang/String;)V");
global::android.location.LocationManager._addGpsStatusListener4794 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "addGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)Z");
global::android.location.LocationManager._removeGpsStatusListener4795 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "removeGpsStatusListener", "(Landroid/location/GpsStatus$Listener;)V");
global::android.location.LocationManager._addNmeaListener4796 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "addNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)Z");
global::android.location.LocationManager._removeNmeaListener4797 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "removeNmeaListener", "(Landroid/location/GpsStatus$NmeaListener;)V");
global::android.location.LocationManager._getGpsStatus4798 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "getGpsStatus", "(Landroid/location/GpsStatus;)Landroid/location/GpsStatus;");
global::android.location.LocationManager._sendExtraCommand4799 = @__env.GetMethodIDNoThrow(global::android.location.LocationManager.staticClass, "sendExtraCommand", "(Ljava/lang/String;Ljava/lang/String;Landroid/os/Bundle;)Z");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace hms.entappsettings.webapi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// LocalNetworkGatewaysOperations operations.
/// </summary>
internal partial class LocalNetworkGatewaysOperations : IServiceOperations<NetworkManagementClient>, ILocalNetworkGatewaysOperations
{
/// <summary>
/// Initializes a new instance of the LocalNetworkGatewaysOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LocalNetworkGatewaysOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local network
/// gateway in the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Local Network Gateway
/// operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<LocalNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<LocalNetworkGateway> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, localNetworkGatewayName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local network
/// gateway in the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Local Network Gateway
/// operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LocalNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LocalNetworkGateway>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Get LocalNetworkGateway operation retrieves information about the
/// specified local network gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LocalNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LocalNetworkGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specified local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, localNetworkGatewayName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specified local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
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>
/// The List LocalNetworkGateways operation retrieves all the local network
/// gateways stored.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List LocalNetworkGateways operation retrieves all the local network
/// gateways stored.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="CameraMetadataTag.cs" company="Google">
//
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore
{
/// <summary>
/// This enum follows the layout of NdkCameraMetadataTags.
/// The values in the file are used for requesting / marshaling camera image's metadata.
/// The comments have been removed to keep the code readable. Please refer to
/// NdkCameraMetadataTags.h for documentation:
/// https://developer.android.com/ndk/reference/ndk_camera_metadata_tags_8h.html .
/// </summary>
public enum CameraMetadataTag
{
SectionColorCorrection = 0,
SectionControl = 1,
SectionEdge = 3,
SectionFlash = 4,
SectionFlashInfo = 5,
SectionHotPixel = 6,
SectionJpeg = 7,
SectionLens = 8,
SectionLensInfo = 9,
SectionNoiseReduction = 10,
SectionRequest = 12,
SectionScaler = 13,
SectionSensor = 14,
SectionSensorInfo = 15,
SectionShading = 16,
SectionStatistics = 17,
SectionStatisticsInfo = 18,
SectionTonemap = 19,
SectionInfo = 21,
SectionBlackLevel = 22,
SectionSync = 23,
SectionDepth = 25,
// Start Value Of Each Section.
ColorCorrectionStart = SectionColorCorrection << 16,
ControlStart = SectionControl << 16,
EdgeStart = SectionEdge << 16,
FlashStart = SectionFlash << 16,
FlashInfoStart = SectionFlashInfo << 16,
HotPixelStart = SectionHotPixel << 16,
JpegStart = SectionJpeg << 16,
LensStart = SectionLens << 16,
LensInfoStart = SectionLensInfo << 16,
NoiseReductionStart = SectionNoiseReduction << 16,
RequestStart = SectionRequest << 16,
ScalerStart = SectionScaler << 16,
SensorStart = SectionSensor << 16,
SensorInfoStart = SectionSensorInfo << 16,
ShadingStart = SectionShading << 16,
StatisticsStart = SectionStatistics << 16,
StatisticsInfoStart = SectionStatisticsInfo << 16,
TonemapStart = SectionTonemap << 16,
InfoStart = SectionInfo << 16,
BlackLevelStart = SectionBlackLevel << 16,
SyncStart = SectionSync << 16,
DepthStart = SectionDepth << 16,
// Note that we only expose the keys that could be used in the camera metadata from the capture
// result. The keys may only appear in CameraCharacteristics are not exposed here.
ColorCorrectionMode = // Byte (Enum)
ColorCorrectionStart,
ColorCorrectionTransform = // Rational[33]
ColorCorrectionStart + 1,
ColorCorrectionGains = // Float[4]
ColorCorrectionStart + 2,
ColorCorrectionAberrationMode = // Byte (Enum)
ColorCorrectionStart + 3,
ControlAeAntibandingMode = // Byte (Enum)
ControlStart,
ControlAeExposureCompensation = // Int32
ControlStart + 1,
ControlAeLock = // Byte (Enum)
ControlStart + 2,
ControlAeMode = // Byte (Enum)
ControlStart + 3,
ControlAeRegions = // Int32[5areaCount]
ControlStart + 4,
ControlAeTargetFpsRange = // Int32[2]
ControlStart + 5,
ControlAePrecaptureTrigger = // Byte (Enum)
ControlStart + 6,
ControlAfMode = // Byte (Enum)
ControlStart + 7,
ControlAfRegions = // Int32[5areaCount]
ControlStart + 8,
ControlAfTrigger = // Byte (Enum)
ControlStart + 9,
ControlAwbLock = // Byte (Enum)
ControlStart + 10,
ControlAwbMode = // Byte (Enum)
ControlStart + 11,
ControlAwbRegions = // Int32[5areaCount]
ControlStart + 12,
ControlCaptureIntent = // Byte (Enum)
ControlStart + 13,
ControlEffectMode = // Byte (Enum)
ControlStart + 14,
ControlMode = // Byte (Enum)
ControlStart + 15,
ControlSceneMode = // Byte (Enum)
ControlStart + 16,
ControlVideoStabilizationMode = // Byte (Enum)
ControlStart + 17,
ControlAeState = // Byte (Enum)
ControlStart + 31,
ControlAfState = // Byte (Enum)
ControlStart + 32,
ControlAwbState = // Byte (Enum)
ControlStart + 34,
ControlPostRawSensitivityBoost = // Int32
ControlStart + 40,
EdgeMode = // Byte (Enum)
EdgeStart,
FlashMode = // Byte (Enum)
FlashStart + 2,
FlashState = // Byte (Enum)
FlashStart + 5,
HotPixelMode = // Byte (Enum)
HotPixelStart,
JpegGpsCoordinates = // Double[3]
JpegStart,
JpegGpsProcessingMethod = // Byte
JpegStart + 1,
JpegGpsTimestamp = // Int64
JpegStart + 2,
JpegOrientation = // Int32
JpegStart + 3,
JpegQuality = // Byte
JpegStart + 4,
JpegThumbnailQuality = // Byte
JpegStart + 5,
JpegThumbnailSize = // Int32[2]
JpegStart + 6,
LensAperture = // Float
LensStart,
LensFilterDensity = // Float
LensStart + 1,
LensFocalLength = // Float
LensStart + 2,
LensFocusDistance = // Float
LensStart + 3,
LensOpticalStabilizationMode = // Byte (Enum)
LensStart + 4,
LensPoseRotation = // Float[4]
LensStart + 6,
LensPoseTranslation = // Float[3]
LensStart + 7,
LensFocusRange = // Float[2]
LensStart + 8,
LensState = // Byte (Enum)
LensStart + 9,
LensIntrinsicCalibration = // Float[5]
LensStart + 10,
LensRadialDistortion = // Float[6]
LensStart + 11,
NoiseReductionMode = // Byte (Enum)
NoiseReductionStart,
RequestPipelineDepth = // Byte
RequestStart + 9,
ScalerCropRegion = // Int32[4]
ScalerStart,
SensorExposureTime = // Int64
SensorStart,
SensorFrameDuration = // Int64
SensorStart + 1,
SensorSensitivity = // Int32
SensorStart + 2,
SensorTimestamp = // Int64
SensorStart + 16,
SensorNeutralColorPoint = // Rational[3]
SensorStart + 18,
SensorNoiseProfile = // Double[2Cfa Channels]
SensorStart + 19,
SensorGreenSplit = // Float
SensorStart + 22,
SensorTestPatternData = // Int32[4]
SensorStart + 23,
SensorTestPatternMode = // Int32 (Enum)
SensorStart + 24,
SensorRollingShutterSkew = // Int64
SensorStart + 26,
SensorDynamicBlackLevel = // Float[4]
SensorStart + 28,
SensorDynamicWhiteLevel = // Int32
SensorStart + 29,
ShadingMode = // Byte (Enum)
ShadingStart,
StatisticsFaceDetectMode = // Byte (Enum)
StatisticsStart,
StatisticsHotPixelMapMode = // Byte (Enum)
StatisticsStart + 3,
StatisticsFaceIds = // Int32[N]
StatisticsStart + 4,
StatisticsFaceLandmarks = // Int32[N6]
StatisticsStart + 5,
StatisticsFaceRectangles = // Int32[N4]
StatisticsStart + 6,
StatisticsFaceScores = // Byte[N]
StatisticsStart + 7,
StatisticsLensShadingMap = // Float[4nm]
StatisticsStart + 11,
StatisticsSceneFlicker = // Byte (Enum)
StatisticsStart + 14,
StatisticsHotPixelMap = // Int32[2n]
StatisticsStart + 15,
StatisticsLensShadingMapMode = // Byte (Enum)
StatisticsStart + 16,
TonemapCurveBlue = // Float[N2]
TonemapStart,
TonemapCurveGreen = // Float[N2]
TonemapStart + 1,
TonemapCurveRed = // Float[N2]
TonemapStart + 2,
TonemapMode = // Byte (Enum)
TonemapStart + 3,
TonemapGamma = // Float
TonemapStart + 6,
TonemapPresetCurve = // Byte (Enum)
TonemapStart + 7,
BlackLevelLock = // Byte (Enum)
BlackLevelStart,
SyncFrameNumber = // Int64 (Enum)
SyncStart,
}
}
| |
using System;
using System.Collections;
using System.Drawing;
namespace Dalssoft.DiagramNet
{
/// <summary>
/// Summary description for DiagramUtil.
/// </summary>
internal class DiagramUtil
{
private DiagramUtil()
{
//
// TODO: Add constructor logic here
//
}
#region Point Calc
public static Point DisplayToCartesianCoord(Point p, Rectangle referenceRec)
{
//int x0 = referenceRec.Location.X + (referenceRec.Width / 2);
//int y0 = referenceRec.Location.Y + (referenceRec.Height / 2);
int x0 = (referenceRec.Width / 2);
int y0 = (referenceRec.Height / 2);
return new Point(p.X - x0, p.Y - y0);
}
public static double PointToAngle(Point cartPoint)
{
double angle = (Math.Atan2(cartPoint.Y, cartPoint.X) * (180 / Math.PI));
if ((angle > 0) && (angle < 180))
angle = 360 - angle;
angle = Math.Abs(angle);
return angle;
}
public static CardinalDirection GetDirection(Rectangle rec, Point point)
{
Point p = DisplayToCartesianCoord(point, rec);
double angle = PointToAngle(p);
//East
if (((angle >= 0) && (angle < 45)) || (angle >= 315))
return CardinalDirection.East;
//North
else if ((angle >= 45) && (angle < 135))
return CardinalDirection.North;
//West
else if ((angle >= 135) && (angle < 225))
return CardinalDirection.West;
//South
else if ((angle >= 225) && (angle < 315))
return CardinalDirection.South;
return CardinalDirection.Nothing;
}
public static Point GetUpperPoint(Point[] points)
{
Point upper = Point.Empty;
upper.X = Int32.MaxValue;
upper.Y = Int32.MaxValue;
foreach(Point p in points)
{
if (p.X < upper.X)
upper.X = p.X;
if (p.Y < upper.Y)
upper.Y = p.Y;
}
return upper;
}
public static Point GetLowerPoint(Point[] points)
{
Point lower = Point.Empty;
lower.X = Int32.MinValue;
lower.Y = Int32.MinValue;
foreach(Point p in points)
{
if (p.X > lower.X)
lower.X = p.X;
if (p.Y > lower.Y)
lower.Y = p.Y;
}
return lower;
}
public static Point GetRelativePoint(Point location1, Point location2)
{
Point ret = Point.Empty;
ret.X = location2.X - location1.X;
ret.Y = location2.Y - location1.Y;
return ret;
}
#endregion
#region Draw Font
public static Size MeasureString(string text, Font font)
{
Bitmap bmp = new Bitmap(1,1);
Graphics g = Graphics.FromImage(bmp);
SizeF sizeF = g.MeasureString(text, font);
bmp.Dispose();
g.Dispose();
return Size.Round(sizeF);
}
public static Size MeasureString(string text, Font font, SizeF layoutArea)
{
Bitmap bmp = new Bitmap(1,1);
Graphics g = Graphics.FromImage(bmp);
SizeF sizeF = g.MeasureString(text, font, layoutArea);
bmp.Dispose();
g.Dispose();
return Size.Round(sizeF);
}
public static Size MeasureString(string text, Font font, int width)
{
Bitmap bmp = new Bitmap(1,1);
Graphics g = Graphics.FromImage(bmp);
SizeF sizeF = g.MeasureString(text, font, width);
bmp.Dispose();
g.Dispose();
return Size.Round(sizeF);
}
public static Size MeasureString(string text, Font font, PointF origin, StringFormat stringFormat)
{
Bitmap bmp = new Bitmap(1,1);
Graphics g = Graphics.FromImage(bmp);
SizeF sizeF = g.MeasureString(text, font, origin, stringFormat);
bmp.Dispose();
g.Dispose();
return Size.Round(sizeF);
}
public static Size MeasureString(string text, Font font, SizeF layoutArea, StringFormat stringFormat)
{
Bitmap bmp = new Bitmap(1,1);
Graphics g = Graphics.FromImage(bmp);
SizeF sizeF = g.MeasureString(text, font, layoutArea, stringFormat);
bmp.Dispose();
g.Dispose();
return Size.Round(sizeF);
}
public static Size MeasureString(string text, Font font, int width, StringFormat format)
{
Bitmap bmp = new Bitmap(1,1);
Graphics g = Graphics.FromImage(bmp);
SizeF sizeF = g.MeasureString(text, font, width, format);
bmp.Dispose();
g.Dispose();
return Size.Round(sizeF);
}
public static Size MeasureString(string text, Font font, SizeF layoutArea, StringFormat stringFormat, out int charactersFitted, out int linesFilled)
{
Bitmap bmp = new Bitmap(1,1);
Graphics g = Graphics.FromImage(bmp);
SizeF sizeF = g.MeasureString(text, font, layoutArea, stringFormat, out charactersFitted, out linesFilled);
bmp.Dispose();
g.Dispose();
return Size.Round(sizeF);
}
#endregion
public static int GetInnerElementsCount(BaseElement el)
{
int ret = 0;
if (el is ILabelElement) ret++;
if (el is NodeElement)
{
NodeElement nel = (NodeElement) el;
ret += nel.Connectors.Length;
}
// if (el is IContainer)
// {
// IContainer cel = (IContainer) el;
// ret += cel.Elements.Count;
// }
return ret;
}
public static BaseElement[] GetInnerElements(BaseElement el)
{
BaseElement[] ret = new BaseElement[GetInnerElementsCount(el)];
int i = 0;
if (el is ILabelElement)
{
ret[i] = ((ILabelElement) el).Label;
i++;
}
if (el is NodeElement)
{
NodeElement nel = (NodeElement) el;
ConnectorElement[] innerConnectors = nel.Connectors;
Array.Copy(innerConnectors, 0, ret, i, innerConnectors.Length);
i += innerConnectors.Length;
}
// if (el is IContainer)
// {
// IContainer cel = (IContainer) el;
// BaseElement [] innerElements = cel.Elements.GetArray();
// Array.Copy(innerElements, 0, ret, i, innerElements.Length);
// i += innerElements.Length;
// }
return ret;
}
public class ArrayHelper
{
private ArrayHelper(){}
public static Array Append(Array arr1, Array arr2)
{
Type arr1Type = arr1.GetType().GetElementType();
Type arr2Type = arr1.GetType().GetElementType();
if (arr1Type != arr2Type) throw new Exception("Arrays isn't the same type");
ArrayList arrNew = new ArrayList(arr1.Length + arr2.Length - 1);
arrNew.AddRange(arr1);
arrNew.AddRange(arr2);
return arrNew.ToArray(arr1Type);
}
public static Array Shrink(Array arr, object removeValue)
{
ArrayList arrNew = new ArrayList(arr.Length - 1);
foreach(object o in arr)
{
if (o != removeValue)
arrNew.Add(o);
}
arrNew.TrimToSize();
return arrNew.ToArray(arr.GetType().GetElementType());
}
}
}
}
| |
// 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 Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Authentication
{
public class AzureADB2CAuthenticationBuilderExtensionsTests
{
[Fact]
public void AddAzureADB2C_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2C(o => { });
var provider = services.BuildServiceProvider();
// Assert
Assert.NotNull(provider.GetService<OpenIdConnectHandler>());
Assert.NotNull(provider.GetService<CookieAuthenticationHandler>());
Assert.NotNull(provider.GetService<PolicySchemeHandler>());
}
[Fact]
public void AddAzureADB2C_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2C(o =>
{
o.Instance = "https://login.microsoftonline.com/tfp";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
o.ResetPasswordPolicyId = "B2C_1_SSPR";
o.EditProfilePolicyId = "B2C_1_SiPe";
});
var provider = services.BuildServiceProvider();
// Assert
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
Assert.NotNull(azureADB2COptionsMonitor);
var azureADB2COptions = azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme);
Assert.Equal(AzureADB2CDefaults.OpenIdScheme, azureADB2COptions.OpenIdConnectSchemeName);
Assert.Equal(AzureADB2CDefaults.CookieScheme, azureADB2COptions.CookieSchemeName);
Assert.Equal("https://login.microsoftonline.com/tfp", azureADB2COptions.Instance);
Assert.Equal("ClientId", azureADB2COptions.ClientId);
Assert.Equal("ClientSecret", azureADB2COptions.ClientSecret);
Assert.Equal("/signin-oidc", azureADB2COptions.CallbackPath);
Assert.Equal("domain.onmicrosoft.com", azureADB2COptions.Domain);
Assert.Equal("B2C_1_SiUpIn", azureADB2COptions.SignUpSignInPolicyId);
Assert.Equal("B2C_1_SSPR", azureADB2COptions.ResetPasswordPolicyId);
Assert.Equal("B2C_1_SiPe", azureADB2COptions.EditProfilePolicyId);
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
Assert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADB2CDefaults.OpenIdScheme);
Assert.Equal("ClientId", openIdOptions.ClientId);
Assert.Equal($"https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", openIdOptions.Authority);
Assert.True(openIdOptions.UseTokenLifetime);
Assert.Equal("/signin-oidc", openIdOptions.CallbackPath);
Assert.Equal(AzureADB2CDefaults.CookieScheme, openIdOptions.SignInScheme);
Assert.NotNull(openIdOptions.TokenValidationParameters);
Assert.Equal("name", openIdOptions.TokenValidationParameters.NameClaimType);
Assert.NotNull(openIdOptions.Events);
var redirectHandler = openIdOptions.Events.OnRedirectToIdentityProvider;
Assert.NotNull(redirectHandler);
Assert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
var remoteFailureHanlder = openIdOptions.Events.OnRemoteFailure;
Assert.NotNull(remoteFailureHanlder);
Assert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
var cookieAuthenticationOptionsMonitor = provider.GetService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.NotNull(cookieAuthenticationOptionsMonitor);
var cookieAuthenticationOptions = cookieAuthenticationOptionsMonitor.Get(AzureADB2CDefaults.CookieScheme);
Assert.Equal("/AzureADB2C/Account/SignIn/AzureADB2C", cookieAuthenticationOptions.LoginPath);
Assert.Equal("/AzureADB2C/Account/SignOut/AzureADB2C", cookieAuthenticationOptions.LogoutPath);
Assert.Equal("/AzureADB2C/Account/AccessDenied", cookieAuthenticationOptions.AccessDeniedPath);
Assert.Equal(SameSiteMode.None, cookieAuthenticationOptions.Cookie.SameSite);
}
[Fact]
public void AddAzureADB2C_AllowsOverridingCookiesAndOpenIdConnectSettings()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2C(o =>
{
o.Instance = "https://login.microsoftonline.com";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
});
services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, o =>
{
o.Authority = "https://overriden.com";
});
services.Configure<CookieAuthenticationOptions>(AzureADB2CDefaults.CookieScheme, o =>
{
o.AccessDeniedPath = "/Overriden";
});
var provider = services.BuildServiceProvider();
// Assert
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
Assert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADB2CDefaults.OpenIdScheme);
Assert.Equal("ClientId", openIdOptions.ClientId);
Assert.Equal($"https://overriden.com", openIdOptions.Authority);
var cookieAuthenticationOptionsMonitor = provider.GetService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.NotNull(cookieAuthenticationOptionsMonitor);
var cookieAuthenticationOptions = cookieAuthenticationOptionsMonitor.Get(AzureADB2CDefaults.CookieScheme);
Assert.Equal("/AzureADB2C/Account/SignIn/AzureADB2C", cookieAuthenticationOptions.LoginPath);
Assert.Equal("/Overriden", cookieAuthenticationOptions.AccessDeniedPath);
}
[Fact]
public void AddAzureADB2C_RegisteringAddCookiesAndAddOpenIdConnectHasNoImpactOnAzureAAExtensions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddCookie()
.AddOpenIdConnect()
.AddAzureADB2C(o =>
{
o.Instance = "https://login.microsoftonline.com";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
});
services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, o =>
{
o.Authority = "https://overriden.com";
});
services.Configure<CookieAuthenticationOptions>(AzureADB2CDefaults.CookieScheme, o =>
{
o.AccessDeniedPath = "/Overriden";
});
var provider = services.BuildServiceProvider();
// Assert
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
Assert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADB2CDefaults.OpenIdScheme);
Assert.Equal("ClientId", openIdOptions.ClientId);
Assert.Equal($"https://overriden.com", openIdOptions.Authority);
var cookieAuthenticationOptionsMonitor = provider.GetService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.NotNull(cookieAuthenticationOptionsMonitor);
var cookieAuthenticationOptions = cookieAuthenticationOptionsMonitor.Get(AzureADB2CDefaults.CookieScheme);
Assert.Equal("/AzureADB2C/Account/SignIn/AzureADB2C", cookieAuthenticationOptions.LoginPath);
Assert.Equal("/Overriden", cookieAuthenticationOptions.AccessDeniedPath);
}
[Fact]
public void AddAzureADB2C_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2C(o => { })
.AddAzureADB2C(o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
Assert.Equal("A scheme with the name 'AzureADB2C' was already added.", exception.Message);
}
[Fact]
public void AddAzureADB2C_ThrowsWhenOpenIdSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2C(o => { })
.AddAzureADB2C("Custom", AzureADB2CDefaults.OpenIdScheme, "Cookie", null, o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
var expectedMessage = $"The Open ID Connect scheme 'AzureADB2COpenID' can't be associated with the Azure Active Directory B2C scheme 'Custom'. " +
"The Open ID Connect scheme 'AzureADB2COpenID' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2C'";
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void AddAzureADB2C_ThrowsWhenCookieSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2C(o => { })
.AddAzureADB2C("Custom", "OpenID", AzureADB2CDefaults.CookieScheme, null, o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
var expectedMessage = $"The cookie scheme 'AzureADB2CCookie' can't be associated with the Azure Active Directory B2C scheme 'Custom'. " +
"The cookie scheme 'AzureADB2CCookie' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2C'";
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
Assert.Equal(expectedMessage, exception.Message);
}
[Fact]
public void AddAzureADB2CBearer_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2CBearer(o => { });
var provider = services.BuildServiceProvider();
// Assert
Assert.NotNull(provider.GetService<JwtBearerHandler>());
Assert.NotNull(provider.GetService<PolicySchemeHandler>());
}
[Fact]
public void AddAzureADB2CBearer_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2CBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/tfp";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
});
var provider = services.BuildServiceProvider();
// Assert
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
Assert.NotNull(azureADB2COptionsMonitor);
var options = azureADB2COptionsMonitor.Get(AzureADB2CDefaults.BearerAuthenticationScheme);
Assert.Equal(AzureADB2CDefaults.JwtBearerAuthenticationScheme, options.JwtBearerSchemeName);
Assert.Equal("https://login.microsoftonline.com/tfp", options.Instance);
Assert.Equal("ClientId", options.ClientId);
Assert.Equal("domain.onmicrosoft.com", options.Domain);
Assert.Equal("B2C_1_SiUpIn", options.DefaultPolicy);
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
Assert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADB2CDefaults.JwtBearerAuthenticationScheme);
Assert.Equal("ClientId", bearerOptions.Audience);
Assert.Equal($"https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", bearerOptions.Authority);
}
[Fact]
public void AddAzureADB2CBearer_CanOverrideJwtBearerOptionsConfiguration()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2CBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
});
services.Configure<JwtBearerOptions>(AzureADB2CDefaults.JwtBearerAuthenticationScheme, o =>
{
o.Audience = "http://overriden.com";
});
var provider = services.BuildServiceProvider();
// Assert
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
Assert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADB2CDefaults.JwtBearerAuthenticationScheme);
Assert.Equal("https://login.microsoftonline.com/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", bearerOptions.Authority);
Assert.Equal("http://overriden.com", bearerOptions.Audience);
}
[Fact]
public void AddAzureADB2CBearer_RegisteringJwtBearerHasNoImpactOnAzureAAExtensions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddJwtBearer()
.AddAzureADB2CBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
});
services.Configure<JwtBearerOptions>(AzureADB2CDefaults.JwtBearerAuthenticationScheme, o =>
{
o.Audience = "http://overriden.com";
});
var provider = services.BuildServiceProvider();
// Assert
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
Assert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADB2CDefaults.JwtBearerAuthenticationScheme);
Assert.Equal("https://login.microsoftonline.com/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", bearerOptions.Authority);
Assert.Equal("http://overriden.com", bearerOptions.Audience);
}
[Fact]
public void AddAzureADB2CBearer_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2CBearer(o => { })
.AddAzureADB2CBearer(o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
Assert.Equal("A scheme with the name 'AzureADB2CBearer' was already added.", exception.Message);
}
[Fact]
public void AddAzureADB2CBearer_ThrowsWhenBearerSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2CBearer(o => { })
.AddAzureADB2CBearer("Custom", AzureADB2CDefaults.JwtBearerAuthenticationScheme, o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
var expectedMessage = $"The JSON Web Token Bearer scheme 'AzureADB2CJwtBearer' can't be associated with the Azure Active Directory B2C scheme 'Custom'. " +
"The JSON Web Token Bearer scheme 'AzureADB2CJwtBearer' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2CBearer'";
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
Assert.Equal(expectedMessage, exception.Message);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Diagnostics.Tracing;
using Azure.Core.Diagnostics;
namespace Azure.Messaging.EventHubs.Processor.Diagnostics
{
/// <summary>
/// EventSource for Azure-Messaging-EventHubs-Processor-BlobEventStore traces.
/// </summary>
///
/// <remarks>
/// When defining Start/Stop tasks, the StopEvent.Id must be exactly StartEvent.Id + 1.
///
/// Do not explicitly include the Guid here, since EventSource has a mechanism to automatically
/// map to an EventSource Guid based on the Name (Azure-Messaging-EventHubs-Processor-BlobEventStore).
/// </remarks>
///
[EventSource(Name = EventSourceName)]
internal class BlobEventStoreEventSource : AzureEventSource
{
/// <summary>The name to use for the event source.</summary>
private const string EventSourceName = "Azure-Messaging-EventHubs-Processor-BlobEventStore";
/// <summary>
/// Provides a singleton instance of the event source for callers to
/// use for logging.
/// </summary>
///
public static BlobEventStoreEventSource Log { get; } = new BlobEventStoreEventSource();
/// <summary>
/// Prevents an instance of the <see cref="BlobEventStoreEventSource" /> class from being created
/// outside the scope of this library. Exposed for testing purposes only.
/// </summary>
///
protected BlobEventStoreEventSource() : base(EventSourceName)
{
}
/// <summary>
/// Indicates that a <see cref="BlobsCheckpointStore" /> was created.
/// </summary>
///
/// <param name="typeName">The type name for the checkpoint store.</param>
/// <param name="accountName">The Storage account name corresponding to the associated container client.</param>
/// <param name="containerName">The name of the associated container client.</param>
///
[Event(20, Level = EventLevel.Verbose, Message = "{0} created. AccountName: '{1}'; ContainerName: '{2}'.")]
public virtual void BlobsCheckpointStoreCreated(string typeName,
string accountName,
string containerName)
{
if (IsEnabled())
{
WriteEvent(20, typeName, accountName ?? string.Empty, containerName ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of ownership has started.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
///
[Event(21, Level = EventLevel.Verbose, Message = "Starting to list ownership for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'.")]
public virtual void ListOwnershipStart(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(21, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of ownership has completed.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
/// <param name="ownershipCount">The amount of ownership received from the storage service.</param>
///
[Event(22, Level = EventLevel.Verbose, Message = "Completed listing ownership for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'. There were {3} ownership entries were found.")]
public virtual void ListOwnershipComplete(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
int ownershipCount)
{
if (IsEnabled())
{
WriteEvent(22, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownershipCount);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while retrieving a list of ownership.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(23, Level = EventLevel.Error, Message = "An exception occurred when listing ownership for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; ErrorMessage: '{3}'.")]
public virtual void ListOwnershipError(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(23, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to claim a partition ownership has started.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
///
[Event(24, Level = EventLevel.Verbose, Message = "Starting to claim ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'.")]
public virtual void ClaimOwnershipStart(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier)
{
if (IsEnabled())
{
WriteEvent(24, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve claim partition ownership has completed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
///
[Event(25, Level = EventLevel.Verbose, Message = "Completed the attempt to claim ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'.")]
public virtual void ClaimOwnershipComplete(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier)
{
if (IsEnabled())
{
WriteEvent(25, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty);
}
}
/// <summary>
/// Indicates that an exception was encountered while attempting to retrieve claim partition ownership.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(26, Level = EventLevel.Error, Message = "An exception occurred when claiming ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'. ErrorMessage: '{5}'.")]
public virtual void ClaimOwnershipError(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(26, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that ownership was unable to be claimed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
/// <param name="message">The message for the failure.</param>
///
[Event(27, Level = EventLevel.Informational, Message = "Unable to claim ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'. Message: '{5}'.")]
public virtual void OwnershipNotClaimable(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier,
string message)
{
if (IsEnabled())
{
WriteEvent(27, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty, message ?? string.Empty);
}
}
/// <summary>
/// Indicates that ownership was successfully claimed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being claimed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the ownership is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership is associated with.</param>
/// <param name="ownerIdentifier">The identifier of the processor that attempted to claim the ownership for.</param>
///
[Event(28, Level = EventLevel.Verbose, Message = "Successfully claimed ownership of partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}' for the owner '{4}'.")]
public virtual void OwnershipClaimed(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string ownerIdentifier)
{
if (IsEnabled())
{
WriteEvent(28, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, ownerIdentifier ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of checkpoints has started.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoints are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoints are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoints are associated with.</param>
///
[Event(29, Level = EventLevel.Verbose, Message = "Starting to list checkpoints for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'.")]
public virtual void ListCheckpointsStart(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(29, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a list of checkpoints has completed.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoints are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoints are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoints are associated with.</param>
/// <param name="checkpointCount">The amount of checkpoints received from the storage service.</param>
///
[Event(30, Level = EventLevel.Verbose, Message = "Completed listing checkpoints for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'. There were '{3}' checkpoints found.")]
public virtual void ListCheckpointsComplete(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
int checkpointCount)
{
if (IsEnabled())
{
WriteEvent(30, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, checkpointCount);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while retrieving a list of checkpoints.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoints are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoints are associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(31, Level = EventLevel.Error, Message = "An exception occurred when listing checkpoints for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; ErrorMessage: '{3}'.")]
public virtual void ListCheckpointsError(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(31, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to create/update a checkpoint has started.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being checkpointed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
///
[Event(32, Level = EventLevel.Verbose, Message = "Starting to create/update a checkpoint for partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'.")]
public virtual void UpdateCheckpointStart(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(32, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to update a checkpoint has completed.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being checkpointed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
///
[Event(33, Level = EventLevel.Verbose, Message = "Completed the attempt to create/update a checkpoint for partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'.")]
public virtual void UpdateCheckpointComplete(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(33, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while updating a checkpoint.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition being checkpointed.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(34, Level = EventLevel.Error, Message = "An exception occurred when creating/updating a checkpoint for partition: `{0}` of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'. ErrorMessage: '{4}'.")]
public virtual void UpdateCheckpointError(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(34, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, errorMessage ?? string.Empty);
}
}
/// <summary>
/// Indicates that invalid checkpoint data was found during an attempt to retrieve a list of checkpoints.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition the data is associated with.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the data is associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the data is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the data is associated with.</param>
///
[Event(35, Level = EventLevel.Warning, Message = "An invalid checkpoint was found for partition: '{0}' of FullyQualifiedNamespace: '{1}'; EventHubName: '{2}'; ConsumerGroup: '{3}'. This checkpoint is not valid and will be ignored.")]
public virtual void InvalidCheckpointFound(string partitionId,
string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup)
{
if (IsEnabled())
{
WriteEvent(35, partitionId ?? string.Empty, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a checkpoint has started.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="partitionId">The partition id the specific checkpoint is associated with.</param>
///
[Event(36, Level = EventLevel.Verbose, Message = "Starting to retrieve checkpoint for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; PartitionId: '{3}'.")]
public virtual void GetCheckpointStart(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string partitionId)
{
if (IsEnabled())
{
WriteEvent(36, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, partitionId ?? string.Empty);
}
}
/// <summary>
/// Indicates that an attempt to retrieve a checkpoint has completed.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="partitionId">The partition id the specific checkpoint is associated with.</param>
///
[Event(37, Level = EventLevel.Verbose, Message = "Completed retrieving checkpoint for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'. PartitionId: '{3}'.")]
public virtual void GetCheckpointComplete(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string partitionId)
{
if (IsEnabled())
{
WriteEvent(37, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, partitionId);
}
}
/// <summary>
/// Indicates that an unhandled exception was encountered while retrieving a checkpoint.
/// </summary>
///
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the checkpoint are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub the checkpoint is associated with, relative to the Event Hubs namespace that contains it.</param>
/// <param name="consumerGroup">The name of the consumer group the checkpoint is associated with.</param>
/// <param name="partitionId">The partition id the specific checkpoint is associated with.</param>
/// <param name="errorMessage">The message for the exception that occurred.</param>
///
[Event(38, Level = EventLevel.Error, Message = "An exception occurred when retrieving checkpoint for FullyQualifiedNamespace: '{0}'; EventHubName: '{1}'; ConsumerGroup: '{2}'; PartitionId: '{3}'; ErrorMessage: '{4}'.")]
public virtual void GetCheckpointError(string fullyQualifiedNamespace,
string eventHubName,
string consumerGroup,
string partitionId,
string errorMessage)
{
if (IsEnabled())
{
WriteEvent(38, fullyQualifiedNamespace ?? string.Empty, eventHubName ?? string.Empty, consumerGroup ?? string.Empty, partitionId ?? string.Empty, errorMessage ?? string.Empty);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace gView.SDEWrapper.x64
{
public class CONST
{
public const int SE_MAX_MESSAGE_LENGTH = 512;
public const int SE_MAX_SQL_MESSAGE_LENGTH = 4096;
public const int SE_MAX_CONFIG_KEYWORD_LEN = 32;
public const int SE_MAX_DESCRIPTION_LEN = 64;
public const int SE_MAX_DATABASE_LEN = 32;
public const int SE_MAX_OWNER_LEN = 32;
public const int SE_MAX_TABLE_LEN = 160;
public const int SE_MAX_COLUMN_LEN = 32;
public const int SE_QUALIFIED_TABLE_NAME = (SE_MAX_DATABASE_LEN + SE_MAX_OWNER_LEN + SE_MAX_TABLE_LEN + 2);
public const System.Int32 SE_NIL_TYPE_MASK = (1);
public const System.Int32 SE_POINT_TYPE_MASK = (1 << 1);
public const System.Int32 SE_LINE_TYPE_MASK = (1 << 2);
public const System.Int32 SE_SIMPLE_LINE_TYPE_MASK = (1 << 3);
public const System.Int32 SE_AREA_TYPE_MASK = (1 << 4);
public const System.Int32 SE_UNVERIFIED_SHAPE_MASK = (1 << 11);
public const System.Int32 SE_MULTIPART_TYPE_MASK = (1 << 18);
public const System.Int32 SE_SMALLINT_TYPE = 1; /* 2-byte Integer */
public const System.Int32 SE_INTEGER_TYPE = 2; /* 4-byte Integer */
public const System.Int32 SE_FLOAT_TYPE = 3; /* 4-byte Float */
public const System.Int32 SE_DOUBLE_TYPE = 4; /* 8-byte Float */
public const System.Int32 SE_STRING_TYPE = 5; /* Null Term. Character Array */
public const System.Int32 SE_BLOB_TYPE = 6; /* Variable Length Data */
public const System.Int32 SE_DATE_TYPE = 7; /* Struct tm Date */
public const System.Int32 SE_SHAPE_TYPE = 8; /* Shape geometry (SE_SHAPE) */
public const System.Int32 SE_RASTER_TYPE = 9; /* Raster */
public const System.Int32 SE_XML_TYPE = 10; /* XML Document */
public const System.Int32 SE_INT64_TYPE = 11; /* 8-byte Integer */
public const System.Int32 SE_UUID_TYPE = 12; /* A Universal Unique ID */
public const System.Int32 SE_CLOB_TYPE = 13; /* Character variable length data */
public const System.Int32 SE_NSTRING_TYPE = 14; /* UNICODE Null Term. Character Array */
public const System.Int32 SE_NCLOB_TYPE = 15; /* UNICODE Character Large Object */
public const System.Int32 SE_POINT_TYPE = 20; /* Point ADT */
public const System.Int32 SE_CURVE_TYPE = 21; /* LineString ADT */
public const System.Int32 SE_LINESTRING_TYPE = 22; /* LineString ADT */
public const System.Int32 SE_SURFACE_TYPE = 23; /* Polygon ADT */
public const System.Int32 SE_POLYGON_TYPE = 24; /* Polygon ADT */
public const System.Int32 SE_GEOMETRYCOLLECTION_TYPE = 25; /* MultiPoint ADT */
public const System.Int32 SE_MULTISURFACE_TYPE = 26; /* LineString ADT */
public const System.Int32 SE_MULTICURVE_TYPE = 27; /* LineString ADT */
public const System.Int32 SE_MULTIPOINT_TYPE = 28; /* MultiPoint ADT */
public const System.Int32 SE_MULTILINESTRING_TYPE = 29; /* MultiLineString ADT */
public const System.Int32 SE_MULTIPOLYGON_TYPE = 30; /* MultiPolygon ADT */
public const System.Int32 SE_GEOMETRY_TYPE = 31; /* Geometry ADT */
public const System.Int32 SE_QUERYTYPE_ATTRIBUTE_FIRST = 1;
public const System.Int32 SE_QUERYTYPE_JFA = 2;
public const System.Int32 SE_QUERYTYPE_JSF = 3;
public const System.Int32 SE_QUERYTYPE_JSFA = 4;
public const System.Int32 SE_QUERYTYPE_V3 = 5;
public const System.Int32 SE_MAX_QUERYTYPE = 5;
/************************************************************
*** SEARCH ORDERS
************************************************************/
public const System.Int16 SE_ATTRIBUTE_FIRST = 1; /* DO NOT USE SPATIAL INDEX */
public const System.Int16 SE_SPATIAL_FIRST = 2; /* USE SPATIAL INDEX */
public const System.Int16 SE_OPTIMIZE = 3;
/*
* ...Search Methods...
*/
public const System.Int32 SM_ENVP = 0; /* ENVELOPES OVERLAP */
public const System.Int32 SM_ENVP_BY_GRID = 1; /* ENVELOPES OVERLAP */
public const System.Int32 SM_CP = 2; /* COMMON POINT */
public const System.Int32 SM_LCROSS = 3; /* LINE CROSS */
public const System.Int32 SM_COMMON = 4; /* COMMON EDGE/LINE */
public const System.Int32 SM_CP_OR_LCROSS = 5; /* COMMON POINT OR LINE CROSS */
public const System.Int32 SM_LCROSS_OR_CP = 5; /* COMMON POINT OR LINE CROSS */
public const System.Int32 SM_ET_OR_AI = 6; /* EDGE TOUCH OR AREA INTERSECT */
public const System.Int32 SM_AI_OR_ET = 6; /* EDGE TOUCH OR AREA INTERSECT */
public const System.Int32 SM_ET_OR_II = 6; /* EDGE TOUCH OR INTERIOR INTERSECT */
public const System.Int32 SM_II_OR_ET = 6; /* EDGE TOUCH OR INTERIOR INTERSECT */
public const System.Int32 SM_AI = 7; /* AREA INTERSECT */
public const System.Int32 SM_II = 7; /* INTERIOR INTERSECT */
public const System.Int32 SM_AI_NO_ET = 8; /* AREA INTERSECT AND NO EDGE TOUCH */
public const System.Int32 SM_II_NO_ET = 8; /* INTERIOR INTERSECT AND NO EDGE TOUCH */
public const System.Int32 SM_PC = 9; /* PRIMARY CONTAINED IN SECONDARY */
public const System.Int32 SM_SC = 10; /* SECONDARY CONTAINED IN PRIMARY */
public const System.Int32 SM_PC_NO_ET = 11; /* PRIM CONTAINED AND NO EDGE TOUCH */
public const System.Int32 SM_SC_NO_ET = 12; /* SEC CONTAINED AND NO EDGE TOUCH */
public const System.Int32 SM_PIP = 13; /* FIRST POINT IN PRIMARY IN SEC */
public const System.Int32 SM_IDENTICAL = 15; /* IDENTICAL */
public const System.Int32 SM_CBM = 16; /* Calculus-based method [Clementini] */
/********************************************************************
*** SPATIAL FILTER TYPES FOR SPATIAL CONSTRAINTS AND STABLE SEARCHES
*********************************************************************/
public const System.Int32 SE_SHAPE_FILTER = 1;
public const System.Int32 SE_ID_FILTER = 2;
public const System.Int32 SE_FINISHED = -4;
/*
* ...Allowable shape types...
*/
public const System.Int32 SG_NIL_SHAPE = 0;
public const System.Int32 SG_POINT_SHAPE = 1;
public const System.Int32 SG_LINE_SHAPE = 2;
public const System.Int32 SG_SIMPLE_LINE_SHAPE = 4;
public const System.Int32 SG_AREA_SHAPE = 8;
public const System.Int32 SG_SHAPE_CLASS_MASK = 255; /* Mask all of the previous */
public const System.Int32 SG_SHAPE_MULTI_PART_MASK = 256; /* Bit flag indicates mult parts */
public const System.Int32 SG_MULTI_POINT_SHAPE = 257;
public const System.Int32 SG_MULTI_LINE_SHAPE = 258;
public const System.Int32 SG_MULTI_SIMPLE_LINE_SHAPE = 260;
public const System.Int32 SG_MULTI_AREA_SHAPE = 264;
/****************************/
/*** State Reserved Ids ***/
/****************************/
public const System.Int32 SE_BASE_STATE_ID = (0);
public const System.Int32 SE_NULL_STATE_ID = (-1);
public const System.Int32 SE_DEFAULT_STATE_ID = (-2);
/*************************************/
/*** State Conflict Filter Types ***/
/*************************************/
public const System.Int32 SE_STATE_DIFF_NOCHECK = 0;
public const System.Int32 SE_STATE_DIFF_NOCHANGE_UPDATE = 1;
public const System.Int32 SE_STATE_DIFF_NOCHANGE_DELETE = 2;
public const System.Int32 SE_STATE_DIFF_UPDATE_NOCHANGE = 3;
public const System.Int32 SE_STATE_DIFF_UPDATE_UPDATE = 4;
public const System.Int32 SE_STATE_DIFF_UPDATE_DELETE = 5;
public const System.Int32 SE_STATE_DIFF_INSERT = 6;
}
public enum SE_ROTATION_TYPE
{
SE_DEFAULT_ROTATION,
SE_LEFT_HAND_ROTATION,
SE_RIGHT_HAND_ROTATION
};
// SE_ERROR
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_ERROR_64
{
public System.Int64 sde_error;
public System.Int64 ext_error;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
public byte[] err_msg1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4096)]
public byte[] err_msg2;
}
// SE_CONNECTION
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_CONNECTION_64
{
public System.Int64 handle;
};
// SE_COLUMN_DEF
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_COLUMN_DEF_64
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = CONST.SE_MAX_COLUMN_LEN)]
public byte[] column_name; /* the column name */
public System.Int32 sde_type; /* the SDE data type */
public System.Int32 size; /* the size of the column values */
public System.Int16 decimal_digits; /* number of digits after decimal */
public System.Boolean nulls_allowed; /* allow NULL values ? */
public System.Int16 row_id_type; /* column's use as table's row id */
};
// SE_POINT
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct SE_POINT
{
public double x, y;
}
// SE_REGINFO
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_REGINFO_64
{
public System.Int64 handle;
};
// SE_LAYERINFO
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_LAYERINFO_64
{
public System.Int64 handle;
};
// SE_ENVELOPE
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_ENVELOPE
{
public double minx;
public double miny;
public double maxx;
public double maxy;
};
// SE_SHAPE
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_SHAPE_64
{
public System.Int64 handle;
};
// SE_QUERYINFO
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_QUERYINFO_64
{
public System.Int64 handle;
};
// SE_COORDREF
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_COORDREF_64
{
public System.Int64 handle;
};
//[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)]
//public struct SE_FILTER2
//{
// [FieldOffset(0), MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)]
// public string table; /* the spatial table name */
// [FieldOffset(226), MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_MAX_COLUMN_LEN)]
// public string column; /* the spatial column name */
// [FieldOffset(258)]
// public System.Int32 filter_type; /* the type of spatial filter */
// //union
// //{
// [FieldOffset(262)]
// public SE_SHAPE shape; /* a shape object */
// //struct id
// //{
// [FieldOffset(262)]
// public System.Int32 ID; /* A SDE_ROW_ID id for a shape */
// [FieldOffset(266), MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)]
// string tableID; /* The shape's spatial table */
// //};
// //} filter;
// [FieldOffset(492)]
// public System.Int32 method; /* the search method to satisfy */
// [FieldOffset(496)]
// public System.Boolean truth; /* TRUE to pass the test, FALSE if it must NOT pass */
// [FieldOffset(497)]
// public System.IntPtr cbm_source; /* set ONLY if the method is SM_CBM */
// [FieldOffset(401)]
// public System.IntPtr cbm_object_code; /* internal system use only */
//};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_FILTER
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)]
public string table; /* the spatial table name */
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_MAX_COLUMN_LEN)]
public string column; /* the spatial column name */
public System.Int32 filter_type; /* the type of spatial filter */
//union
//{
public SE_SHAPE_64 shape; /* a shape object */
//struct id
//{
//public System.Int32 ID; /* A SDE_ROW_ID id for a shape */
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CONST.SE_QUALIFIED_TABLE_NAME)]
string tableID; /* The shape's spatial table */
//};
//} filter;
public System.Int32 method; /* the search method to satisfy */
public System.Boolean truth; /* TRUE to pass the test, FALSE if it must NOT pass */
public System.IntPtr cbm_source; /* set ONLY if the method is SM_CBM */
public System.IntPtr cbm_object_code; /* internal system use only */
};
// SE_STREAM
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SE_STREAM_64
{
public System.Int64 handle;
};
// tm
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct tm
{
public int tm_sec; /* seconds after the minute - [0,59] */
public int tm_min; /* minutes after the hour - [0,59] */
public int tm_hour; /* hours since midnight - [0,23] */
public int tm_mday; /* day of the month - [1,31] */
public int tm_mon; /* months since January - [0,11] */
public int tm_year; /* years since 1900 */
public int tm_wday; /* days since Sunday - [0,6] */
public int tm_yday; /* days since January 1 - [0,365] */
public int tm_isdst; /* daylight savings time flag */
};
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BulkSendResponse
/// </summary>
[DataContract]
public partial class BulkSendResponse : IEquatable<BulkSendResponse>, IValidatableObject
{
public BulkSendResponse()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BulkSendResponse" /> class.
/// </summary>
/// <param name="BatchId">BatchId.</param>
/// <param name="BatchName">BatchName.</param>
/// <param name="BatchSize">BatchSize.</param>
/// <param name="EnvelopeOrTemplateId">EnvelopeOrTemplateId.</param>
/// <param name="ErrorDetails">Array or errors..</param>
/// <param name="Errors">Errors.</param>
/// <param name="QueueLimit">QueueLimit.</param>
/// <param name="TotalQueued">TotalQueued.</param>
public BulkSendResponse(string BatchId = default(string), string BatchName = default(string), string BatchSize = default(string), string EnvelopeOrTemplateId = default(string), List<string> ErrorDetails = default(List<string>), List<string> Errors = default(List<string>), string QueueLimit = default(string), string TotalQueued = default(string))
{
this.BatchId = BatchId;
this.BatchName = BatchName;
this.BatchSize = BatchSize;
this.EnvelopeOrTemplateId = EnvelopeOrTemplateId;
this.ErrorDetails = ErrorDetails;
this.Errors = Errors;
this.QueueLimit = QueueLimit;
this.TotalQueued = TotalQueued;
}
/// <summary>
/// Gets or Sets BatchId
/// </summary>
[DataMember(Name="batchId", EmitDefaultValue=false)]
public string BatchId { get; set; }
/// <summary>
/// Gets or Sets BatchName
/// </summary>
[DataMember(Name="batchName", EmitDefaultValue=false)]
public string BatchName { get; set; }
/// <summary>
/// Gets or Sets BatchSize
/// </summary>
[DataMember(Name="batchSize", EmitDefaultValue=false)]
public string BatchSize { get; set; }
/// <summary>
/// Gets or Sets EnvelopeOrTemplateId
/// </summary>
[DataMember(Name="envelopeOrTemplateId", EmitDefaultValue=false)]
public string EnvelopeOrTemplateId { get; set; }
/// <summary>
/// Array or errors.
/// </summary>
/// <value>Array or errors.</value>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public List<string> ErrorDetails { get; set; }
/// <summary>
/// Gets or Sets Errors
/// </summary>
[DataMember(Name="errors", EmitDefaultValue=false)]
public List<string> Errors { get; set; }
/// <summary>
/// Gets or Sets QueueLimit
/// </summary>
[DataMember(Name="queueLimit", EmitDefaultValue=false)]
public string QueueLimit { get; set; }
/// <summary>
/// Gets or Sets TotalQueued
/// </summary>
[DataMember(Name="totalQueued", EmitDefaultValue=false)]
public string TotalQueued { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BulkSendResponse {\n");
sb.Append(" BatchId: ").Append(BatchId).Append("\n");
sb.Append(" BatchName: ").Append(BatchName).Append("\n");
sb.Append(" BatchSize: ").Append(BatchSize).Append("\n");
sb.Append(" EnvelopeOrTemplateId: ").Append(EnvelopeOrTemplateId).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" Errors: ").Append(Errors).Append("\n");
sb.Append(" QueueLimit: ").Append(QueueLimit).Append("\n");
sb.Append(" TotalQueued: ").Append(TotalQueued).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as BulkSendResponse);
}
/// <summary>
/// Returns true if BulkSendResponse instances are equal
/// </summary>
/// <param name="other">Instance of BulkSendResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkSendResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BatchId == other.BatchId ||
this.BatchId != null &&
this.BatchId.Equals(other.BatchId)
) &&
(
this.BatchName == other.BatchName ||
this.BatchName != null &&
this.BatchName.Equals(other.BatchName)
) &&
(
this.BatchSize == other.BatchSize ||
this.BatchSize != null &&
this.BatchSize.Equals(other.BatchSize)
) &&
(
this.EnvelopeOrTemplateId == other.EnvelopeOrTemplateId ||
this.EnvelopeOrTemplateId != null &&
this.EnvelopeOrTemplateId.Equals(other.EnvelopeOrTemplateId)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.SequenceEqual(other.ErrorDetails)
) &&
(
this.Errors == other.Errors ||
this.Errors != null &&
this.Errors.SequenceEqual(other.Errors)
) &&
(
this.QueueLimit == other.QueueLimit ||
this.QueueLimit != null &&
this.QueueLimit.Equals(other.QueueLimit)
) &&
(
this.TotalQueued == other.TotalQueued ||
this.TotalQueued != null &&
this.TotalQueued.Equals(other.TotalQueued)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.BatchId != null)
hash = hash * 59 + this.BatchId.GetHashCode();
if (this.BatchName != null)
hash = hash * 59 + this.BatchName.GetHashCode();
if (this.BatchSize != null)
hash = hash * 59 + this.BatchSize.GetHashCode();
if (this.EnvelopeOrTemplateId != null)
hash = hash * 59 + this.EnvelopeOrTemplateId.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.Errors != null)
hash = hash * 59 + this.Errors.GetHashCode();
if (this.QueueLimit != null)
hash = hash * 59 + this.QueueLimit.GetHashCode();
if (this.TotalQueued != null)
hash = hash * 59 + this.TotalQueued.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph {
/// <summary>
/// IPrefabBuilder is an interface to create Prefab AssetReference from incoming asset group.
/// Subclass of IPrefabBuilder must have CUstomPrefabBuilder attribute.
/// </summary>
public interface IPrefabBuilder {
/// <summary>
/// Called when validating this prefabBuilder.
/// NodeException should be thrown if this modifier is not ready to be used for building.
/// </summary>
void OnValidate ();
/**
*
* @result Name of prefab file if prefab can be created. null if not.
*/
/// <summary>
/// Determines whether this instance can create prefab with the specified groupKey objects.
/// </summary>
/// <returns><c>true</c> if this instance can create prefab the specified groupKey objects; otherwise, <c>false</c>.</returns>
/// <param name="groupKey">Group key.</param>
/// <param name="objects">Objects.</param>
string CanCreatePrefab (string groupKey, List<UnityEngine.Object> objects, UnityEngine.GameObject previous);
/// <summary>
/// Creates the prefab.
/// </summary>
/// <returns>The prefab.</returns>
/// <param name="groupKey">Group key.</param>
/// <param name="objects">Objects.</param>
UnityEngine.GameObject CreatePrefab (string groupKey, List<UnityEngine.Object> objects, UnityEngine.GameObject previous);
/// <summary>
/// Draw Inspector GUI for this PrefabBuilder.
/// </summary>
/// <param name="onValueChanged">On value changed.</param>
void OnInspectorGUI (Action onValueChanged);
}
/// <summary>
/// Custom prefab builder attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class CustomPrefabBuilder : Attribute {
private string m_name;
private string m_version;
private int m_assetThreshold;
private const int kDEFAULT_ASSET_THRES = 10;
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name {
get {
return m_name;
}
}
/// <summary>
/// Gets the version.
/// </summary>
/// <value>The version.</value>
public string Version {
get {
return m_version;
}
}
/// <summary>
/// Gets the asset threshold.
/// </summary>
/// <value>The asset threshold.</value>
public int AssetThreshold {
get {
return m_assetThreshold;
}
}
public CustomPrefabBuilder (string name) {
m_name = name;
m_version = string.Empty;
m_assetThreshold = kDEFAULT_ASSET_THRES;
}
public CustomPrefabBuilder (string name, string version) {
m_name = name;
m_version = version;
m_assetThreshold = kDEFAULT_ASSET_THRES;
}
public CustomPrefabBuilder (string name, string version, int itemThreashold) {
m_name = name;
m_version = version;
m_assetThreshold = itemThreashold;
}
}
public partial class PrefabBuilderUtility {
private static Dictionary<string, string> s_attributeAssemblyQualifiedNameMap;
public static Dictionary<string, string> GetAttributeAssemblyQualifiedNameMap () {
if(s_attributeAssemblyQualifiedNameMap == null) {
// attribute name or class name : class name
s_attributeAssemblyQualifiedNameMap = new Dictionary<string, string>();
var allBuilders = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) {
var builders = assembly.GetTypes()
.Where(t => !t.IsInterface)
.Where(t => typeof(IPrefabBuilder).IsAssignableFrom(t));
allBuilders.AddRange (builders);
}
foreach (var type in allBuilders) {
// set attribute-name as key of dict if atribute is exist.
CustomPrefabBuilder attr =
type.GetCustomAttributes(typeof(CustomPrefabBuilder), true).FirstOrDefault() as CustomPrefabBuilder;
var typename = type.AssemblyQualifiedName;
if (attr != null) {
if (!s_attributeAssemblyQualifiedNameMap.ContainsKey(attr.Name)) {
s_attributeAssemblyQualifiedNameMap[attr.Name] = typename;
}
} else {
s_attributeAssemblyQualifiedNameMap[typename] = typename;
}
}
}
return s_attributeAssemblyQualifiedNameMap;
}
public static string GetPrefabBuilderGUIName(IPrefabBuilder builder) {
CustomPrefabBuilder attr =
builder.GetType().GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder;
return attr.Name;
}
public static bool HasValidCustomPrefabBuilderAttribute(Type t) {
CustomPrefabBuilder attr =
t.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder;
return attr != null && !string.IsNullOrEmpty(attr.Name);
}
public static string GetPrefabBuilderGUIName(string className) {
if(className != null) {
var type = Type.GetType(className);
if(type != null) {
CustomPrefabBuilder attr =
type.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder;
if(attr != null) {
return attr.Name;
}
}
}
return string.Empty;
}
public static string GetPrefabBuilderVersion(string className) {
var type = Type.GetType(className);
if(type != null) {
CustomPrefabBuilder attr =
type.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder;
if(attr != null) {
return attr.Version;
}
}
return string.Empty;
}
public static int GetPrefabBuilderAssetThreshold(string className) {
var type = Type.GetType(className);
if(type != null) {
CustomPrefabBuilder attr =
type.GetCustomAttributes(typeof(CustomPrefabBuilder), false).FirstOrDefault() as CustomPrefabBuilder;
if(attr != null) {
return attr.AssetThreshold;
}
}
return 0;
}
public static string GUINameToAssemblyQualifiedName(string guiName) {
var map = GetAttributeAssemblyQualifiedNameMap();
if(map.ContainsKey(guiName)) {
return map[guiName];
}
return null;
}
public static IPrefabBuilder CreatePrefabBuilder(string guiName) {
var className = GUINameToAssemblyQualifiedName(guiName);
if(className != null) {
var type = Type.GetType(className);
if (type == null) {
return null;
}
return (IPrefabBuilder) type.Assembly.CreateInstance(type.FullName);
}
return null;
}
public static IPrefabBuilder CreatePrefabBuilderByAssemblyQualifiedName(string assemblyQualifiedName) {
if(assemblyQualifiedName == null) {
return null;
}
Type t = Type.GetType(assemblyQualifiedName);
if(t == null) {
return null;
}
if(!HasValidCustomPrefabBuilderAttribute(t)) {
return null;
}
return (IPrefabBuilder) t.Assembly.CreateInstance(t.FullName);
}
}
}
| |
using System;
using MonoBrickFirmware.Extensions;
namespace MonoBrickFirmware.Sensors
{
public class EV3ColorSensor : UartSensor{
/// <summary>
/// Initializes a new instance of the NXTColorSensor class in color mode
/// </summary>
public EV3ColorSensor (SensorPort port) : this(port, ColorMode.Color)
{
}
/// <summary>
/// Initializes a new instance of the NXTColorSensor class.
/// </summary>
/// <param name="mode">Mode.</param>
public EV3ColorSensor (SensorPort port, ColorMode mode) : base(port)
{
base.Initialise(base.uartMode);
Mode = mode;
}
/// <summary>
/// Gets or sets the color mode.
/// </summary>
/// <value>The color mode.</value>
public ColorMode Mode {
get{return SensorModeToColorMode(base.uartMode);}
set{
base.SetMode(ColorModeToSensorMode(value));
}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch (Mode)
{
case ColorMode.Ambient:
s = Read().ToString();
break;
case ColorMode.Color:
s = ReadColor().ToString();
break;
case ColorMode.Reflection:
s = Read().ToString();
break;
case ColorMode.Blue:
s = Read().ToString();
break;
case ColorMode.RGB:
s = ReadRGB().ToString();
break;
default:
s = Read().ToString();
break;
}
return s;
}
/// <summary>
/// Read the raw value of the reflected or ambient light. In color mode the color index is returned
/// </summary>
/// <returns>The raw value</returns>
public int ReadRaw ()
{
return Read();
}
/// <summary>
/// Read the intensity of the reflected or ambient light in percent. In color mode the color index is returned
/// </summary>
public int Read()
{
int value = 0;
switch (Mode)
{
case ColorMode.Color:
value = (int)ReadColor();
break;
default:
value = CalculateRawAverageAsPct();
break;
}
return value;
}
/// <summary>
/// Reads the color.
/// </summary>
/// <returns>The color.</returns>
public Color ReadColor()
{
Color color = Color.None;
if (Mode == ColorMode.Color) {
color = (Color) (base.ReadByte());
}
return color;
}
/// <summary>
/// Reads the RGB color.
/// </summary>
/// <returns>The RGB color.</returns>
public RGBColor ReadRGB()
{
RGBColor rgbColor = null;
if (uartMode == UARTMode.Mode4)
{
byte[] rawBytes = ReadBytes(6);
rgbColor = new RGBColor(rawBytes[0], rawBytes[2], rawBytes[4]);
}
return rgbColor;
}
protected int CalculateRawAverageAsPct ()
{
return(int) base.ReadByte();
}
private UARTMode ColorModeToSensorMode (ColorMode mode)
{
UARTMode sensorMode = UARTMode.Mode0;
switch (mode) {
case ColorMode.Ambient:
sensorMode = UARTMode.Mode1;
break;
case ColorMode.Color:
sensorMode = UARTMode.Mode2;
break;
case ColorMode.Blue:
sensorMode = UARTMode.Mode1;
break;
case ColorMode.Green:
sensorMode = UARTMode.Mode0;//not supported by the EV3 use relection
break;
case ColorMode.Reflection:
sensorMode = UARTMode.Mode0;
break;
case ColorMode.RGB:
sensorMode = UARTMode.Mode4;
break;
}
return sensorMode;
}
private ColorMode SensorModeToColorMode (UARTMode mode)
{
ColorMode colorMode = ColorMode.Reflection;
switch (mode) {
case UARTMode.Mode1:
colorMode = ColorMode.Ambient;
break;
case UARTMode.Mode2:
colorMode = ColorMode.Color;
break;
case UARTMode.Mode0:
colorMode = ColorMode.Reflection;
break;
case UARTMode.Mode4:
colorMode = ColorMode.RGB;
break;
}
return colorMode;
}
public override string GetSensorName ()
{
return "EV3 Color";
}
public override void SelectNextMode()
{
Mode = Mode.Next();
if(Mode == ColorMode.Green)
Mode = Mode.Next();
return;
}
public override void SelectPreviousMode ()
{
Mode = Mode.Previous();
if(Mode == ColorMode.Green)
Mode = Mode.Previous();
return;
}
public override int NumberOfModes ()
{
return Enum.GetNames(typeof(ColorMode)).Length-1;//Green mode not supported;
}
public override string SelectedMode ()
{
return Mode.ToString();
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Media.DialProtocol;
using Windows.Devices.Enumeration;
using ScreenCasting.Data.Common;
using Windows.Media.Casting;
using System.Threading.Tasks;
using ScreenCasting.Data.Azure;
using System.Collections.Generic;
using ScreenCasting.Util;
using Windows.UI.Xaml.Media;
using System.Reflection;
using Windows.UI.ViewManagement;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
namespace ScreenCasting
{
public sealed partial class Scenario3 : Page
{
private const int MAX_RESULTS = 10;
private MainPage rootPage;
private DeviceWatcher watcher;
private DeviceInformation activeDevice = null;
private object activeCastConnectionHandler = null;
private VideoMetaData video = null;
public Scenario3()
{
this.InitializeComponent();
rootPage = MainPage.Current;
// Get the list of available Azure videos.
AzureDataProvider dataProvider = new AzureDataProvider();
List<VideoMetaData> videos = dataProvider.GetAll(MAX_RESULTS);
Random indexRandomizer = new Random();
// Pick a random video
video = videos[indexRandomizer.Next(0, videos.Count - 1)];
//Subscribe to player events
player.MediaOpened += Player_MediaOpened;
player.MediaFailed += Player_MediaFailed;
player.CurrentStateChanged += Player_CurrentStateChanged;
//Set the look and feel of the TransportControls
player.TransportControls.IsCompact = true;
//Set the source on the player
rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
player.Source = video.VideoLink;
this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);
}
private async void castingDevicesList_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
if (castingDevicesList.SelectedItem != null)
{
//Get the selected DeviceInformation obj before we stop the watcher and clear the list
DeviceInformation selectedDeviceInfo = (DeviceInformation)castingDevicesList.SelectedItem;
//When a device is selected, first thing we do is stop the watcher so it's search doesn't conflict with streaming
if (watcher != null && watcher.Status != DeviceWatcherStatus.Stopped)
{
progressText.Text = "Stopping watcher";
StopCurrentWatcher();
}
//Update the display status for the selected device to connecting.
rootPage.NotifyUser("Connecting", NotifyType.StatusMessage);
//Try casting using DIAL first
bool castSucceeded = await TryLaunchDialAppAsync(selectedDeviceInfo);
if (!castSucceeded) castSucceeded = await TryProjectionManagerCastAsync(selectedDeviceInfo);
//If neither dial and projectionamanger worked for the selected device, try the CAST API
if (!castSucceeded)
castSucceeded = await TryCastMediaElementAsync(selectedDeviceInfo);
if (castSucceeded)
{
//Update the display status for the selected device.
rootPage.NotifyUser(string.Format("Casting '{0}'", video.Title), NotifyType.StatusMessage);
disconnectButton.IsEnabled = true;
}
else
{
//Show a retry button when connecting to the selected device failed.
rootPage.NotifyUser(string.Format("Casting {0} failed to device {1}", video.Title, selectedDeviceInfo.Name), NotifyType.ErrorMessage);
}
}
}
private async void disconnectButton_Click(object sender, RoutedEventArgs e)
{
//Update the display status for the selected device.
rootPage.NotifyUser(string.Format("Disconnecting : '{0}'", activeDevice.Name), NotifyType.StatusMessage);
bool disconnected = false;
if (this.activeCastConnectionHandler is DialApp)
disconnected = await TryStopDialAppAsync((DialApp)activeCastConnectionHandler, activeDevice);
if (this.activeCastConnectionHandler is CastingConnection)
disconnected = await TryDisconnectCastingSessionAsync((CastingConnection)activeCastConnectionHandler, activeDevice);
if (disconnected)
{
//Update the display status for the selected device.
rootPage.NotifyUser(string.Format("Disconnected : '{0}'", activeDevice.Name), NotifyType.StatusMessage);
// Set the active device variables to null
activeDevice = null;
activeCastConnectionHandler = null;
disconnectButton.IsEnabled = true;
}
else
{
//Update the display status for the selected device.
rootPage.NotifyUser(string.Format("Disconnecting from '{0}' failed", activeDevice.Name), NotifyType.ErrorMessage);
}
}
private async Task<bool> TryDisconnectCastingSessionAsync(CastingConnection connection, DeviceInformation device)
{
bool disconnected = false;
//Disconnect the casting session
CastingConnectionErrorStatus status = await connection.DisconnectAsync();
if (status == CastingConnectionErrorStatus.Succeeded)
{
rootPage.NotifyUser("Connection disconnected successfully.", NotifyType.StatusMessage);
disconnected = true;
}
else
{
rootPage.NotifyUser(string.Format("Failed to disconnect connection with reason {0}.", status.ToString()), NotifyType.ErrorMessage);
}
return disconnected;
}
private async Task<bool> TryStopDialAppAsync(DialApp app, DeviceInformation device)
{
bool stopped = false;
//Get the current application state
DialAppStateDetails stateDetails = await app.GetAppStateAsync();
switch (stateDetails.State)
{
case DialAppState.NetworkFailure:
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
break;
}
case DialAppState.Stopped:
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application was already stopped.", NotifyType.StatusMessage);
break;
}
default:
{
DialAppStopResult result = await app.StopAsync();
if (result == DialAppStopResult.Stopped)
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application stopped successfully.", NotifyType.StatusMessage);
}
else
{
if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Error occured trying to stop application. Status: '{0}'", result.ToString()), NotifyType.StatusMessage);
}
else //in case of DialAppStopResult.OperationNotSupported, there is not much more you can do. You could implement your own
// mechanism to stop the application on that device.
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Stop is not supported by device: '{0}'", device.Name), NotifyType.ErrorMessage);
}
}
break;
}
}
return stopped;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
#region Watcher Events
private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//Add each discovered device to our listbox
castingDevicesList.Items.Add(args);
});
}
private async void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//Remove any removed devices from our listbox
DeviceInformation removedDevice = null;
foreach (DeviceInformation currentDevice in this.castingDevicesList.Items)
{
if (currentDevice.Id == args.Id)
{
removedDevice = currentDevice;
break;
}
}
this.castingDevicesList.Items.Remove(removedDevice);
});
}
private async void Watcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//If enumeration completes, update UI and transition watcher to the stopped state
rootPage.NotifyUser("Watcher completed enumeration of devices", NotifyType.StatusMessage);
progressText.Text = "Enumeration Completed";
watcher.Stop();
});
}
private async void Watcher_Stopped(DeviceWatcher sender, object args)
{
//unsubscribe from the stopped event
sender.Stopped -= Watcher_Stopped;
//Setting the watcher to null will allow StopCurrentWatcher to continue on the UI thread.
watcher = null;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//Update UX when the watcher stops
rootPage.NotifyUser("Watcher has been stopped", NotifyType.StatusMessage);
progressText.Text = "";
watcherControlButton.Content = "Restart Device Watcher";
progressRing.IsActive = false;
});
}
private async void Watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//If enumeration completes, update UI and transition watcher to the stopped state
rootPage.NotifyUser("Watcher received an update for a listed device", NotifyType.StatusMessage);
//Go through our list of device until you find the DeviceInformation object that is updated.
DeviceInformation updateDevice = null;
foreach (DeviceInformation currentDevice in this.castingDevicesList.Items)
{
if (currentDevice.Id == args.Id)
{
updateDevice = currentDevice;
break;
}
}
//Update the DeviceInformation object.
if (updateDevice != null)
updateDevice.Update(args);
});
}
#endregion
#region Watcher Start and Stop
private void StopCurrentWatcher()
{
if (watcher != null)
{
//Unregister from the watcher events before stopping.
watcher.Added -= Watcher_Added;
watcher.Removed -= Watcher_Removed;
watcher.EnumerationCompleted -= Watcher_EnumerationCompleted;
//If the watcher isn't running, start it up
if (watcher.Status != DeviceWatcherStatus.Stopping)
{
//clear the list as we're starting the watcher over
castingDevicesList.Items.Clear();
//Stop the current watcher
watcher.Stop();
//Hold this thread until Watcher.Stopped has completed
System.Threading.SpinWait.SpinUntil(() =>
{
return watcher == null;
}
);
}
}
}
private async void watcherControlButton_Click(object sender, RoutedEventArgs e)
{
//Pause the video in the local player
this.player.Pause();
StopCurrentWatcher();
this.castingDevicesList.Items.Clear();
CustomDevicePickerFilter filter = new CustomDevicePickerFilter();
//Add the CAST API Filter, so that the application only shows Miracast, Bluetooth, DLNA devices that can render the video
//filter.SupportedDeviceSelectors.Add(await CastingDevice.GetDeviceSelectorFromCastingSourceAsync(this.player.GetAsCastingSource()));
//Add the DIAL Filter, so that the application only shows DIAL devices that have the application installed or advertise that they can install them.
filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));
filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());
filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{D0875FB4-2196-4c7a-A63D-E416ADDD60A1}\"" + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
//Create our watcher and have it find casting devices capable of video casting
watcher = DeviceInformation.CreateWatcher(filter.ToString());
//Register for watcher events
watcher.Added += Watcher_Added;
watcher.Removed += Watcher_Removed;
watcher.Stopped += Watcher_Stopped;
watcher.Updated += Watcher_Updated;
watcher.EnumerationCompleted += Watcher_EnumerationCompleted;
//start the watcher
watcher.Start();
//update the UI to reflect the watcher's state
rootPage.NotifyUser("Watcher has been started", NotifyType.StatusMessage);
progressText.Text = "Searching";
progressRing.IsActive = true;
}
#endregion
ProjectionViewBroker pvb = new ProjectionViewBroker();
int thisViewId;
#region ProjectionManager APIs
private async Task<bool> TryProjectionManagerCastAsync(DeviceInformation device)
{
bool projectionManagerCastAsyncSucceeded = false;
if ((activeDevice == null && ProjectionManager.ProjectionDisplayAvailable && device == null) || device != null)
{
thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
// If projection is already in progress, then it could be shown on the monitor again
// Otherwise, we need to create a new view to show the presentation
if (rootPage.ProjectionViewPageControl == null)
{
// First, create a new, blank view
var thisDispatcher = Window.Current.Dispatcher;
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// ViewLifetimeControl is a wrapper to make sure the view is closed only
// when the app is done with it
rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
// Assemble some data necessary for the new page
pvb.MainPageDispatcher = thisDispatcher;
pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
pvb.MainViewId = thisViewId;
pvb.ProjectionStopping += Pvb_ProjectionStopping;
// Display the page in the view. Note that the view will not become visible
// until "StartProjectingAsync" is called
var rootFrame = new Frame();
rootFrame.Navigate(typeof(ProjectionViewPage), pvb);
Window.Current.Content = rootFrame;
Window.Current.Activate();
});
}
try
{
// Start/StopViewInUse are used to signal that the app is interacting with the
// view, so it shouldn't be closed yet, even if the user loses access to it
rootPage.ProjectionViewPageControl.StartViewInUse();
try
{
//if (ProjectionManager.ProjectionDisplayAvailable)
//{
// // Show the view on a second display (if available) or on the primary display
// await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId);
//}
//else
//{
await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, device);
//}
}
catch (Exception ex)
{
if (!ProjectionManager.ProjectionDisplayAvailable)
throw ex;
}
if (pvb.ProjectedPage != null)
{
this.player.Pause();
await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position);
}
if (device != null)
{
activeDevice = device;
activeCastConnectionHandler = pvb;
}
projectionManagerCastAsyncSucceeded = true;
}
catch (Exception)
{
rootPage.NotifyUser("The projection view is being disposed", NotifyType.ErrorMessage);
}
ApplicationView.GetForCurrentView().ExitFullScreenMode();
}
return projectionManagerCastAsyncSucceeded;
}
private bool TryStopProjectionManagerAsync(ProjectionViewBroker broker)
{
broker.ProjectedPage.StopProjecting();
return true;
}
private async void Pvb_ProjectionStarted(object sender, EventArgs e)
{
//await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
//{
// //rootPage.NotifyUser("Moving Media Element to the second screen", NotifyType.StatusMessage);
// //ProjectionViewBroker broker = sender as ProjectionViewBroker;
//});
}
private async void Pvb_ProjectionStopping(object sender, EventArgs e)
{
ProjectionViewBroker broker = sender as ProjectionViewBroker;
TimeSpan position = broker.ProjectedPage.Player.Position;
Uri source = broker.ProjectedPage.Player.Source;
await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Moving Media Element back to the first screen", NotifyType.StatusMessage);
this.player.Position = position;
this.player.Source = source;
this.player.Play();
});
}
#endregion
#region Media Element Casting Methods
private async Task<bool> TryCastMediaElementAsync(DeviceInformation device)
{
bool castMediaElementSucceeded = false;
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports Miracast, Bluetooth, or DLNA", device.Name), NotifyType.StatusMessage);
if (await CastingDevice.DeviceInfoSupportsCastingAsync(device))
{
CastingConnection connection = null;
//Check to see whether we are casting to the same device
if (activeDevice != null && device.Id == activeDevice.Id)
connection = activeCastConnectionHandler as CastingConnection;
else // if not casting to the same device reset the active device related variables.
{
activeDevice = null;
activeCastConnectionHandler = null;
}
// If we can re-use the existing connection
if (connection == null || connection.State == CastingConnectionState.Disconnected || connection.State == CastingConnectionState.Disconnecting)
{
CastingDevice castDevice = null;
activeDevice = null;
//Try to create a CastingDevice instannce. If it doesn't succeed, the selected device does not support playback of the video source.
rootPage.NotifyUser(string.Format("Attempting to resolve casting device for '{0}'", device.Name), NotifyType.StatusMessage);
try { castDevice = await CastingDevice.FromIdAsync(device.Id); } catch { }
if (castDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support playback of this media", device.Name), NotifyType.StatusMessage);
}
else
{
//Create a casting conneciton from our selected casting device
rootPage.NotifyUser(string.Format("Creating connection for '{0}'", device.Name), NotifyType.StatusMessage);
connection = castDevice.CreateCastingConnection();
//Hook up the casting events
connection.ErrorOccurred += Connection_ErrorOccurred;
connection.StateChanged += Connection_StateChanged;
}
//Cast the content loaded in the media element to the selected casting device
rootPage.NotifyUser(string.Format("Casting to '{0}'", device.Name), NotifyType.StatusMessage);
CastingSource source = null;
// Get the casting source
try { source = player.GetAsCastingSource(); } catch { }
if (source == null)
{
rootPage.NotifyUser(string.Format("Failed to get casting source for video '{0}'", video.Title), NotifyType.ErrorMessage);
}
else
{
CastingConnectionErrorStatus status = await connection.RequestStartCastingAsync(source);
if (status == CastingConnectionErrorStatus.Succeeded)
{
//Remember the device to which casting succeeded
activeDevice = device;
//Remember the current active connection.
activeCastConnectionHandler = connection;
castMediaElementSucceeded = true;
}
else
{
rootPage.NotifyUser(string.Format("Failed to cast to '{0}'", device.Name), NotifyType.ErrorMessage);
}
}
}
}
else
{
rootPage.NotifyUser(string.Format("'{0}' does not support Miracast, Bluetooth, or DLNA", device.Name), NotifyType.StatusMessage);
}
return castMediaElementSucceeded;
}
private async void Connection_StateChanged(CastingConnection sender, object args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
disconnectButton.IsEnabled = !(sender.State == CastingConnectionState.Disconnected || sender.State == CastingConnectionState.Disconnecting);
rootPage.NotifyUser("Casting Connection State Changed: " + sender.State, NotifyType.StatusMessage);
});
}
private async void Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
disconnectButton.IsEnabled = false;
rootPage.NotifyUser("Casting Error Occured: " + args.Message, NotifyType.ErrorMessage);
});
}
#endregion
#region DIAL Casting Methods
private async Task<bool> TryLaunchDialAppAsync(DeviceInformation device)
{
bool dialAppLaunchSucceeded = false;
//Update the launch arguments to include the Position
this.dial_launch_args_textbox.Text = string.Format("v={0}&t={1}&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id, player.Position.Ticks);
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports DIAL", device.Name), NotifyType.StatusMessage);
if (await DialDevice.DeviceInfoSupportsDialAsync(device))
{
DialDevice dialDevice = null;
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Attempting to resolve DIAL device for '{0}'", device.Name), NotifyType.StatusMessage);
try { dialDevice = await DialDevice.FromIdAsync(device.Id); } catch { }
if (dialDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
}
else
{
//Get the DialApp object for the specific application on the selected device
DialApp app = dialDevice.GetDialApp(this.dial_appname_textbox.Text);
if (app == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' cannot find app with ID '{1}'", device.Name, this.dial_appname_textbox.Text), NotifyType.StatusMessage);
}
else
{
//Get the current application state
DialAppStateDetails stateDetails = await app.GetAppStateAsync();
if (stateDetails.State == DialAppState.NetworkFailure)
{
// In case getting the application state failed because of a network failure
rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser(string.Format("Attempting to launch '{0}'", app.AppName), NotifyType.StatusMessage);
//Launch the application on the 1st screen device
DialAppLaunchResult result = await app.RequestLaunchAsync(this.dial_launch_args_textbox.Text);
//Verify to see whether the application was launched
if (result == DialAppLaunchResult.Launched)
{
//Remember the device to which casting succeeded
activeDevice = device;
//DIAL is sessionsless but the DIAL app allows us to get the state and "disconnect".
//Disconnect in the case of DIAL is equivalenet to stopping the app.
activeCastConnectionHandler = app;
rootPage.NotifyUser(string.Format("Launched '{0}'", app.AppName), NotifyType.StatusMessage);
//This is where you will need to add you application specific communication between your 1st and 2nd screen applications
//...
dialAppLaunchSucceeded = true;
}
}
}
}
}
else
{
rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
}
return dialAppLaunchSucceeded;
}
#endregion
#region Media Element Status Changes
private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
{
// As long as the video is ready to play and more importantly get a casting source
// allow the watcher to be started
if (
this.player.CurrentState == MediaElementState.Playing
|| this.player.CurrentState == MediaElementState.Paused
|| this.player.CurrentState == MediaElementState.Buffering
)
{
this.watcherControlButton.IsEnabled = true;
}
else
{
this.watcherControlButton.IsEnabled = false;
StopCurrentWatcher();
}
// Update status
rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
}
private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
}
private void Player_MediaOpened(object sender, RoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
player.Play();
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Hyak.Common;
using Microsoft.Azure.Management.Internal.Resources.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Azure.Management.Internal.Resources
{
/// <summary>
/// Operations for managing tags.
/// </summary>
internal partial class TagOperations : IServiceOperations<ResourceManagementClient>, ITagOperations
{
/// <summary>
/// Initializes a new instance of the TagOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal TagOperations(ResourceManagementClient client)
{
this._client = client;
}
private ResourceManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient.
/// </summary>
public ResourceManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a subscription resource tag.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Tag information.
/// </returns>
public async Task<TagCreateResult> CreateOrUpdateAsync(string tagName, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagCreateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagCreateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
TagDetails tagInstance = new TagDetails();
result.Tag = tagInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
tagInstance.Id = idInstance;
}
JToken tagNameValue = responseDoc["tagName"];
if (tagNameValue != null && tagNameValue.Type != JTokenType.Null)
{
string tagNameInstance = ((string)tagNameValue);
tagInstance.Name = tagNameInstance;
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
tagInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue = countValue["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue);
countInstance.Value = valueInstance;
}
}
JToken valuesArray = responseDoc["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
TagValue tagValueInstance = new TagValue();
tagInstance.Values.Add(tagValueInstance);
JToken idValue2 = valuesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
tagValueInstance.Id = idInstance2;
}
JToken tagValueValue = valuesValue["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance2 = ((string)tagValueValue);
tagValueInstance.Value = tagValueInstance2;
}
JToken countValue2 = valuesValue["count"];
if (countValue2 != null && countValue2.Type != JTokenType.Null)
{
TagCount countInstance2 = new TagCount();
tagValueInstance.Count = countInstance2;
JToken typeValue2 = countValue2["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
countInstance2.Type = typeInstance2;
}
JToken valueValue2 = countValue2["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue2);
countInstance2.Value = valueInstance2;
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a subscription resource tag value.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='tagValue'>
/// Required. The value of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Tag information.
/// </returns>
public async Task<TagCreateValueResult> CreateOrUpdateValueAsync(string tagName, string tagValue, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
if (tagValue == null)
{
throw new ArgumentNullException("tagValue");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateValueAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
url = url + "/tagValues/";
url = url + Uri.EscapeDataString(tagValue);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagCreateValueResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagCreateValueResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
TagValue valueInstance = new TagValue();
result.Value = valueInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
valueInstance.Id = idInstance;
}
JToken tagValueValue = responseDoc["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance = ((string)tagValueValue);
valueInstance.Value = tagValueInstance;
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
valueInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue = countValue["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue);
countInstance.Value = valueInstance2;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete a subscription resource tag.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string tagName, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete a subscription resource tag value.
/// </summary>
/// <param name='tagName'>
/// Required. The name of the tag.
/// </param>
/// <param name='tagValue'>
/// Required. The value of the tag.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteValueAsync(string tagName, string tagValue, CancellationToken cancellationToken)
{
// Validate
if (tagName == null)
{
throw new ArgumentNullException("tagName");
}
if (tagValue == null)
{
throw new ArgumentNullException("tagValue");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
TracingAdapter.Enter(invocationId, this, "DeleteValueAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames/";
url = url + Uri.EscapeDataString(tagName);
url = url + "/tagValues/";
url = url + Uri.EscapeDataString(tagValue);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get a list of subscription resource tags.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of subscription tags.
/// </returns>
public async Task<TagsListResult> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/tagNames";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
TagDetails tagDetailsInstance = new TagDetails();
result.Tags.Add(tagDetailsInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
tagDetailsInstance.Id = idInstance;
}
JToken tagNameValue = valueValue["tagName"];
if (tagNameValue != null && tagNameValue.Type != JTokenType.Null)
{
string tagNameInstance = ((string)tagNameValue);
tagDetailsInstance.Name = tagNameInstance;
}
JToken countValue = valueValue["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
tagDetailsInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue2 = countValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
countInstance.Value = valueInstance;
}
}
JToken valuesArray = valueValue["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
TagValue tagValueInstance = new TagValue();
tagDetailsInstance.Values.Add(tagValueInstance);
JToken idValue2 = valuesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
tagValueInstance.Id = idInstance2;
}
JToken tagValueValue = valuesValue["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance2 = ((string)tagValueValue);
tagValueInstance.Value = tagValueInstance2;
}
JToken countValue2 = valuesValue["count"];
if (countValue2 != null && countValue2.Type != JTokenType.Null)
{
TagCount countInstance2 = new TagCount();
tagValueInstance.Count = countInstance2;
JToken typeValue2 = countValue2["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
countInstance2.Type = typeInstance2;
}
JToken valueValue3 = countValue2["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
countInstance2.Value = valueInstance2;
}
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get a list of tags under a subscription.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of subscription tags.
/// </returns>
public async Task<TagsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TagsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TagsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
TagDetails tagDetailsInstance = new TagDetails();
result.Tags.Add(tagDetailsInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
tagDetailsInstance.Id = idInstance;
}
JToken tagNameValue = valueValue["tagName"];
if (tagNameValue != null && tagNameValue.Type != JTokenType.Null)
{
string tagNameInstance = ((string)tagNameValue);
tagDetailsInstance.Name = tagNameInstance;
}
JToken countValue = valueValue["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
TagCount countInstance = new TagCount();
tagDetailsInstance.Count = countInstance;
JToken typeValue = countValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
countInstance.Type = typeInstance;
}
JToken valueValue2 = countValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
countInstance.Value = valueInstance;
}
}
JToken valuesArray = valueValue["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
TagValue tagValueInstance = new TagValue();
tagDetailsInstance.Values.Add(tagValueInstance);
JToken idValue2 = valuesValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
tagValueInstance.Id = idInstance2;
}
JToken tagValueValue = valuesValue["tagValue"];
if (tagValueValue != null && tagValueValue.Type != JTokenType.Null)
{
string tagValueInstance2 = ((string)tagValueValue);
tagValueInstance.Value = tagValueInstance2;
}
JToken countValue2 = valuesValue["count"];
if (countValue2 != null && countValue2.Type != JTokenType.Null)
{
TagCount countInstance2 = new TagCount();
tagValueInstance.Count = countInstance2;
JToken typeValue2 = countValue2["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
countInstance2.Type = typeInstance2;
}
JToken valueValue3 = countValue2["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
countInstance2.Value = valueInstance2;
}
}
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mike Gorse <mgorse@novell.com>
//
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Atspi;
namespace AtSpiTest
{
public abstract class Base
{
#region Protected Fields
protected Registry registry;
#endregion
#region Private Fields
private Queue<System.Diagnostics.Process> openProcesses = new Queue<System.Diagnostics.Process> ();
#endregion
#region Setup/Teardown
public virtual void StartApplication (string name)
{
Registry.Initialize (true);
System.Diagnostics.Process p = new System.Diagnostics.Process ();
// TODO: It would be better to look at the first line
// of the file, rather than infer from the name.
// How to do this?
p.StartInfo.FileName = (name.Contains (".exe")? "mono": "python");
p.StartInfo.Arguments = name;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.Start ();
openProcesses.Enqueue (p);
}
[TestFixtureTearDown]
public virtual void TearDown ()
{
while (openProcesses.Count > 0) {
System.Diagnostics.Process p = openProcesses.Dequeue ();
if (!p.HasExited)
p.Kill ();
}
Registry.Terminate ();
// give the registry daemon time to process the signal
System.Threading.Thread.Sleep (100);
}
#endregion
#region Private Methods
public static string GetAppPath (string filename)
{
return "../../apps/" + filename;
}
#endregion
#region Protected Helper Methods
protected Accessible FindApplication (string name)
{
return Desktop.Instance.FindDescendant (FindApplicationPredicate, name);
}
protected bool FindApplicationPredicate (Accessible a, object [] args)
{
return (a.Name == (string)args[0] &&
a.Role == Role.Application &&
a.Children.Count > 0);
}
protected bool CheckName (Accessible a, object [] args)
{
return (a.Name == (string)args[0]);
}
protected Accessible GetApplication (string filename)
{
return GetApplication (filename, filename);
}
protected Accessible GetApplication (string filename, string name)
{
if (filename != null)
StartApplication (GetAppPath (filename));
else
Registry.Initialize (true);
for (;;) {
Accessible a = FindApplication (name);
if (a != null)
return a;
Iterate ();
}
}
protected Accessible GetFrame (string filename)
{
return GetFrame (filename, filename);
}
protected Accessible GetFrame (string filename, string name)
{
Accessible app = GetApplication (filename, name);
if (app == null)
return null;
Accessible frame = app.Children [0];
Assert.AreEqual (Role.Frame, frame.Role, "First child should be a window");
return frame;
}
protected Accessible FindByRole (Accessible accessible, Role role)
{
return FindByRole (accessible, role, false);
}
protected Accessible FindByRole (Accessible accessible, Role role, bool wait)
{
return Find (accessible, role, null, wait);
}
protected Accessible Find (Accessible accessible, Role role, string name, bool wait)
{
for (;;) {
Accessible ret = accessible.FindDescendant (Check, role, name);
if (ret != null)
return ret;
if (!wait)
return null;
Iterate ();
}
}
protected bool Check (Accessible accessible, object [] args)
{
return (accessible.Role == (Role)args[0] &&
(args [1] == null || accessible.Name == (string)args [1]));
}
protected void Iterate ()
{
System.Threading.Thread.Sleep (100);
}
public static void States (Accessible accessible, params StateType [] expected)
{
List <StateType> expectedStates = new List <StateType> (expected);
List <StateType> missingStates = new List <StateType> ();
List <StateType> superfluousStates = new List <StateType> ();
StateSet stateSet = accessible.StateSet;
foreach (StateType state in Enum.GetValues (typeof (StateType))) {
if (expectedStates.Contains (state) &&
(!(stateSet.Contains (state))))
missingStates.Add (state);
else if ((!expectedStates.Contains (state)) &&
(stateSet.Contains (state)))
superfluousStates.Add (state);
}
string missingStatesMsg = string.Empty;
string superfluousStatesMsg = string.Empty;
if (missingStates.Count != 0) {
missingStatesMsg = "Missing states: ";
foreach (StateType state in missingStates)
missingStatesMsg += state.ToString () + ",";
}
if (superfluousStates.Count != 0) {
superfluousStatesMsg = "Superfluous states: ";
foreach (StateType state in superfluousStates)
superfluousStatesMsg += state.ToString () + ",";
}
Assert.IsTrue ((missingStates.Count == 0) && (superfluousStates.Count == 0),
missingStatesMsg + " .. " + superfluousStatesMsg);
}
#endregion
#region Abstract Members
#endregion
}
}
| |
using System;
namespace Chaos.NaCl.Internal.Ed25519Ref10;
internal static partial class ScalarOperations
{
private static Int64 load_3(byte[] input, int offset)
{
Int64 result;
result = (Int64)input[offset + 0];
result |= ((Int64)input[offset + 1]) << 8;
result |= ((Int64)input[offset + 2]) << 16;
return result;
}
private static Int64 load_4(byte[] input, int offset)
{
Int64 result;
result = (Int64)input[offset + 0];
result |= ((Int64)input[offset + 1]) << 8;
result |= ((Int64)input[offset + 2]) << 16;
result |= ((Int64)input[offset + 3]) << 24;
return result;
}
/*
Input:
a[0]+256*a[1]+...+256^31*a[31] = a
b[0]+256*b[1]+...+256^31*b[31] = b
c[0]+256*c[1]+...+256^31*c[31] = c
Output:
s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l
where l = 2^252 + 27742317777372353535851937790883648493.
*/
public static void sc_muladd(byte[] s, byte[] a, byte[] b, byte[] c)
{
Int64 a0 = 2097151 & load_3(a, 0);
Int64 a1 = 2097151 & (load_4(a, 2) >> 5);
Int64 a2 = 2097151 & (load_3(a, 5) >> 2);
Int64 a3 = 2097151 & (load_4(a, 7) >> 7);
Int64 a4 = 2097151 & (load_4(a, 10) >> 4);
Int64 a5 = 2097151 & (load_3(a, 13) >> 1);
Int64 a6 = 2097151 & (load_4(a, 15) >> 6);
Int64 a7 = 2097151 & (load_3(a, 18) >> 3);
Int64 a8 = 2097151 & load_3(a, 21);
Int64 a9 = 2097151 & (load_4(a, 23) >> 5);
Int64 a10 = 2097151 & (load_3(a, 26) >> 2);
Int64 a11 = (load_4(a, 28) >> 7);
Int64 b0 = 2097151 & load_3(b, 0);
Int64 b1 = 2097151 & (load_4(b, 2) >> 5);
Int64 b2 = 2097151 & (load_3(b, 5) >> 2);
Int64 b3 = 2097151 & (load_4(b, 7) >> 7);
Int64 b4 = 2097151 & (load_4(b, 10) >> 4);
Int64 b5 = 2097151 & (load_3(b, 13) >> 1);
Int64 b6 = 2097151 & (load_4(b, 15) >> 6);
Int64 b7 = 2097151 & (load_3(b, 18) >> 3);
Int64 b8 = 2097151 & load_3(b, 21);
Int64 b9 = 2097151 & (load_4(b, 23) >> 5);
Int64 b10 = 2097151 & (load_3(b, 26) >> 2);
Int64 b11 = (load_4(b, 28) >> 7);
Int64 c0 = 2097151 & load_3(c, 0);
Int64 c1 = 2097151 & (load_4(c, 2) >> 5);
Int64 c2 = 2097151 & (load_3(c, 5) >> 2);
Int64 c3 = 2097151 & (load_4(c, 7) >> 7);
Int64 c4 = 2097151 & (load_4(c, 10) >> 4);
Int64 c5 = 2097151 & (load_3(c, 13) >> 1);
Int64 c6 = 2097151 & (load_4(c, 15) >> 6);
Int64 c7 = 2097151 & (load_3(c, 18) >> 3);
Int64 c8 = 2097151 & load_3(c, 21);
Int64 c9 = 2097151 & (load_4(c, 23) >> 5);
Int64 c10 = 2097151 & (load_3(c, 26) >> 2);
Int64 c11 = (load_4(c, 28) >> 7);
Int64 s0;
Int64 s1;
Int64 s2;
Int64 s3;
Int64 s4;
Int64 s5;
Int64 s6;
Int64 s7;
Int64 s8;
Int64 s9;
Int64 s10;
Int64 s11;
Int64 s12;
Int64 s13;
Int64 s14;
Int64 s15;
Int64 s16;
Int64 s17;
Int64 s18;
Int64 s19;
Int64 s20;
Int64 s21;
Int64 s22;
Int64 s23;
Int64 carry0;
Int64 carry1;
Int64 carry2;
Int64 carry3;
Int64 carry4;
Int64 carry5;
Int64 carry6;
Int64 carry7;
Int64 carry8;
Int64 carry9;
Int64 carry10;
Int64 carry11;
Int64 carry12;
Int64 carry13;
Int64 carry14;
Int64 carry15;
Int64 carry16;
Int64 carry17;
Int64 carry18;
Int64 carry19;
Int64 carry20;
Int64 carry21;
Int64 carry22;
s0 = c0 + a0 * b0;
s1 = c1 + a0 * b1 + a1 * b0;
s2 = c2 + a0 * b2 + a1 * b1 + a2 * b0;
s3 = c3 + a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0;
s4 = c4 + a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0;
s5 = c5 + a0 * b5 + a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + a5 * b0;
s6 = c6 + a0 * b6 + a1 * b5 + a2 * b4 + a3 * b3 + a4 * b2 + a5 * b1 + a6 * b0;
s7 = c7 + a0 * b7 + a1 * b6 + a2 * b5 + a3 * b4 + a4 * b3 + a5 * b2 + a6 * b1 + a7 * b0;
s8 = c8 + a0 * b8 + a1 * b7 + a2 * b6 + a3 * b5 + a4 * b4 + a5 * b3 + a6 * b2 + a7 * b1 + a8 * b0;
s9 = c9 + a0 * b9 + a1 * b8 + a2 * b7 + a3 * b6 + a4 * b5 + a5 * b4 + a6 * b3 + a7 * b2 + a8 * b1 + a9 * b0;
s10 = c10 + a0 * b10 + a1 * b9 + a2 * b8 + a3 * b7 + a4 * b6 + a5 * b5 + a6 * b4 + a7 * b3 + a8 * b2 + a9 * b1 + a10 * b0;
s11 = c11 + a0 * b11 + a1 * b10 + a2 * b9 + a3 * b8 + a4 * b7 + a5 * b6 + a6 * b5 + a7 * b4 + a8 * b3 + a9 * b2 + a10 * b1 + a11 * b0;
s12 = a1 * b11 + a2 * b10 + a3 * b9 + a4 * b8 + a5 * b7 + a6 * b6 + a7 * b5 + a8 * b4 + a9 * b3 + a10 * b2 + a11 * b1;
s13 = a2 * b11 + a3 * b10 + a4 * b9 + a5 * b8 + a6 * b7 + a7 * b6 + a8 * b5 + a9 * b4 + a10 * b3 + a11 * b2;
s14 = a3 * b11 + a4 * b10 + a5 * b9 + a6 * b8 + a7 * b7 + a8 * b6 + a9 * b5 + a10 * b4 + a11 * b3;
s15 = a4 * b11 + a5 * b10 + a6 * b9 + a7 * b8 + a8 * b7 + a9 * b6 + a10 * b5 + a11 * b4;
s16 = a5 * b11 + a6 * b10 + a7 * b9 + a8 * b8 + a9 * b7 + a10 * b6 + a11 * b5;
s17 = a6 * b11 + a7 * b10 + a8 * b9 + a9 * b8 + a10 * b7 + a11 * b6;
s18 = a7 * b11 + a8 * b10 + a9 * b9 + a10 * b8 + a11 * b7;
s19 = a8 * b11 + a9 * b10 + a10 * b9 + a11 * b8;
s20 = a9 * b11 + a10 * b10 + a11 * b9;
s21 = a10 * b11 + a11 * b10;
s22 = a11 * b11;
s23 = 0;
carry0 = (s0 + (1 << 20)) >> 21; s1 += carry0; s0 -= carry0 << 21;
carry2 = (s2 + (1 << 20)) >> 21; s3 += carry2; s2 -= carry2 << 21;
carry4 = (s4 + (1 << 20)) >> 21; s5 += carry4; s4 -= carry4 << 21;
carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; s6 -= carry6 << 21;
carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; s8 -= carry8 << 21;
carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; s10 -= carry10 << 21;
carry12 = (s12 + (1 << 20)) >> 21; s13 += carry12; s12 -= carry12 << 21;
carry14 = (s14 + (1 << 20)) >> 21; s15 += carry14; s14 -= carry14 << 21;
carry16 = (s16 + (1 << 20)) >> 21; s17 += carry16; s16 -= carry16 << 21;
carry18 = (s18 + (1 << 20)) >> 21; s19 += carry18; s18 -= carry18 << 21;
carry20 = (s20 + (1 << 20)) >> 21; s21 += carry20; s20 -= carry20 << 21;
carry22 = (s22 + (1 << 20)) >> 21; s23 += carry22; s22 -= carry22 << 21;
carry1 = (s1 + (1 << 20)) >> 21; s2 += carry1; s1 -= carry1 << 21;
carry3 = (s3 + (1 << 20)) >> 21; s4 += carry3; s3 -= carry3 << 21;
carry5 = (s5 + (1 << 20)) >> 21; s6 += carry5; s5 -= carry5 << 21;
carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; s7 -= carry7 << 21;
carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; s9 -= carry9 << 21;
carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; s11 -= carry11 << 21;
carry13 = (s13 + (1 << 20)) >> 21; s14 += carry13; s13 -= carry13 << 21;
carry15 = (s15 + (1 << 20)) >> 21; s16 += carry15; s15 -= carry15 << 21;
carry17 = (s17 + (1 << 20)) >> 21; s18 += carry17; s17 -= carry17 << 21;
carry19 = (s19 + (1 << 20)) >> 21; s20 += carry19; s19 -= carry19 << 21;
carry21 = (s21 + (1 << 20)) >> 21; s22 += carry21; s21 -= carry21 << 21;
s11 += s23 * 666643;
s12 += s23 * 470296;
s13 += s23 * 654183;
s14 -= s23 * 997805;
s15 += s23 * 136657;
s16 -= s23 * 683901;
s23 = 0;
s10 += s22 * 666643;
s11 += s22 * 470296;
s12 += s22 * 654183;
s13 -= s22 * 997805;
s14 += s22 * 136657;
s15 -= s22 * 683901;
s22 = 0;
s9 += s21 * 666643;
s10 += s21 * 470296;
s11 += s21 * 654183;
s12 -= s21 * 997805;
s13 += s21 * 136657;
s14 -= s21 * 683901;
s21 = 0;
s8 += s20 * 666643;
s9 += s20 * 470296;
s10 += s20 * 654183;
s11 -= s20 * 997805;
s12 += s20 * 136657;
s13 -= s20 * 683901;
s20 = 0;
s7 += s19 * 666643;
s8 += s19 * 470296;
s9 += s19 * 654183;
s10 -= s19 * 997805;
s11 += s19 * 136657;
s12 -= s19 * 683901;
s19 = 0;
s6 += s18 * 666643;
s7 += s18 * 470296;
s8 += s18 * 654183;
s9 -= s18 * 997805;
s10 += s18 * 136657;
s11 -= s18 * 683901;
s18 = 0;
carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; s6 -= carry6 << 21;
carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; s8 -= carry8 << 21;
carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; s10 -= carry10 << 21;
carry12 = (s12 + (1 << 20)) >> 21; s13 += carry12; s12 -= carry12 << 21;
carry14 = (s14 + (1 << 20)) >> 21; s15 += carry14; s14 -= carry14 << 21;
carry16 = (s16 + (1 << 20)) >> 21; s17 += carry16; s16 -= carry16 << 21;
carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; s7 -= carry7 << 21;
carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; s9 -= carry9 << 21;
carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; s11 -= carry11 << 21;
carry13 = (s13 + (1 << 20)) >> 21; s14 += carry13; s13 -= carry13 << 21;
carry15 = (s15 + (1 << 20)) >> 21; s16 += carry15; s15 -= carry15 << 21;
s5 += s17 * 666643;
s6 += s17 * 470296;
s7 += s17 * 654183;
s8 -= s17 * 997805;
s9 += s17 * 136657;
s10 -= s17 * 683901;
s17 = 0;
s4 += s16 * 666643;
s5 += s16 * 470296;
s6 += s16 * 654183;
s7 -= s16 * 997805;
s8 += s16 * 136657;
s9 -= s16 * 683901;
s16 = 0;
s3 += s15 * 666643;
s4 += s15 * 470296;
s5 += s15 * 654183;
s6 -= s15 * 997805;
s7 += s15 * 136657;
s8 -= s15 * 683901;
s15 = 0;
s2 += s14 * 666643;
s3 += s14 * 470296;
s4 += s14 * 654183;
s5 -= s14 * 997805;
s6 += s14 * 136657;
s7 -= s14 * 683901;
s14 = 0;
s1 += s13 * 666643;
s2 += s13 * 470296;
s3 += s13 * 654183;
s4 -= s13 * 997805;
s5 += s13 * 136657;
s6 -= s13 * 683901;
s13 = 0;
s0 += s12 * 666643;
s1 += s12 * 470296;
s2 += s12 * 654183;
s3 -= s12 * 997805;
s4 += s12 * 136657;
s5 -= s12 * 683901;
s12 = 0;
carry0 = (s0 + (1 << 20)) >> 21; s1 += carry0; s0 -= carry0 << 21;
carry2 = (s2 + (1 << 20)) >> 21; s3 += carry2; s2 -= carry2 << 21;
carry4 = (s4 + (1 << 20)) >> 21; s5 += carry4; s4 -= carry4 << 21;
carry6 = (s6 + (1 << 20)) >> 21; s7 += carry6; s6 -= carry6 << 21;
carry8 = (s8 + (1 << 20)) >> 21; s9 += carry8; s8 -= carry8 << 21;
carry10 = (s10 + (1 << 20)) >> 21; s11 += carry10; s10 -= carry10 << 21;
carry1 = (s1 + (1 << 20)) >> 21; s2 += carry1; s1 -= carry1 << 21;
carry3 = (s3 + (1 << 20)) >> 21; s4 += carry3; s3 -= carry3 << 21;
carry5 = (s5 + (1 << 20)) >> 21; s6 += carry5; s5 -= carry5 << 21;
carry7 = (s7 + (1 << 20)) >> 21; s8 += carry7; s7 -= carry7 << 21;
carry9 = (s9 + (1 << 20)) >> 21; s10 += carry9; s9 -= carry9 << 21;
carry11 = (s11 + (1 << 20)) >> 21; s12 += carry11; s11 -= carry11 << 21;
s0 += s12 * 666643;
s1 += s12 * 470296;
s2 += s12 * 654183;
s3 -= s12 * 997805;
s4 += s12 * 136657;
s5 -= s12 * 683901;
s12 = 0;
carry0 = s0 >> 21; s1 += carry0; s0 -= carry0 << 21;
carry1 = s1 >> 21; s2 += carry1; s1 -= carry1 << 21;
carry2 = s2 >> 21; s3 += carry2; s2 -= carry2 << 21;
carry3 = s3 >> 21; s4 += carry3; s3 -= carry3 << 21;
carry4 = s4 >> 21; s5 += carry4; s4 -= carry4 << 21;
carry5 = s5 >> 21; s6 += carry5; s5 -= carry5 << 21;
carry6 = s6 >> 21; s7 += carry6; s6 -= carry6 << 21;
carry7 = s7 >> 21; s8 += carry7; s7 -= carry7 << 21;
carry8 = s8 >> 21; s9 += carry8; s8 -= carry8 << 21;
carry9 = s9 >> 21; s10 += carry9; s9 -= carry9 << 21;
carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21;
carry11 = s11 >> 21; s12 += carry11; s11 -= carry11 << 21;
s0 += s12 * 666643;
s1 += s12 * 470296;
s2 += s12 * 654183;
s3 -= s12 * 997805;
s4 += s12 * 136657;
s5 -= s12 * 683901;
s12 = 0;
carry0 = s0 >> 21; s1 += carry0; s0 -= carry0 << 21;
carry1 = s1 >> 21; s2 += carry1; s1 -= carry1 << 21;
carry2 = s2 >> 21; s3 += carry2; s2 -= carry2 << 21;
carry3 = s3 >> 21; s4 += carry3; s3 -= carry3 << 21;
carry4 = s4 >> 21; s5 += carry4; s4 -= carry4 << 21;
carry5 = s5 >> 21; s6 += carry5; s5 -= carry5 << 21;
carry6 = s6 >> 21; s7 += carry6; s6 -= carry6 << 21;
carry7 = s7 >> 21; s8 += carry7; s7 -= carry7 << 21;
carry8 = s8 >> 21; s9 += carry8; s8 -= carry8 << 21;
carry9 = s9 >> 21; s10 += carry9; s9 -= carry9 << 21;
carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21;
unchecked
{
s[0] = (byte)(s0 >> 0);
s[1] = (byte)(s0 >> 8);
s[2] = (byte)((s0 >> 16) | (s1 << 5));
s[3] = (byte)(s1 >> 3);
s[4] = (byte)(s1 >> 11);
s[5] = (byte)((s1 >> 19) | (s2 << 2));
s[6] = (byte)(s2 >> 6);
s[7] = (byte)((s2 >> 14) | (s3 << 7));
s[8] = (byte)(s3 >> 1);
s[9] = (byte)(s3 >> 9);
s[10] = (byte)((s3 >> 17) | (s4 << 4));
s[11] = (byte)(s4 >> 4);
s[12] = (byte)(s4 >> 12);
s[13] = (byte)((s4 >> 20) | (s5 << 1));
s[14] = (byte)(s5 >> 7);
s[15] = (byte)((s5 >> 15) | (s6 << 6));
s[16] = (byte)(s6 >> 2);
s[17] = (byte)(s6 >> 10);
s[18] = (byte)((s6 >> 18) | (s7 << 3));
s[19] = (byte)(s7 >> 5);
s[20] = (byte)(s7 >> 13);
s[21] = (byte)(s8 >> 0);
s[22] = (byte)(s8 >> 8);
s[23] = (byte)((s8 >> 16) | (s9 << 5));
s[24] = (byte)(s9 >> 3);
s[25] = (byte)(s9 >> 11);
s[26] = (byte)((s9 >> 19) | (s10 << 2));
s[27] = (byte)(s10 >> 6);
s[28] = (byte)((s10 >> 14) | (s11 << 7));
s[29] = (byte)(s11 >> 1);
s[30] = (byte)(s11 >> 9);
s[31] = (byte)(s11 >> 17);
}
}
}
| |
/***************************************************************************************************************
* IcsLinearLayout.cs
*
* Copyright (c) 2015, Shahman Teh Sharifuddin
* All rights reserved.
*
**************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace TabCarouselPage.Droid.Widget
{
public class IcsLinearLayout : LinearLayout
{
public static readonly int[] LinearLayoutResources = new[] {
/* 0 */ global::Android.Resource.Attribute.Divider ,
/* 1 */ global::Android.Resource.Attribute.ShowDividers ,
/* 2 */ global::Android.Resource.Attribute.DividerPadding
};
private enum EAttributeIndex
{
Divider = 0,
ShowDivider = 1,
DividerPadding = 2
}
// private const int LinearLayoutDivider = 0;
// private const int LinearLayoutShowDivider = 1;
// private const int LinearLayoutDividerPadding = 2;
private global::Android.Graphics.Drawables.Drawable divider;
private int dividerWidth;
private int dividerHeight;
private readonly int showDividers;
private readonly int dividerPadding;
protected IcsLinearLayout(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { }
public IcsLinearLayout(Context context) : base(context) { }
public IcsLinearLayout(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { }
public IcsLinearLayout(Context context, int themeAttr)
: base(context)
{
var a = context.ObtainStyledAttributes(null, LinearLayoutResources, themeAttr, 0);
SetDividerDrawable(a.GetDrawable((int)EAttributeIndex.Divider));
dividerPadding = a.GetDimensionPixelSize((int)EAttributeIndex.DividerPadding, 0);
showDividers = a.GetInteger((int)EAttributeIndex.ShowDivider, (int)ShowDividers.None);
a.Recycle();
}
public IcsLinearLayout(Context context, IAttributeSet attrs)
: base(context, attrs)
{
var a = context.ObtainStyledAttributes(null, LinearLayoutResources, attrs.StyleAttribute, 0);
SetDividerDrawable(a.GetDrawable((int)EAttributeIndex.Divider));
dividerPadding = a.GetDimensionPixelSize((int)EAttributeIndex.DividerPadding, 0);
showDividers = a.GetInteger((int)EAttributeIndex.ShowDivider, (int)ShowDividers.None);
a.Recycle();
}
public override sealed void SetDividerDrawable(global::Android.Graphics.Drawables.Drawable divider)
{
if (divider == this.divider)
{
return;
}
this.divider = divider;
if (divider != null)
{
dividerWidth = divider.IntrinsicWidth;
dividerHeight = divider.IntrinsicHeight;
}
else
{
dividerWidth = 0;
dividerHeight = 0;
}
SetWillNotDraw(divider == null);
RequestLayout();
}
protected override void MeasureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)
{
var index = IndexOfChild(child);
var orientation = Orientation;
var layoutParams = ((LayoutParams)(child.LayoutParameters));
if (HasDividerBeforeChildAt(index))
{
if (orientation == global::Android.Widget.Orientation.Vertical)
{
//Account for the divider by pushing everything up
layoutParams.TopMargin = dividerHeight;
}
else
{
//Account for the divider by pushing everything left
layoutParams.LeftMargin = dividerWidth;
}
}
var count = ChildCount;
if (index == count - 1)
{
if (HasDividerBeforeChildAt(count))
{
if (orientation == global::Android.Widget.Orientation.Vertical)
{
layoutParams.BottomMargin = dividerHeight;
}
else
{
layoutParams.RightMargin = dividerWidth;
}
}
}
base.MeasureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
}
protected override void OnDraw(Canvas canvas)
{
if (divider != null)
{
if (Orientation == global::Android.Widget.Orientation.Vertical)
{
DrawDividerVertical(canvas);
}
else
{
DrawDividersHorizontal(canvas);
}
}
base.OnDraw(canvas);
}
private void DrawDividerVertical(Canvas canvas)
{
var count = ChildCount;
for (var i = 0; i < count; i++)
{
var child = GetChildAt(i);
if (child != null && child.Visibility != ViewStates.Gone)
{
if (HasDividerBeforeChildAt(i))
{
var layoutParams = ((LayoutParams)(child.LayoutParameters));
var top = child.Top = layoutParams.TopMargin /*- mDividerHeight*/;
DrawHorizontalDivider(canvas, top);
}
}
}
if (HasDividerBeforeChildAt(count))
{
var child = GetChildAt(count - 1);
var bottom = 0;
if (child == null)
{
bottom = Height - PaddingBottom - dividerHeight;
}
else
{
//LayoutParams layoutParams = ( ( LayoutParams ) ( child.LayoutParameters ) );
bottom = child.Bottom /* + layoutParams.BottomMargin*/;
}
DrawHorizontalDivider(canvas, bottom);
}
}
private void DrawDividersHorizontal(Canvas canvas)
{
var count = ChildCount;
for (var i = 0; i < count; i++)
{
var child = GetChildAt(i);
if (child != null && child.Visibility != ViewStates.Gone)
{
if (HasDividerBeforeChildAt(i))
{
var layoutParams = ((LayoutParams)(child.LayoutParameters));
var left = child.Left - layoutParams.LeftMargin /* - mDividerWidth */;
DrawVerticalDivider(canvas, left);
}
}
}
if (HasDividerBeforeChildAt(count))
{
var child = GetChildAt(count - 1);
var right = 0;
if (child == null)
{
right = Width - PaddingRight - dividerWidth;
}
else
{
//LayoutParams layoutParams = ( ( LayoutParams ) ( child.LayoutParameters ) );
right = child.Right /* + layoutParams.RightMargin*/;
}
DrawVerticalDivider(canvas, right);
}
}
private void DrawHorizontalDivider(Canvas canvas, int top)
{
divider.SetBounds(PaddingLeft + dividerPadding, top, Width - PaddingRight - dividerPadding, top + dividerHeight);
divider.Draw(canvas);
}
private void DrawVerticalDivider(Canvas canvas, int left)
{
divider.SetBounds(left, PaddingTop + dividerPadding, left + dividerWidth, Height - PaddingBottom - dividerPadding);
divider.Draw(canvas);
}
private bool HasDividerBeforeChildAt(int childIndex)
{
if (childIndex == 0 || childIndex == ChildCount)
{
return false;
}
if ((showDividers & (int)ShowDividers.Middle) != 0)
{
var hasVisibleViewBefore = false;
for (var i = childIndex - 1; i >= 0; i--)
{
if (GetChildAt(i).Visibility == ViewStates.Gone)
{
continue;
}
hasVisibleViewBefore = true;
break;
}
return hasVisibleViewBefore;
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Diagnostics;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition.ReflectionModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.Hosting
{
public partial class CatalogExportProvider : ExportProvider, IDisposable
{
private class InnerCatalogExportProvider : ExportProvider
{
private CatalogExportProvider _outerExportProvider;
public InnerCatalogExportProvider(CatalogExportProvider outerExportProvider)
{
Assumes.NotNull(outerExportProvider);
_outerExportProvider = outerExportProvider;
}
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
return _outerExportProvider.InternalGetExportsCore(definition, atomicComposition);
}
}
private readonly CompositionLock _lock;
private Dictionary<ComposablePartDefinition, CatalogPart> _activatedParts = new Dictionary<ComposablePartDefinition, CatalogPart>();
private HashSet<ComposablePartDefinition> _rejectedParts = new HashSet<ComposablePartDefinition>();
private ConditionalWeakTable<object, List<ComposablePart>> _gcRoots;
private HashSet<IDisposable> _partsToDispose = new HashSet<IDisposable>();
private ComposablePartCatalog _catalog;
private volatile bool _isDisposed = false;
private volatile bool _isRunning = false;
private bool _disableSilentRejection = false;
private ExportProvider _sourceProvider;
private ImportEngine _importEngine;
private CompositionOptions _compositionOptions;
private ExportProvider _innerExportProvider;
/// <summary>
/// Initializes a new instance of the <see cref="CatalogExportProvider"/> class.
/// </summary>
/// <param name="catalog">
/// The <see cref="ComposablePartCatalog"/> that the <see cref="CatalogExportProvider"/>
/// uses to produce <see cref="Export"/> objects.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="catalog"/> is <see langword="null"/>.
/// </exception>
public CatalogExportProvider(ComposablePartCatalog catalog)
: this(catalog, CompositionOptions.Default)
{
}
public CatalogExportProvider(ComposablePartCatalog catalog, bool isThreadSafe)
: this(catalog, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default)
{
}
public CatalogExportProvider(ComposablePartCatalog catalog, CompositionOptions compositionOptions)
{
Requires.NotNull(catalog, nameof(catalog));
if (compositionOptions > (CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe | CompositionOptions.ExportCompositionService))
{
throw new ArgumentOutOfRangeException("compositionOptions");
}
_catalog = catalog;
_compositionOptions = compositionOptions;
var notifyCatalogChanged = _catalog as INotifyComposablePartCatalogChanged;
if (notifyCatalogChanged != null)
{
notifyCatalogChanged.Changing += OnCatalogChanging;
}
CompositionScopeDefinition scopeDefinition = _catalog as CompositionScopeDefinition;
if (scopeDefinition != null)
{
_innerExportProvider = new AggregateExportProvider(new ScopeManager(this, scopeDefinition), new InnerCatalogExportProvider(this));
}
else
{
_innerExportProvider = new InnerCatalogExportProvider(this);
}
_lock = new CompositionLock(compositionOptions.HasFlag(CompositionOptions.IsThreadSafe));
_disableSilentRejection = compositionOptions.HasFlag(CompositionOptions.DisableSilentRejection);
}
/// <summary>
/// Gets the composable part catalog that the provider users to
/// produce exports.
/// </summary>
/// <value>
/// The <see cref="ComposablePartCatalog"/> that the
/// <see cref="CatalogExportProvider"/>
/// uses to produce <see cref="Export"/> objects.
/// </value>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CompositionContainer"/> has been disposed of.
/// </exception>
public ComposablePartCatalog Catalog
{
get
{
ThrowIfDisposed();
Contract.Ensures(Contract.Result<ComposablePartCatalog>() != null);
return _catalog;
}
}
/// <summary>
/// Gets the export provider which provides the provider access to additional
/// exports.
/// </summary>
/// <value>
/// The <see cref="ExportProvider"/> which provides the
/// <see cref="CatalogExportProvider"/> access to additional
/// <see cref="Export"/> objects. The default is <see langword="null"/>.
/// </value>
/// <exception cref="ArgumentNullException">
/// <paramref name="value"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// This property has already been set.
/// <para>
/// -or-
/// </para>
/// The methods on the <see cref="CatalogExportProvider"/>
/// have already been accessed.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="CatalogExportProvider"/> has been disposed of.
/// </exception>
/// <remarks>
/// This property must be set before accessing any methods on the
/// <see cref="CatalogExportProvider"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "EnsureCanSet ensures that the property is set only once, Dispose is not required")]
public ExportProvider SourceProvider
{
get
{
ThrowIfDisposed();
using (_lock.LockStateForRead())
{
return _sourceProvider;
}
}
set
{
ThrowIfDisposed();
Requires.NotNull(value, nameof(value));
ImportEngine newImportEngine = null;
AggregateExportProvider aggregateExportProvider = null;
ExportProvider sourceProvider = value;
bool isThrowing = true;
try
{
newImportEngine = new ImportEngine(sourceProvider, _compositionOptions);
sourceProvider.ExportsChanging += OnExportsChangingInternal;
using (_lock.LockStateForWrite())
{
EnsureCanSet(_sourceProvider);
_sourceProvider = sourceProvider;
_importEngine = newImportEngine;
isThrowing = false;
}
}
finally
{
if (isThrowing)
{
sourceProvider.ExportsChanging -= OnExportsChangingInternal;
newImportEngine.Dispose();
if (aggregateExportProvider != null)
{
aggregateExportProvider.Dispose();
}
}
}
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
public void 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 (disposing)
{
if (!_isDisposed)
{
//Note: We do not dispose _lock on dispose because DisposePart needs it to check isDisposed state
// to eliminate race conditions between it and Dispose
INotifyComposablePartCatalogChanged catalogToUnsubscribeFrom = null;
HashSet<IDisposable> partsToDispose = null;
ImportEngine importEngine = null;
ExportProvider sourceProvider = null;
AggregateExportProvider aggregateExportProvider = null;
try
{
using (_lock.LockStateForWrite())
{
if (!_isDisposed)
{
catalogToUnsubscribeFrom = _catalog as INotifyComposablePartCatalogChanged;
_catalog = null;
aggregateExportProvider = _innerExportProvider as AggregateExportProvider;
_innerExportProvider = null;
sourceProvider = _sourceProvider;
_sourceProvider = null;
importEngine = _importEngine;
_importEngine = null;
partsToDispose = _partsToDispose;
_gcRoots = null;
_isDisposed = true;
}
}
}
finally
{
if (catalogToUnsubscribeFrom != null)
{
catalogToUnsubscribeFrom.Changing -= OnCatalogChanging;
}
if (aggregateExportProvider != null)
{
aggregateExportProvider.Dispose();
}
if (sourceProvider != null)
{
sourceProvider.ExportsChanging -= OnExportsChangingInternal;
}
if (importEngine != null)
{
importEngine.Dispose();
}
if (partsToDispose != null)
{
foreach (var part in partsToDispose)
{
part.Dispose();
}
}
}
}
}
}
/// <summary>
/// Returns all exports that match the conditions of the specified import.
/// </summary>
/// <param name="definition">The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="Export"/> to get.</param>
/// <returns></returns>
/// <result>
/// An <see cref="IEnumerable{T}"/> of <see cref="Export"/> objects that match
/// the conditions defined by <see cref="ImportDefinition"/>, if found; otherwise, an
/// empty <see cref="IEnumerable{T}"/>.
/// </result>
/// <remarks>
/// <note type="inheritinfo">
/// The implementers should not treat the cardinality-related mismatches as errors, and are not
/// expected to throw exceptions in those cases.
/// For instance, if the import requests exactly one export and the provider has no matching exports or more than one,
/// it should return an empty <see cref="IEnumerable{T}"/> of <see cref="Export"/>.
/// </note>
/// </remarks>
protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
Assumes.NotNull(_innerExportProvider);
IEnumerable<Export> exports;
_innerExportProvider.TryGetExports(definition, atomicComposition, out exports);
return exports;
}
private IEnumerable<Export> InternalGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
// Use the version of the catalog appropriate to this atomicComposition
ComposablePartCatalog currentCatalog = atomicComposition.GetValueAllowNull(_catalog);
IPartCreatorImportDefinition partCreatorDefinition = definition as IPartCreatorImportDefinition;
bool isExportFactory = false;
if (partCreatorDefinition != null)
{
definition = partCreatorDefinition.ProductImportDefinition;
isExportFactory = true;
}
CreationPolicy importPolicy = definition.GetRequiredCreationPolicy();
List<Export> exports = new List<Export>();
bool ensureRejection = EnsureRejection(atomicComposition);
foreach (var partDefinitionAndExportDefinition in currentCatalog.GetExports(definition))
{
bool isPartRejected = ensureRejection && IsRejected(partDefinitionAndExportDefinition.Item1, atomicComposition);
if (!isPartRejected)
{
exports.Add(CreateExport(partDefinitionAndExportDefinition.Item1, partDefinitionAndExportDefinition.Item2, isExportFactory, importPolicy));
}
}
return exports;
}
private Export CreateExport(ComposablePartDefinition partDefinition, ExportDefinition exportDefinition, bool isExportFactory, CreationPolicy importPolicy)
{
if (isExportFactory)
{
return new PartCreatorExport(this,
partDefinition,
exportDefinition);
}
else
{
return CatalogExport.CreateExport(this,
partDefinition,
exportDefinition,
importPolicy);
}
}
private void OnExportsChangingInternal(object sender, ExportsChangeEventArgs e)
{
UpdateRejections(e.AddedExports.Concat(e.RemovedExports), e.AtomicComposition);
}
private static ExportDefinition[] GetExportsFromPartDefinitions(IEnumerable<ComposablePartDefinition> partDefinitions)
{
List<ExportDefinition> exports = new List<ExportDefinition>();
foreach (var partDefinition in partDefinitions)
{
foreach (var export in partDefinition.ExportDefinitions)
{
exports.Add(export);
// While creating a PartCreatorExportDefinition for every changed definition may not be the most
// efficient way to do this the PartCreatorExportDefinition is very efficient and doesn't do any
// real work unless its metadata is pulled on. If this turns out to be a bottleneck then we
// will need to start tracking all the PartCreator's we hand out and only send those which we
// have handed out. In fact we could do the same thing for all the Exports if we wished but
// that requires a cache management which we don't want to do at this point.
exports.Add(new PartCreatorExportDefinition(export));
}
}
return exports.ToArray();
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private void OnCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e)
{
using (var atomicComposition = new AtomicComposition(e.AtomicComposition))
{
// Save the preview catalog to use in place of the original while handling
// this event
atomicComposition.SetValue(_catalog,
new CatalogChangeProxy(_catalog, e.AddedDefinitions, e.RemovedDefinitions));
IEnumerable<ExportDefinition> addedExports = GetExportsFromPartDefinitions(e.AddedDefinitions);
IEnumerable<ExportDefinition> removedExports = GetExportsFromPartDefinitions(e.RemovedDefinitions);
// Remove any parts based on eliminated definitions (in a atomicComposition-friendly
// fashion)
foreach (var definition in e.RemovedDefinitions)
{
CatalogPart removedPart = null;
bool removed = false;
using (_lock.LockStateForRead())
{
removed = _activatedParts.TryGetValue(definition, out removedPart);
}
if (removed)
{
var capturedDefinition = definition;
DisposePart(null, removedPart, atomicComposition);
atomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
{
_activatedParts.Remove(capturedDefinition);
}
});
}
}
UpdateRejections(addedExports.ConcatAllowingNull(removedExports), atomicComposition);
OnExportsChanging(
new ExportsChangeEventArgs(addedExports, removedExports, atomicComposition));
atomicComposition.AddCompleteAction(() => OnExportsChanged(
new ExportsChangeEventArgs(addedExports, removedExports, null)));
atomicComposition.Complete();
}
}
private CatalogPart GetComposablePart(ComposablePartDefinition partDefinition, bool isSharedPart)
{
ThrowIfDisposed();
EnsureRunning();
CatalogPart catalogPart = null;
if (isSharedPart)
{
catalogPart = GetSharedPart(partDefinition);
}
else
{
ComposablePart part = partDefinition.CreatePart();
catalogPart = new CatalogPart(part);
IDisposable disposablePart = part as IDisposable;
if (disposablePart != null)
{
using (_lock.LockStateForWrite())
{
_partsToDispose.Add(disposablePart);
}
}
}
return catalogPart;
}
private CatalogPart GetSharedPart(ComposablePartDefinition partDefinition)
{
CatalogPart catalogPart = null;
// look up the part
using (_lock.LockStateForRead())
{
if (_activatedParts.TryGetValue(partDefinition, out catalogPart))
{
return catalogPart;
}
}
// create a part outside of the lock
ComposablePart newPart = partDefinition.CreatePart();
IDisposable disposableNewPart = newPart as IDisposable;
using (_lock.LockStateForWrite())
{
// check if the part is still not there
if (!_activatedParts.TryGetValue(partDefinition, out catalogPart))
{
catalogPart = new CatalogPart(newPart);
_activatedParts.Add(partDefinition, catalogPart);
if (disposableNewPart != null)
{
_partsToDispose.Add(disposableNewPart);
}
// indiacate the the part has been added
newPart = null;
disposableNewPart = null;
}
}
// if disposableNewPart != null, this means we have created a new instance of something disposable and not used it
// Dispose of it now
if (disposableNewPart != null)
{
disposableNewPart.Dispose();
}
return catalogPart;
}
private object GetExportedValue(CatalogPart part, ExportDefinition export, bool isSharedPart)
{
ThrowIfDisposed();
EnsureRunning();
Assumes.NotNull(part, export);
// We don't protect against thread racing here, as "importsSatisfied" is merely an optimization
// if two threads satisfy imports twice, the results is the same, just the perf hit is heavier.
bool importsSatisfied = part.ImportsSatisfied;
ImportEngine importEngine = importsSatisfied ? null : _importEngine;
object exportedValue = CompositionServices.GetExportedValueFromComposedPart(
importEngine, part.Part, export);
if (!importsSatisfied)
{
// and set "ImportsSatisfied" to true
part.ImportsSatisfied = true;
}
// Only hold conditional references for recomposable non-shared parts because we are
// already holding strong references to the shared parts.
if (exportedValue != null && !isSharedPart && part.Part.IsRecomposable())
{
PreventPartCollection(exportedValue, part.Part);
}
return exportedValue;
}
private void ReleasePart(object exportedValue, CatalogPart catalogPart, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
EnsureRunning();
DisposePart(exportedValue, catalogPart, atomicComposition);
}
private void DisposePart(object exportedValue, CatalogPart catalogPart, AtomicComposition atomicComposition)
{
Assumes.NotNull(catalogPart);
if (_isDisposed)
return;
ImportEngine importEngine = null;
using (_lock.LockStateForWrite())
{
if (_isDisposed)
return;
importEngine = _importEngine;
}
if (importEngine != null)
{
importEngine.ReleaseImports(catalogPart.Part, atomicComposition);
}
if (exportedValue != null)
{
atomicComposition.AddCompleteActionAllowNull(() =>
{
AllowPartCollection(exportedValue);
});
}
IDisposable diposablePart = catalogPart.Part as IDisposable;
if (diposablePart != null)
{
atomicComposition.AddCompleteActionAllowNull(() =>
{
bool removed = false;
if (_isDisposed)
return;
using (_lock.LockStateForWrite())
{
if (_isDisposed)
return;
removed = _partsToDispose.Remove(diposablePart);
}
if (removed)
{
diposablePart.Dispose();
}
});
}
}
private void PreventPartCollection(object exportedValue, ComposablePart part)
{
Assumes.NotNull(exportedValue, part);
using (_lock.LockStateForWrite())
{
List<ComposablePart> partList;
ConditionalWeakTable<object, List<ComposablePart>> gcRoots = _gcRoots;
if (gcRoots == null)
{
gcRoots = new ConditionalWeakTable<object, List<ComposablePart>>();
}
if (!gcRoots.TryGetValue(exportedValue, out partList))
{
partList = new List<ComposablePart>();
gcRoots.Add(exportedValue, partList);
}
partList.Add(part);
if (_gcRoots == null)
{
Thread.MemoryBarrier();
_gcRoots = gcRoots;
}
}
}
private void AllowPartCollection(object gcRoot)
{
if (_gcRoots != null)
{
using (_lock.LockStateForWrite())
{
_gcRoots.Remove(gcRoot);
}
}
}
private bool IsRejected(ComposablePartDefinition definition, AtomicComposition atomicComposition)
{
// Check to see if we're currently working on the definition in question.
// Recursive queries always answer optimistically, as if the definition hasn't
// been rejected - because if it is we can discard all decisions that were based
// on the faulty assumption in the first place.
var forceRejectionTest = false;
if (atomicComposition != null)
{
AtomicCompositionQueryState state = QueryPartState(atomicComposition, definition);
switch (state)
{
case AtomicCompositionQueryState.TreatAsRejected:
return true;
case AtomicCompositionQueryState.TreatAsValidated:
return false;
case AtomicCompositionQueryState.NeedsTesting:
forceRejectionTest = true;
break;
default:
Assumes.IsTrue(state == AtomicCompositionQueryState.Unknown);
// Need to do the work to determine the state
break;
}
}
if (!forceRejectionTest)
{
// Next, anything that has been activated is not rejected
using (_lock.LockStateForRead())
{
if (_activatedParts.ContainsKey(definition))
{
return false;
}
// Last stop before doing the hard work: check a specific registry of rejected parts
if (_rejectedParts.Contains(definition))
{
return true;
}
}
}
// Determine whether or not the definition's imports can be satisfied
return DetermineRejection(definition, atomicComposition);
}
private bool EnsureRejection(AtomicComposition atomicComposition)
{
return !(_disableSilentRejection && (atomicComposition == null));
}
private bool DetermineRejection(ComposablePartDefinition definition, AtomicComposition parentAtomicComposition)
{
ChangeRejectedException exception = null;
// if there is no active atomic composition and rejection is disabled, there's no need to do any of the below
if (!EnsureRejection(parentAtomicComposition))
{
return false;
}
using (var localAtomicComposition = new AtomicComposition(parentAtomicComposition))
{
// The part definition we're currently working on is treated optimistically
// as if we know it hasn't been rejected. This handles recursion, and if we
// later decide that it has been rejected we'll discard all nested progress so
// all side-effects of the mistake are erased.
//
// Note that this means that recursive failures that would be detected by the
// import engine are not discovered by rejection currently. Loops among
// prerequisites, runaway import chains involving factories, and prerequisites
// that cannot be fully satisfied still result in runtime errors. Doing
// otherwise would be possible but potentially expensive - and could be a v2
// improvement if deemed worthwhile.
UpdateAtomicCompositionQueryForPartEquals(localAtomicComposition,
definition, AtomicCompositionQueryState.TreatAsValidated);
var newPart = definition.CreatePart();
try
{
_importEngine.PreviewImports(newPart, localAtomicComposition);
// Reuse the partially-fleshed out part the next time we need a shared
// instance to keep the expense of pre-validation to a minimum. Note that
// _activatedParts holds references to both shared and non-shared parts.
// The non-shared parts will only be used for rejection purposes only but
// the shared parts will be handed out when requested via GetExports as
// well as be used for rejection purposes.
localAtomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
{
if (!_activatedParts.ContainsKey(definition))
{
_activatedParts.Add(definition, new CatalogPart(newPart));
IDisposable newDisposablePart = newPart as IDisposable;
if (newDisposablePart != null)
{
_partsToDispose.Add(newDisposablePart);
}
}
}
});
// Success! Complete any recursive work that was conditioned on this part's validation
localAtomicComposition.Complete();
return false;
}
catch (ChangeRejectedException ex)
{
exception = ex;
}
}
// If we've reached this point then this part has been rejected so we need to
// record the rejection in our parent composition or execute it immediately if
// one doesn't exist.
parentAtomicComposition.AddCompleteActionAllowNull(() =>
{
using (_lock.LockStateForWrite())
{
_rejectedParts.Add(definition);
}
CompositionTrace.PartDefinitionRejected(definition, exception);
});
if (parentAtomicComposition != null)
{
UpdateAtomicCompositionQueryForPartEquals(parentAtomicComposition,
definition, AtomicCompositionQueryState.TreatAsRejected);
}
return true;
}
private void UpdateRejections(IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition)
{
using (var localAtomicComposition = new AtomicComposition(atomicComposition))
{
// Reconsider every part definition that has been previously
// rejected to see if any of them can be added back.
var affectedRejections = new HashSet<ComposablePartDefinition>();
ComposablePartDefinition[] rejectedParts;
using (_lock.LockStateForRead())
{
rejectedParts = _rejectedParts.ToArray();
}
foreach (var definition in rejectedParts)
{
if (QueryPartState(localAtomicComposition, definition) == AtomicCompositionQueryState.TreatAsValidated)
{
continue;
}
foreach (var import in definition.ImportDefinitions.Where(ImportEngine.IsRequiredImportForPreview))
{
if (changedExports.Any(export => import.IsConstraintSatisfiedBy(export)))
{
affectedRejections.Add(definition);
break;
}
}
}
UpdateAtomicCompositionQueryForPartInHashSet(localAtomicComposition,
affectedRejections, AtomicCompositionQueryState.NeedsTesting);
// Determine if any of the resurrectable parts is now available so that we can
// notify listeners of the exact changes to exports
var resurrectedExports = new List<ExportDefinition>();
foreach (var partDefinition in affectedRejections)
{
if (!IsRejected(partDefinition, localAtomicComposition))
{
// Notify listeners of the newly available exports and
// prepare to remove the rejected part from the list of rejections
resurrectedExports.AddRange(partDefinition.ExportDefinitions);
// Capture the local so that the closure below refers to the current definition
// in the loop and not the value of 'partDefinition' when the closure executes
var capturedPartDefinition = partDefinition;
localAtomicComposition.AddCompleteAction(() =>
{
using (_lock.LockStateForWrite())
{
_rejectedParts.Remove(capturedPartDefinition);
}
CompositionTrace.PartDefinitionResurrected(capturedPartDefinition);
});
}
}
// Notify anyone sourcing exports that the resurrected exports have appeared
if (resurrectedExports.Any())
{
OnExportsChanging(
new ExportsChangeEventArgs(resurrectedExports, new ExportDefinition[0], localAtomicComposition));
localAtomicComposition.AddCompleteAction(() => OnExportsChanged(
new ExportsChangeEventArgs(resurrectedExports, new ExportDefinition[0], null)));
}
localAtomicComposition.Complete();
}
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
/// <summary>
/// EnsureCanRun must be called from within a lock.
/// </summary>
[DebuggerStepThrough]
private void EnsureCanRun()
{
if ((_sourceProvider == null) || (_importEngine == null))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
}
}
[DebuggerStepThrough]
private void EnsureRunning()
{
if (!_isRunning)
{
using (_lock.LockStateForWrite())
{
if (!_isRunning)
{
EnsureCanRun();
_isRunning = true;
}
}
}
}
/// <summary>
/// EnsureCanSet<T> must be called from within a lock.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="currentValue"></param>
[DebuggerStepThrough]
private void EnsureCanSet<T>(T currentValue)
where T : class
{
if ((_isRunning) || (currentValue != null))
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectAlreadyInitialized));
}
}
private AtomicCompositionQueryState QueryPartState(AtomicComposition atomicComposition, ComposablePartDefinition definition)
{
PartQueryStateNode node = GetPartQueryStateNode(atomicComposition);
if (node == null)
{
return AtomicCompositionQueryState.Unknown;
}
else
{
return node.GetQueryState(definition);
}
}
private PartQueryStateNode GetPartQueryStateNode(AtomicComposition atomicComposition)
{
PartQueryStateNode node;
atomicComposition.TryGetValue(this, out node);
return node;
}
private void UpdateAtomicCompositionQueryForPartEquals(
AtomicComposition atomicComposition,
ComposablePartDefinition part,
AtomicCompositionQueryState state)
{
PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition);
atomicComposition.SetValue(this, new PartEqualsQueryStateNode(part, previousNode, state));
}
private void UpdateAtomicCompositionQueryForPartInHashSet(
AtomicComposition atomicComposition,
HashSet<ComposablePartDefinition> hashset,
AtomicCompositionQueryState state)
{
PartQueryStateNode previousNode = GetPartQueryStateNode(atomicComposition);
atomicComposition.SetValue(this, new PartInHashSetQueryStateNode(hashset, previousNode, state));
}
private enum AtomicCompositionQueryState
{
Unknown,
TreatAsRejected,
TreatAsValidated,
NeedsTesting
};
private abstract class PartQueryStateNode
{
private readonly PartQueryStateNode _previousNode;
private readonly AtomicCompositionQueryState _state;
protected PartQueryStateNode(PartQueryStateNode previousNode, AtomicCompositionQueryState state)
{
_previousNode = previousNode;
_state = state;
}
protected abstract bool IsMatchingDefinition(ComposablePartDefinition part, int partHashCode);
public AtomicCompositionQueryState GetQueryState(ComposablePartDefinition definition)
{
int hashCode = definition.GetHashCode();
PartQueryStateNode node = this;
do
{
if (node.IsMatchingDefinition(definition, hashCode))
{
return node._state;
}
node = node._previousNode;
}
while (node != null);
return AtomicCompositionQueryState.Unknown;
}
}
private class PartEqualsQueryStateNode : PartQueryStateNode
{
private ComposablePartDefinition _part;
private int _hashCode;
public PartEqualsQueryStateNode(ComposablePartDefinition part, PartQueryStateNode previousNode, AtomicCompositionQueryState state) :
base(previousNode, state)
{
_part = part;
_hashCode = part.GetHashCode();
}
protected override bool IsMatchingDefinition(ComposablePartDefinition part, int partHashCode)
{
if (partHashCode != _hashCode)
{
return false;
}
return _part.Equals(part);
}
}
private class PartInHashSetQueryStateNode : PartQueryStateNode
{
private HashSet<ComposablePartDefinition> _parts;
public PartInHashSetQueryStateNode(HashSet<ComposablePartDefinition> parts, PartQueryStateNode previousNode, AtomicCompositionQueryState state) :
base(previousNode, state)
{
_parts = parts;
}
protected override bool IsMatchingDefinition(ComposablePartDefinition part, int partHashCode)
{
return _parts.Contains(part);
}
}
private class CatalogPart
{
private volatile bool _importsSatisfied = false;
public CatalogPart(ComposablePart part)
{
Part = part;
}
public ComposablePart Part { get; private set; }
public bool ImportsSatisfied
{
get
{
return _importsSatisfied;
}
set
{
_importsSatisfied = value;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Pchp.Core;
using Pchp.Core.Utilities;
namespace Peachpie.Runtime.Tests
{
[TestClass]
public class OrderedDictionaryTest
{
//static string ToString(OrderedDictionary array) => string.Join("", array.Select(entry => entry.Item2));
static string ToString(OrderedDictionary array)
{
var result = new StringBuilder();
foreach (var value in array) // uses FastEnumerator
{
Debug.Assert(value.Value.String != null); // only string values for the test
result.Append(value.Value.String);
}
return result.ToString();
}
[TestMethod]
public void Test1()
{
var array = new OrderedDictionary();
Assert.AreEqual(0, array.Count);
array.Add("Hello");
array.Add(" ");
array.Add("World");
Assert.AreEqual(3, array.Count);
Assert.AreEqual("Hello World", ToString(array));
Assert.AreEqual("Hello", array[0]);
Assert.AreEqual("World", array[2]);
array.Remove(1);
Assert.AreEqual(2, array.Count);
Assert.AreEqual("HelloWorld", ToString(array));
Assert.AreEqual("World", array[2]);
array.Add("!");
Assert.AreEqual(3, array.Count);
Assert.AreEqual("HelloWorld!", ToString(array));
Assert.AreEqual("!", array[3]);
Assert.IsTrue(array.ContainsKey(0));
Assert.IsFalse(array.ContainsKey(1));
}
[TestMethod]
public void Test2()
{
var array = new OrderedDictionary(100000);
const int count = 1000000;
for (int i = count; i > 0; i--)
{
array[i] = i.ToString("x4");
}
Assert.AreEqual(count, array.Count);
int removed = 0;
for (int i = 1; i < count; i += 3)
{
Assert.IsTrue(array.Remove(i));
removed++;
}
Assert.AreEqual(count - removed, array.Count);
}
[TestMethod]
public void TestPacked()
{
var array = new OrderedDictionary(100000);
Assert.IsTrue(array.IsPacked);
const int count = 1000000;
for (int i = 0; i < count; i++)
{
array[i] = i.ToString("x4");
}
Assert.IsTrue(array.IsPacked);
Assert.AreEqual(count, array.Count);
for (int i = count - 1; i >= 0; i--)
{
Assert.IsTrue(array.Remove(i));
Assert.IsTrue(array.IsPacked);
}
Assert.AreEqual(0, array.Count);
Assert.AreEqual("", ToString(array)); // enumeration of empty array works
for (int i = 0; i < count; i++)
{
array[i] = i.ToString("x4");
}
Assert.IsTrue(array.IsPacked);
array.Add("last");
Assert.IsTrue(array.IsPacked);
Assert.AreEqual(count + 1, array.Count);
Assert.IsTrue(array.ContainsKey(count));
Assert.AreEqual("last", array[count]);
}
[TestMethod]
public void TestShuffle()
{
// create array and check shuffle
var array = new OrderedDictionary();
const int count = 123;
for (int i = 0; i < count; i++)
{
array.Add(i.ToString("x4"));
}
array.Remove(44);
array.Remove(45);
array.Remove(46);
array.Remove(0);
array.Shuffle(new Random());
var set = new HashSet<long>();
foreach (var pair in array)
{
Assert.IsTrue(set.Add(pair.Key.Integer));
}
Assert.AreEqual(array.Count, set.Count);
}
[TestMethod]
public void TestReverse()
{
var array = new OrderedDictionary();
const int count = 11;
for (int i = 0; i < count; i++)
{
array.Add(i.ToString("x4"));
}
// reverse reverse -> must result in the same array as before
var before = ToString(array);
array.Reverse();
array.Reverse();
Assert.AreEqual(before, ToString(array));
// expected count
Assert.AreEqual(count, array.Count);
// remove items and reverse array with holes:
Assert.IsTrue(array.Remove(3));
Assert.IsTrue(array.Remove(4));
Assert.IsTrue(array.Remove(7));
array.Reverse();
var last = new KeyValuePair<IntStringKey, PhpValue>(int.MaxValue, default);
foreach (var pair in array)
{
Assert.IsTrue(last.Key.Integer > pair.Key.Integer);
Assert.AreEqual(pair.Value.String, pair.Key.Integer.ToString("x4"));
last = pair;
}
}
class KeyComparer : IComparer<KeyValuePair<IntStringKey, PhpValue>>
{
public int Compare(KeyValuePair<IntStringKey, PhpValue> x, KeyValuePair<IntStringKey, PhpValue> y)
{
return x.Key.Integer.CompareTo(y.Key.Integer);
}
}
class ValueComparer : IComparer<KeyValuePair<IntStringKey, PhpValue>>
{
public int Compare(KeyValuePair<IntStringKey, PhpValue> x, KeyValuePair<IntStringKey, PhpValue> y)
{
return StringComparer.OrdinalIgnoreCase.Compare(x.Value.String, y.Value.String);
}
}
[TestMethod]
public void TestSort()
{
var array = new OrderedDictionary();
const int count = 10;
for (int i = count; i > 0; i--)
{
array[i] = i.ToString();
}
// remove items and reverse array with holes:
Assert.IsTrue(array.Remove(3));
Assert.IsTrue(array.Remove(4));
Assert.IsTrue(array.Remove(7));
array.Sort(new KeyComparer());
Assert.AreEqual(count - 3, array.Count);
var last = new KeyValuePair<IntStringKey, PhpValue>(0, default);
foreach (var pair in array)
{
Assert.IsTrue(last.Key.Integer < pair.Key.Integer);
Assert.AreEqual(pair.Value.String, pair.Key.Integer.ToString());
last = pair;
}
}
[TestMethod]
public void TestDiff()
{
var array = new OrderedDictionary();
const int count = 100;
for (int i = 0; i < count; i++)
{
array[i] = i.ToString();
}
array.Shuffle(new Random());
var array2 = new OrderedDictionary();
array2.Add("3");
array2.Add("4");
array2.Add("7");
var diff = array.SetOperation(SetOperations.Difference, new[] { new PhpArray(array2) }, new ValueComparer());
Assert.AreEqual(array.Count - array2.Count, diff.Count);
var diff_diff = array.SetOperation(SetOperations.Difference, new[] { new PhpArray(diff) }, new ValueComparer());
Assert.AreEqual(diff_diff.Count, array2.Count);
}
[TestMethod]
public void TestPrepend()
{
var array = new OrderedDictionary();
array[0] = "0";
array[1] = "1";
array.AddFirst(-1, "-1");
array.AddFirst(-2, "-2");
Assert.AreEqual(4, array.Count);
Assert.AreEqual("-2-101", ToString(array));
}
[TestMethod]
public void TestUtils()
{
var array = new PhpArray()
{
{ 1, "Hello" },
{ 2, "World" },
{ 3, "!" },
};
// array of values
var values = array.ValuesToArray(value => value.ToString());
Assert.IsInstanceOfType(values, typeof(string[]));
Assert.AreEqual("!", values[2]);
Assert.AreEqual(3, values.Length);
// empty array of values
Assert.AreSame(new PhpArray().ValuesToArray(value => value), Array.Empty<PhpValue>());
// dictionary
var dict = array.ToDictionary(key => key.ToString(), value => value.ToClr());
Assert.IsInstanceOfType(dict, typeof(Dictionary<string, object>));
Assert.IsTrue(dict.ContainsKey("3"));
}
}
}
| |
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 ExampleWebApi.Areas.HelpPage.ModelDescriptions;
using ExampleWebApi.Areas.HelpPage.Models;
namespace ExampleWebApi.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);
}
}
}
}
| |
using System;
using Foundation;
using ObjCRuntime;
using UIKit;
namespace MonoTouch.Mixpanel
{
// @interface Mixpanel : NSObject
[BaseType (typeof(NSObject))]
interface Mixpanel
{
// @property (readonly, atomic, strong) MixpanelPeople * people;
[Export ("people", ArgumentSemantic.Strong)]
MixpanelPeople People { get; }
// @property (readonly, copy, atomic) NSString * distinctId;
[Export ("distinctId")]
string DistinctId { get; }
// @property (copy, atomic) NSString * nameTag;
[Export ("nameTag")]
string NameTag { get; set; }
// @property (copy, atomic) NSString * serverURL;
[Export ("serverURL")]
string ServerURL { get; set; }
// @property (atomic) NSUInteger flushInterval;
[Export ("flushInterval")]
nuint FlushInterval { get; set; }
// @property (atomic) BOOL flushOnBackground;
[Export ("flushOnBackground")]
bool FlushOnBackground { get; set; }
// @property (atomic) BOOL showNetworkActivityIndicator;
[Export ("showNetworkActivityIndicator")]
bool ShowNetworkActivityIndicator { get; set; }
// @property (atomic) BOOL checkForSurveysOnActive;
[Export ("checkForSurveysOnActive")]
bool CheckForSurveysOnActive { get; set; }
// @property (atomic) BOOL showSurveyOnActive;
[Export ("showSurveyOnActive")]
bool ShowSurveyOnActive { get; set; }
// @property (atomic) BOOL checkForNotificationsOnActive;
[Export ("checkForNotificationsOnActive")]
bool CheckForNotificationsOnActive { get; set; }
// @property (atomic) BOOL checkForVariantsOnActive;
[Export ("checkForVariantsOnActive")]
bool CheckForVariantsOnActive { get; set; }
// @property (atomic) BOOL showNotificationOnActive;
[Export ("showNotificationOnActive")]
bool ShowNotificationOnActive { get; set; }
// @property (atomic) CGFloat miniNotificationPresentationTime;
[Export ("miniNotificationPresentationTime")]
nfloat MiniNotificationPresentationTime { get; set; }
// @property (atomic) UIColor * miniNotificationBackgroundColor;
[Export ("miniNotificationBackgroundColor", ArgumentSemantic.Assign)]
UIColor MiniNotificationBackgroundColor { get; set; }
[Wrap ("WeakDelegate")]
[NullAllowed]
MixpanelDelegate Delegate { get; set; }
// @property (atomic, weak) id<MixpanelDelegate> _Nullable delegate;
[NullAllowed, Export ("delegate", ArgumentSemantic.Weak)]
NSObject WeakDelegate { get; set; }
// +(Mixpanel *)sharedInstanceWithToken:(NSString *)apiToken;
[Static]
[Export ("sharedInstanceWithToken:")]
Mixpanel SharedInstanceWithToken (string apiToken);
// +(Mixpanel *)sharedInstanceWithToken:(NSString *)apiToken launchOptions:(NSDictionary *)launchOptions;
[Static]
[Export ("sharedInstanceWithToken:launchOptions:")]
Mixpanel SharedInstanceWithToken (string apiToken, NSDictionary launchOptions);
// +(Mixpanel *)sharedInstance;
[Static]
[Export ("sharedInstance")]
Mixpanel SharedInstance { get; }
// -(instancetype)initWithToken:(NSString *)apiToken launchOptions:(NSDictionary *)launchOptions andFlushInterval:(NSUInteger)flushInterval;
[Export ("initWithToken:launchOptions:andFlushInterval:")]
IntPtr Constructor (string apiToken, NSDictionary launchOptions, nuint flushInterval);
// -(instancetype)initWithToken:(NSString *)apiToken andFlushInterval:(NSUInteger)flushInterval;
[Export ("initWithToken:andFlushInterval:")]
IntPtr Constructor (string apiToken, nuint flushInterval);
// -(void)identify:(NSString *)distinctId;
[Export ("identify:")]
void Identify (string distinctId);
// -(void)track:(NSString *)event;
[Export ("track:")]
void Track (string @event);
// -(void)track:(NSString *)event properties:(NSDictionary *)properties;
[Export ("track:properties:")]
void Track (string @event, NSDictionary properties);
// -(void)trackPushNotification:(NSDictionary *)userInfo;
[Export ("trackPushNotification:")]
void TrackPushNotification (NSDictionary userInfo);
// -(void)registerSuperProperties:(NSDictionary *)properties;
[Export ("registerSuperProperties:")]
void RegisterSuperProperties (NSDictionary properties);
// -(void)registerSuperPropertiesOnce:(NSDictionary *)properties;
[Export ("registerSuperPropertiesOnce:")]
void RegisterSuperPropertiesOnce (NSDictionary properties);
// -(void)registerSuperPropertiesOnce:(NSDictionary *)properties defaultValue:(id)defaultValue;
[Export ("registerSuperPropertiesOnce:defaultValue:")]
void RegisterSuperPropertiesOnce (NSDictionary properties, NSObject defaultValue);
// -(void)unregisterSuperProperty:(NSString *)propertyName;
[Export ("unregisterSuperProperty:")]
void UnregisterSuperProperty (string propertyName);
// -(void)clearSuperProperties;
[Export ("clearSuperProperties")]
void ClearSuperProperties ();
// -(NSDictionary *)currentSuperProperties;
[Export ("currentSuperProperties")]
NSDictionary CurrentSuperProperties { get; }
// -(void)timeEvent:(NSString *)event;
[Export ("timeEvent:")]
void TimeEvent (string @event);
// -(void)clearTimedEvents;
[Export ("clearTimedEvents")]
void ClearTimedEvents ();
// -(void)reset;
[Export ("reset")]
void Reset ();
// -(void)flush;
[Export ("flush")]
void Flush ();
// -(void)flushWithCompletion:(void (^)())handler;
[Export ("flushWithCompletion:")]
void FlushWithCompletion (Action handler);
// -(void)archive;
[Export ("archive")]
void Archive ();
// -(void)createAlias:(NSString *)alias forDistinctID:(NSString *)distinctID;
[Export ("createAlias:forDistinctID:")]
void CreateAlias (string alias, string distinctID);
// -(NSString *)libVersion;
[Export ("libVersion")]
string LibVersion { get; }
// -(void)showSurveyWithID:(NSUInteger)ID;
[Export ("showSurveyWithID:")]
void ShowSurveyWithID (nuint ID);
// -(void)showSurvey;
[Export ("showSurvey")]
void ShowSurvey ();
// -(void)showNotificationWithID:(NSUInteger)ID;
[Export ("showNotificationWithID:")]
void ShowNotificationWithID (nuint ID);
// -(void)showNotificationWithType:(NSString *)type;
[Export ("showNotificationWithType:")]
void ShowNotificationWithType (string type);
// -(void)showNotification;
[Export ("showNotification")]
void ShowNotification ();
// -(void)joinExperiments;
[Export ("joinExperiments")]
void JoinExperiments ();
// -(void)joinExperimentsWithCallback:(void (^)())experimentsLoadedCallback;
[Export ("joinExperimentsWithCallback:")]
void JoinExperimentsWithCallback (Action experimentsLoadedCallback);
}
// @interface MixpanelPeople : NSObject
[BaseType (typeof(NSObject))]
interface MixpanelPeople
{
// -(void)addPushDeviceToken:(NSData *)deviceToken;
[Export ("addPushDeviceToken:")]
void AddPushDeviceToken (NSData deviceToken);
// -(void)set:(NSDictionary *)properties;
[Export ("set:")]
void Set (NSDictionary properties);
// -(void)set:(NSString *)property to:(id)object;
[Export ("set:to:")]
void Set (string property, NSObject @object);
// -(void)setOnce:(NSDictionary *)properties;
[Export ("setOnce:")]
void SetOnce (NSDictionary properties);
// -(void)increment:(NSDictionary *)properties;
[Export ("increment:")]
void Increment (NSDictionary properties);
// -(void)increment:(NSString *)property by:(NSNumber *)amount;
[Export ("increment:by:")]
void Increment (string property, NSNumber amount);
// -(void)append:(NSDictionary *)properties;
[Export ("append:")]
void Append (NSDictionary properties);
// -(void)union:(NSDictionary *)properties;
[Export ("union:")]
void Union (NSDictionary properties);
// -(void)trackCharge:(NSNumber *)amount;
[Export ("trackCharge:")]
void TrackCharge (NSNumber amount);
// -(void)trackCharge:(NSNumber *)amount withProperties:(NSDictionary *)properties;
[Export ("trackCharge:withProperties:")]
void TrackCharge (NSNumber amount, NSDictionary properties);
// -(void)clearCharges;
[Export ("clearCharges")]
void ClearCharges ();
// -(void)deleteUser;
[Export ("deleteUser")]
void DeleteUser ();
}
// @protocol MixpanelDelegate <NSObject>
[Protocol, Model]
[BaseType (typeof(NSObject))]
interface MixpanelDelegate
{
// @optional -(BOOL)mixpanelWillFlush:(Mixpanel *)mixpanel;
[Export ("mixpanelWillFlush:")]
bool MixpanelWillFlush (Mixpanel mixpanel);
}
[BaseType(typeof(NSObject))]
interface MPDesignerEventBindingRequestMesssage
{
[Field("MPDesignerEventBindingRequestMessageType", "__Internal")]
NSString RequestMessageType { get; }
}
[Protocol, Model]
[BaseType(typeof(NSObject))]
interface MPEventBinding
{
// -(NSString *)libVersion;
//[Export ("libVersion")]
// string LibVersion { get; }
}
[BaseType(typeof(NSObject))]
interface MPABTestDesignerConnection
{
// -(NSString *)libVersion;
//[Export ("libVersion")]
// string LibVersion { get; }
}
/*
Undefined symbols for architecture i386:
"_MPDesignerEventBindingRequestMessageType", referenced from:
-[MPABTestDesignerConnection initWithURL:keepTrying:connectCallback:disconnectCallback:] in libMixpanel.a(MPABTestDesignerConnection.o)
"_OBJC_CLASS_$_MPDesignerEventBindingRequestMessage", referenced from:
objc-class-ref in libMixpanel.a(MPABTestDesignerConnection.o)
"_OBJC_CLASS_$_MPDesignerTrackMessage", referenced from:
objc-class-ref in libMixpanel.a(Mixpanel.o)
"_OBJC_CLASS_$_MPEventBinding", referenced from:
objc-class-ref in libMixpanel.a(Mixpanel.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
MTOUCH: error MT5214: Native linking failed, undefined sy
*/
/*
public delegate void MixpanelSurveyCompletion(NSArray surveys);
[BaseType(typeof(NSObject))]
public partial interface Mixpanel
{
[Export("people", ArgumentSemantic.Retain)]
MixpanelPeople People { get; }
[Export("distinctId", ArgumentSemantic.Copy)]
string DistinctId { get; }
[Export("nameTag", ArgumentSemantic.Copy)]
string NameTag { get; set; }
[Export("serverURL", ArgumentSemantic.Copy)]
string ServerURL { get; set; }
[Export("flushInterval")]
uint FlushInterval { get; set; }
[Export("flushOnBackground")]
bool FlushOnBackground { get; set; }
[Export("showNetworkActivityIndicator")]
bool ShowNetworkActivityIndicator { get; set; }
[Export("checkForSurveysOnActive")]
bool CheckForSurveysOnActive { get; set; }
[Export("showSurveyOnActive")]
bool ShowSurveyOnActive { get; set; }
[Export("checkForNotificationsOnActive")]
bool CheckForNotificationsOnActive { get; set; }
[Export("checkForVariantsOnActive")]
bool CheckForVariantsOnActive { get; set; }
[Export("showNotificationOnActive")]
bool ShowNotificationOnActive { get; set; }
[Export("miniNotificationPresentationTime")]
float MiniNotificationPresentationTime { get; set; }
[Export("delegate", ArgumentSemantic.Assign)]
MixpanelDelegate Delegate { get; set; }
[Static, Export("sharedInstanceWithToken:")]
Mixpanel SharedInstanceWithToken(string apiToken);
[Static, Export("sharedInstanceWithToken:launchOptions:")]
Mixpanel SharedInstanceWithToken(string apiToken, NSDictionary launchOption);
[Static, Export("sharedInstance")]
Mixpanel SharedInstance { get; }
[Export("initWithToken:launchOptions:andFlushInterval:")]
IntPtr Constructor(string apiToken, NSDictionary launchOptions, uint flushInterval);
[Export("initWithToken:andFlushInterval:")]
IntPtr Constructor(string apiToken, uint flushInterval);
[Export("identify:")]
void Identify(string distinctId);
[Export("track:")]
void Track(string eventName);
[Export("track:properties:")]
void Track(string eventName, NSDictionary properties);
[Export("trackPushNotification:")]
void Track(NSDictionary userInfo);
[Export("registerSuperProperties:")]
void RegisterSuperProperties(NSDictionary properties);
[Export("registerSuperPropertiesOnce:")]
void RegisterSuperPropertiesOnce(NSDictionary properties);
[Export("registerSuperPropertiesOnce:defaultValue:")]
void RegisterSuperPropertiesOnce(NSDictionary properties, NSObject defaultValue);
[Export("unregisterSuperProperty:")]
void UnregisterSuperProperty(string propertyName);
[Export("clearSuperProperties")]
void ClearSuperProperties();
[Export("currentSuperProperties")]
NSDictionary CurrentSuperProperties { get; }
[Export("reset")]
void Reset();
[Export("flush")]
void Flush();
[Export("archive")]
void Archive();
[Export("showSurveyWithID:")]
void ShowSurveyWithID(uint ID);
[Export("showSurvey")]
void ShowSurvey();
[Export("showNotificationWithID:")]
void ShowNotificationWithID(uint ID);
[Export("showNotificationWithType:")]
void ShowNotificationWithType(string type);
[Export("showNotification")]
void ShowNotification();
[Export("joinExperiments")]
void JoinExperiments();
[Export("createAlias:forDistinctID:")]
void CreateAlias(string alias, string distinctID);
// LL: Added this for Tink
[Export("lla_checkForSurveysWithCompletion:")]
void LLACheckForSurveys(MixpanelSurveyCompletion completion);
[Export("lla_showSurveyWithObject:")]
void LLAShowSurvey(NSObject survey);
[Export("lla_markSurvey:shown:withAnswerCount:")]
void LLAMarkSurvey(NSObject survey, bool shown, int count);
}
[BaseType(typeof(NSObject))]
public partial interface MixpanelPeople
{
[Export("addPushDeviceToken:")]
void AddPushDeviceToken(NSData deviceToken);
[Export("set:")]
void Set(NSDictionary properties);
[Export("set:to:")]
void Set(string property, NSObject obj);
[Export("setOnce:")]
void SetOnce(NSDictionary properties);
[Export("increment:")]
void Increment(NSDictionary properties);
[Export("increment:by:")]
void Increment(string property, NSNumber amount);
[Export("append:")]
void Append(NSDictionary properties);
[Export("union:")]
void Union(NSDictionary properties);
[Export("trackCharge:")]
void TrackCharge(NSNumber amount);
[Export("trackCharge:withProperties:")]
void TrackCharge(NSNumber amount, NSDictionary properties);
[Export("clearCharges")]
void ClearCharges();
[Export("deleteUser")]
void DeleteUser();
}
[Model, BaseType(typeof(NSObject))]
public partial interface MixpanelDelegate
{
[Export("mixpanelWillFlush:")]
bool MixpanelWillFlush(Mixpanel mixpanel);
}
*/
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class MatrixCtl : System.Windows.Forms.UserControl, IProperty
{
private List<XmlNode> _ReportItems;
private DesignXmlDraw _Draw;
bool fDataSet, fPBBefore, fPBAfter, fNoRows, fCellDataElementOutput, fCellDataElementName;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ComboBox cbDataSet;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.CheckBox chkPBBefore;
private System.Windows.Forms.CheckBox chkPBAfter;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbNoRows;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.CheckBox chkCellContents;
private System.Windows.Forms.TextBox tbCellDataElementName;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal MatrixCtl(DesignXmlDraw dxDraw, List<XmlNode> ris)
{
_ReportItems = ris;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode riNode = _ReportItems[0];
tbNoRows.Text = _Draw.GetElementValue(riNode, "NoRows", "");
cbDataSet.Items.AddRange(_Draw.DataSetNames);
cbDataSet.Text = _Draw.GetDataSetNameValue(riNode);
if (_Draw.GetReportItemDataRegionContainer(riNode) != null)
cbDataSet.Enabled = false;
chkPBBefore.Checked = _Draw.GetElementValue(riNode, "PageBreakAtStart", "false").ToLower()=="true"? true:false;
chkPBAfter.Checked = _Draw.GetElementValue(riNode, "PageBreakAtEnd", "false").ToLower()=="true"? true:false;
this.chkCellContents.Checked = _Draw.GetElementValue(riNode, "CellDataElementOutput", "Output")=="Output"?true:false;
this.tbCellDataElementName.Text = _Draw.GetElementValue(riNode, "CellDataElementName", "Cell");
fNoRows = fDataSet = fPBBefore = fPBAfter = fCellDataElementOutput = fCellDataElementName = false;
}
/// <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 Component 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.label2 = new System.Windows.Forms.Label();
this.cbDataSet = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.chkPBAfter = new System.Windows.Forms.CheckBox();
this.chkPBBefore = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.tbNoRows = new System.Windows.Forms.TextBox();
this.tbCellDataElementName = new System.Windows.Forms.TextBox();
this.chkCellContents = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 23);
this.label2.TabIndex = 0;
this.label2.Text = "DataSet Name";
//
// cbDataSet
//
this.cbDataSet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDataSet.Location = new System.Drawing.Point(120, 16);
this.cbDataSet.Name = "cbDataSet";
this.cbDataSet.Size = new System.Drawing.Size(304, 21);
this.cbDataSet.TabIndex = 1;
this.cbDataSet.SelectedIndexChanged += new System.EventHandler(this.cbDataSet_SelectedIndexChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.chkPBAfter);
this.groupBox1.Controls.Add(this.chkPBBefore);
this.groupBox1.Location = new System.Drawing.Point(24, 88);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(400, 48);
this.groupBox1.TabIndex = 4;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Page Breaks";
//
// chkPBAfter
//
this.chkPBAfter.Location = new System.Drawing.Point(192, 16);
this.chkPBAfter.Name = "chkPBAfter";
this.chkPBAfter.Size = new System.Drawing.Size(128, 24);
this.chkPBAfter.TabIndex = 1;
this.chkPBAfter.Text = "Insert after Matrix";
this.chkPBAfter.CheckedChanged += new System.EventHandler(this.chkPBAfter_CheckedChanged);
//
// chkPBBefore
//
this.chkPBBefore.Location = new System.Drawing.Point(16, 16);
this.chkPBBefore.Name = "chkPBBefore";
this.chkPBBefore.Size = new System.Drawing.Size(128, 24);
this.chkPBBefore.TabIndex = 0;
this.chkPBBefore.Text = "Insert before Matrix";
this.chkPBBefore.CheckedChanged += new System.EventHandler(this.chkPBBefore_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 48);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 23);
this.label1.TabIndex = 2;
this.label1.Text = "No rows message";
//
// tbNoRows
//
this.tbNoRows.Location = new System.Drawing.Point(120, 48);
this.tbNoRows.Name = "tbNoRows";
this.tbNoRows.Size = new System.Drawing.Size(304, 20);
this.tbNoRows.TabIndex = 3;
this.tbNoRows.Text = "textBox1";
this.tbNoRows.TextChanged += new System.EventHandler(this.tbNoRows_TextChanged);
//
// tbCellDataElementName
//
this.tbCellDataElementName.Location = new System.Drawing.Point(133, 42);
this.tbCellDataElementName.Name = "tbCellDataElementName";
this.tbCellDataElementName.Size = new System.Drawing.Size(183, 20);
this.tbCellDataElementName.TabIndex = 0;
this.tbCellDataElementName.Text = "";
this.tbCellDataElementName.TextChanged += new System.EventHandler(this.tbCellDataElementName_TextChanged);
//
// chkCellContents
//
this.chkCellContents.Location = new System.Drawing.Point(16, 16);
this.chkCellContents.Name = "chkCellContents";
this.chkCellContents.Size = new System.Drawing.Size(160, 24);
this.chkCellContents.TabIndex = 0;
this.chkCellContents.Text = "Render cell contents";
this.chkCellContents.CheckedChanged += new System.EventHandler(this.chkCellContents_CheckedChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 48);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(112, 16);
this.label3.TabIndex = 1;
this.label3.Text = "Cell Element Name";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.tbCellDataElementName);
this.groupBox2.Controls.Add(this.chkCellContents);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Location = new System.Drawing.Point(24, 152);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(400, 72);
this.groupBox2.TabIndex = 5;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "XML";
//
// MatrixCtl
//
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.tbNoRows);
this.Controls.Add(this.label1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.cbDataSet);
this.Controls.Add(this.label2);
this.Name = "MatrixCtl";
this.Size = new System.Drawing.Size(472, 288);
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
foreach (XmlNode riNode in this._ReportItems)
ApplyChanges(riNode);
// No more changes
fNoRows = fDataSet = fPBBefore = fPBAfter= fCellDataElementOutput = fCellDataElementName = false;
}
public void ApplyChanges(XmlNode node)
{
if (fNoRows)
_Draw.SetElement(node, "NoRows", this.tbNoRows.Text);
if (fDataSet)
_Draw.SetElement(node, "DataSetName", this.cbDataSet.Text);
if (fPBBefore)
_Draw.SetElement(node, "PageBreakAtStart", this.chkPBBefore.Checked? "true":"false");
if (fPBAfter)
_Draw.SetElement(node, "PageBreakAtEnd", this.chkPBAfter.Checked? "true":"false");
if (fCellDataElementOutput)
_Draw.SetElement(node, "CellDataElementOutput", this.chkCellContents.Checked? "Output":"NoOutput");
if (fCellDataElementName)
{
if (this.tbCellDataElementName.Text.Length > 0)
_Draw.SetElement(node, "CellDataElementName", this.tbCellDataElementName.Text);
else
_Draw.RemoveElement(node, "CellDataElementName");
}
}
private void cbDataSet_SelectedIndexChanged(object sender, System.EventArgs e)
{
fDataSet = true;
}
private void chkPBBefore_CheckedChanged(object sender, System.EventArgs e)
{
fPBBefore = true;
}
private void chkPBAfter_CheckedChanged(object sender, System.EventArgs e)
{
fPBAfter = true;
}
private void tbNoRows_TextChanged(object sender, System.EventArgs e)
{
fNoRows = true;
}
private void tbCellDataElementName_TextChanged(object sender, System.EventArgs e)
{
fCellDataElementName = true;
}
private void chkCellContents_CheckedChanged(object sender, System.EventArgs e)
{
this.fCellDataElementOutput = true;
}
}
}
| |
/**
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using UnityEngine;
using UnityEditor;
using System;
using Rotorz.ReorderableList;
namespace Fungus
{
public class VariableListAdaptor : IReorderableListAdaptor {
protected SerializedProperty _arrayProperty;
public float fixedItemHeight;
public SerializedProperty this[int index] {
get { return _arrayProperty.GetArrayElementAtIndex(index); }
}
public SerializedProperty arrayProperty {
get { return _arrayProperty; }
}
public VariableListAdaptor(SerializedProperty arrayProperty, float fixedItemHeight) {
if (arrayProperty == null)
throw new ArgumentNullException("Array property was null.");
if (!arrayProperty.isArray)
throw new InvalidOperationException("Specified serialized propery is not an array.");
this._arrayProperty = arrayProperty;
this.fixedItemHeight = fixedItemHeight;
}
public VariableListAdaptor(SerializedProperty arrayProperty) : this(arrayProperty, 0f) {
}
public int Count {
get { return _arrayProperty.arraySize; }
}
public virtual bool CanDrag(int index) {
return true;
}
public virtual bool CanRemove(int index) {
return true;
}
public void Add() {
int newIndex = _arrayProperty.arraySize;
++_arrayProperty.arraySize;
_arrayProperty.GetArrayElementAtIndex(newIndex).ResetValue();
}
public void Insert(int index) {
_arrayProperty.InsertArrayElementAtIndex(index);
_arrayProperty.GetArrayElementAtIndex(index).ResetValue();
}
public void Duplicate(int index) {
_arrayProperty.InsertArrayElementAtIndex(index);
}
public void Remove(int index) {
// Remove the Fungus Variable component
Variable variable = _arrayProperty.GetArrayElementAtIndex(index).objectReferenceValue as Variable;
Undo.DestroyObjectImmediate(variable);
_arrayProperty.GetArrayElementAtIndex(index).objectReferenceValue = null;
_arrayProperty.DeleteArrayElementAtIndex(index);
}
public void Move(int sourceIndex, int destIndex) {
if (destIndex > sourceIndex)
--destIndex;
_arrayProperty.MoveArrayElement(sourceIndex, destIndex);
}
public void Clear() {
_arrayProperty.ClearArray();
}
public void BeginGUI()
{}
public void EndGUI()
{}
public virtual void DrawItemBackground(Rect position, int index) {
}
public void DrawItem(Rect position, int index)
{
Variable variable = this[index].objectReferenceValue as Variable;
if (variable == null)
{
return;
}
float[] widths = { 80, 100, 140, 60 };
Rect[] rects = new Rect[4];
for (int i = 0; i < 4; ++i)
{
rects[i] = position;
rects[i].width = widths[i] - 5;
for (int j = 0; j < i; ++j)
{
rects[i].x += widths[j];
}
}
VariableInfoAttribute variableInfo = VariableEditor.GetVariableInfo(variable.GetType());
if (variableInfo == null)
{
return;
}
Flowchart flowchart = FlowchartWindow.GetFlowchart();
if (flowchart == null)
{
return;
}
// Highlight if an active or selected command is referencing this variable
bool highlight = false;
if (flowchart.selectedBlock != null)
{
if (Application.isPlaying && flowchart.selectedBlock.IsExecuting())
{
highlight = flowchart.selectedBlock.activeCommand.HasReference(variable);
}
else if (!Application.isPlaying && flowchart.selectedCommands.Count > 0)
{
foreach (Command selectedCommand in flowchart.selectedCommands)
{
if (selectedCommand == null)
{
continue;
}
if (selectedCommand.HasReference(variable))
{
highlight = true;
break;
}
}
}
}
if (highlight)
{
GUI.backgroundColor = Color.green;
GUI.Box(position, "");
}
string key = variable.key;
VariableScope scope = variable.scope;
// To access properties in a monobehavior, you have to new a SerializedObject
// http://answers.unity3d.com/questions/629803/findrelativeproperty-never-worked-for-me-how-does.html
SerializedObject variableObject = new SerializedObject(this[index].objectReferenceValue);
variableObject.Update();
GUI.Label(rects[0], variableInfo.VariableType);
key = EditorGUI.TextField(rects[1], variable.key);
SerializedProperty keyProp = variableObject.FindProperty("key");
keyProp.stringValue = flowchart.GetUniqueVariableKey(key, variable);
SerializedProperty defaultProp = variableObject.FindProperty("value");
EditorGUI.PropertyField(rects[2], defaultProp, new GUIContent(""));
SerializedProperty scopeProp = variableObject.FindProperty("scope");
scope = (VariableScope)EditorGUI.EnumPopup(rects[3], variable.scope);
scopeProp.enumValueIndex = (int)scope;
variableObject.ApplyModifiedProperties();
GUI.backgroundColor = Color.white;
}
public virtual float GetItemHeight(int index) {
return fixedItemHeight != 0f
? fixedItemHeight
: EditorGUI.GetPropertyHeight(this[index], GUIContent.none, false)
;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Moyasar.Abstraction;
using Moyasar.Exceptions;
using Moyasar.Models;
using Moyasar.Services;
using MoyasarTest.Helpers;
using Xunit;
using BasicDict = System.Collections.Generic.Dictionary<string, object>;
namespace MoyasarTest
{
public class PaymentTest
{
[Fact(DisplayName = "Method must return with no exceptions thrown if data are valid")]
public void TestValidatePaymentInfo()
{
GetValidPaymentInfo().Validate();
GetValidPaymentInfo(GetValidApplePaySource()).Validate();
GetValidPaymentInfo(GetValidStcPaySource()).Validate();
}
[Fact]
public async void TestPaymentInfoValidationRules()
{
var info = GetValidPaymentInfo();
info.Validate();
info.Amount = -1;
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => info.Validate()));
info = GetValidPaymentInfo();
info.Validate();
info.Source = null;
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => info.Validate()));
info = GetValidPaymentInfo();
info.Validate();
info.CallbackUrl = "hey";
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => info.Validate()));
}
[Fact]
public async void TestCcSourceValidationRules()
{
var source = GetValidCcSource();
source.Validate();
source.Name = "";
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => source.Validate()));
source = GetValidCcSource();
source.Validate();
source.Number = "";
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => source.Validate()));
source = GetValidCcSource();
source.Validate();
source.Cvc = 0;
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => source.Validate()));
source.Cvc = 1000;
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => source.Validate()));
source = GetValidCcSource();
source.Validate();
source.Month = 0;
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => source.Validate()));
source.Month = 13;
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => source.Validate()));
source = GetValidCcSource();
source.Validate();
source.Year = -1;
await Assert.ThrowsAsync<ValidationException>(async () => await Task.Run(() => source.Validate()));
}
[Fact]
public void TestDeserializingPayment()
{
ServiceMockHelper.MockJsonResponse("Fixtures/CreditCard/Paid.json");
var payment = Payment.Fetch("b6c01c90-a091-45a4-9358-71668ecbf7ea");
Assert.Equal("b6c01c90-a091-45a4-9358-71668ecbf7ea", payment.Id);
Assert.Equal(1000, payment.Amount);
Assert.Equal("SAR", payment.Currency);
Assert.Equal("Test Payment", payment.Description);
Assert.Equal("https://mystore.com/order/redirect-back", payment.CallbackUrl);
Assert.Equal("5c02ba44-7fd1-444c-b82b-d3993b87d4b0", payment.Metadata["order_id"]);
Assert.Equal("50", payment.Metadata["tax"]);
Assert.IsType<CreditCard>(payment.Source);
var ccSource = (CreditCard) payment.Source;
Assert.Equal("Long John", ccSource.Name);
Assert.Equal("XXXX-XXXX-XXXX-1111", ccSource.Number);
Assert.Equal("moyasar_ap_je1iUidxhrh74257S891wvW", ccSource.GatewayId);
Assert.Equal("125478454231", ccSource.ReferenceNumber);
}
[Fact]
public void TestDeserializingApplePayPayment()
{
ServiceMockHelper.MockJsonResponse("Fixtures/ApplePay/Paid.json");
var payment = Payment.Fetch("a4a144ba-adc3-43bd-98e8-c80f2925fdc4");
Assert.Equal(1000, payment.Amount);
Assert.Equal("SAR", payment.Currency);
Assert.Equal("Test Payment", payment.Description);
Assert.Null(payment.CallbackUrl);
Assert.IsType<ApplePayMethod>(payment.Source);
var applePaySource = (ApplePayMethod) payment.Source;
Assert.Equal("applepay", applePaySource.Type);
Assert.Equal("XXXX-XXXX-XXXX-1111", applePaySource.Number);
Assert.Equal("APPROVED", applePaySource.Message);
Assert.Equal("moyasar_ap_je1iUidxhrh74257S891wvW", applePaySource.GatewayId);
Assert.Equal("125478454231", applePaySource.ReferenceNumber);
}
[Fact]
public void TestDeserializingStcPayPayment()
{
ServiceMockHelper.MockJsonResponse("Fixtures/StcPay/Paid.json");
var payment = Payment.Fetch("50559d3b-e67f-4b3a-8df8-509dde19fe38");
Assert.Equal(1000, payment.Amount);
Assert.Equal("SAR", payment.Currency);
Assert.Equal("Test Payment", payment.Description);
Assert.Null(payment.CallbackUrl);
Assert.IsType<StcPayMethod>(payment.Source);
var method = (StcPayMethod) payment.Source;
Assert.Equal("stcpay", method.Type);
Assert.Equal("0555555555", method.Mobile);
Assert.Equal("Paid", method.Message);
}
[Fact]
public void TestRefundPayment()
{
ServiceMockHelper.MockJsonResponse("Fixtures/CreditCard/Paid.json");
var payment = Payment.Fetch("b6c01c90-a091-45a4-9358-71668ecbf7ea");
var id = payment.Id;
var amount = payment.Amount;
ServiceMockHelper.MockJsonResponse("Fixtures/CreditCard/Refunded.json");
payment.Refund();
Assert.Equal(id, payment.Id);
Assert.Equal("refunded", payment.Status);
Assert.Equal(amount, payment.RefundedAmount);
Assert.Equal(DateTime.Parse("2019-01-03T10:14:14.414Z").ToUniversalTime(), payment.RefundedAt);
}
[Fact]
public async void RefundHigherAmountMustThrowException()
{
ServiceMockHelper.MockJsonResponse("Fixtures/CreditCard/Paid.json");
var payment = Payment.Fetch("b6c01c90-a091-45a4-9358-71668ecbf7ea");
var id = payment.Id;
var amount = payment.Amount;
ServiceMockHelper.MockJsonResponse("Fixtures/CreditCard/Refunded.json");
await Assert.ThrowsAsync<ValidationException>
(
async () => await Task.Run(() => payment.Refund(amount + 1))
);
}
[Fact]
public void TestPaymentListing()
{
ServiceMockHelper.MockJsonResponse("Fixtures/PaymentList.json");
var pagination = Payment.List();
Assert.IsType<CreditCard>(pagination.Items[0].Source);
Assert.IsType<ApplePayMethod>(pagination.Items[1].Source);
Assert.IsType<StcPayMethod>(pagination.Items[2].Source);
Assert.Equal(2, pagination.CurrentPage);
Assert.Equal(3, pagination.NextPage);
Assert.Equal(1, pagination.PreviousPage);
Assert.Equal(3, pagination.TotalPages);
Assert.Equal(9, pagination.TotalCount);
}
internal static PaymentInfo GetValidPaymentInfo(IPaymentSource source = null)
{
return new PaymentInfo
{
Amount = 3500,
Currency = "SAR",
Description = "Chinese Noodles Meal",
Source = source ?? GetValidCcSource(),
CallbackUrl = "http://mysite.test/payment_callback",
Metadata = new Dictionary<string, string>
{
{"order_id", "1232141"},
{"store_note", "okay"}
}
};
}
private static CreditCardSource GetValidCcSource()
{
return new CreditCardSource
{
Name = "John Doe",
Number = "4111111111111111",
Cvc = 141,
Month = 3,
Year = 2021,
};
}
private static ApplePaySource GetValidApplePaySource()
{
return new ApplePaySource
{
Token = @"{""stuff"":""foobar""}"
};
}
private static StcPaySource GetValidStcPaySource()
{
return new StcPaySource
{
Branch = "1",
Cashier = "1",
Mobile = "0555555555"
};
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.WindowsAzure.Commands.ServiceManagement.PlatformImageRepository.Model;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Threading;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests
{
[TestClass]
public class PIRTest : ServiceManagementTest
{
private const string vhdNamePrefix = "pirtestosvhd";
private const string imageNamePrefix = "pirtestosimage";
private string vhdName;
private string vhdBlobLocation;
private string image;
private const string location1 = "West US";
private const string location2 = "North Central US";
private const string location3 = "East US";
private static string publisher = "publisher1";
private static string normaluser = "normaluser2";
private const string normaluserSubId = "602258C5-52EC-46B3-A49A-7587A764AC84";
private const string storageNormalUser = "normalstorage";
[ClassInitialize]
public static void ClassInit(TestContext context)
{
if (defaultAzureSubscription.Equals(null))
{
Assert.Inconclusive("No Subscription is selected!");
}
if (vmPowershellCmdlets.GetAzureSubscription(publisher) == null)
{
publisher = defaultAzureSubscription.SubscriptionName;
}
if (vmPowershellCmdlets.GetAzureSubscription(normaluser) == null)
{
normaluser = defaultAzureSubscription.SubscriptionName;
}
}
[TestInitialize]
public void Initialize()
{
vhdName = Utilities.GetUniqueShortName(vhdNamePrefix);
image = Utilities.GetUniqueShortName(imageNamePrefix);
vhdBlobLocation = string.Format("{0}{1}/{2}", blobUrlRoot, vhdContainerName, vhdName);
try
{
if (string.IsNullOrEmpty(localFile))
{
vmPowershellCmdlets.AddAzureVhd(new FileInfo(osVhdName), vhdBlobLocation);
}
else
{
vmPowershellCmdlets.AddAzureVhd(new FileInfo(localFile), vhdBlobLocation);
}
}
catch (Exception e)
{
if (e.ToString().Contains("already exists") || e.ToString().Contains("currently a lease"))
{
// Use the already uploaded vhd.
Console.WriteLine("Using already uploaded blob..");
}
else
{
Console.WriteLine(e.ToString());
Assert.Inconclusive("Upload vhd is not set!");
}
}
try
{
vmPowershellCmdlets.AddAzureVMImage(image, vhdBlobLocation, OS.Windows);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
pass = false;
testStartTime = DateTime.Now;
}
[TestCleanup]
public virtual void CleanUp()
{
SwitchToPublisher();
Console.WriteLine("Test {0}", pass ? "passed" : "failed");
if ((cleanupIfPassed && pass) || (cleanupIfFailed && !pass))
{
Console.WriteLine("Starting to clean up created VM and service.");
try
{
vmPowershellCmdlets.RemoveAzureVMImage(image, false);
}
catch (Exception e)
{
Console.WriteLine("Exception occurs during cleanup: {0}", e.ToString());
}
try
{
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
/// <summary>
/// This test covers Get-AzurePlatformVMImage, Set-AzurePlatformVMImage and Remove-AzurePlatformVMImage cmdlets
/// </summary>
[TestMethod(), TestCategory("PIRTest"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get,Set,Remove)-AzurePlatformVMImage)")]
public void AzurePlatformVMImageSingleLocationTest()
{
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
// starting the test.
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
// Replicate the user image to "West US" and wait until the replication process is completed.
ComputeImageConfig compCfg = new ComputeImageConfig
{
Offer = "test",
Sku = "test",
Version = "test"
};
MarketplaceImageConfig marketCfg = null;
vmPowershellCmdlets.SetAzurePlatformVMImageReplicate(image, new string[] { location1 }, compCfg, marketCfg);
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
WaitForReplicationComplete(image);
// Make the replicated image public and wait until the PIR image shows up.
vmPowershellCmdlets.SetAzurePlatformVMImagePublic(image);
OSImageContext pirImage = WaitForPIRAppear(image, publisher);
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
// Check the locations of the PIR image.
string pirlocations = vmPowershellCmdlets.GetAzureVMImage(pirImage.ImageName)[0].Location;
Assert.IsTrue(pirlocations.Contains(location1));
Assert.IsFalse(pirlocations.Contains(location2));
Assert.IsFalse(pirlocations.Contains(location3));
// Switch to the normal User and check the PIR image.
SwitchToNormalUser();
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, image));
WaitForPIRAppear(image, publisher);
// Switch to the publisher and make the PIR image private
SwitchToPublisher();
vmPowershellCmdlets.SetAzurePlatformVMImagePrivate(image);
// Switch to the normal User and wait until the PIR image disapper
SwitchToNormalUser();
WaitForPIRDisappear(pirImage.ImageName);
// Switch to the publisher and remove the PIR image.
SwitchToPublisher();
vmPowershellCmdlets.RemoveAzurePlatformVMImage(image);
Assert.AreEqual(0, vmPowershellCmdlets.GetAzurePlatformVMImage(image).ReplicationProgress.Count);
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
pass = true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
/// <summary>
/// This test covers Get-AzurePlatformVMImage, Set-AzurePlatformVMImage and Remove-AzurePlatformVMImage cmdlets
/// </summary>
[TestMethod(), TestCategory("PIRTest"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get,Set,Remove)-AzurePlatformVMImage)")]
public void AzurePlatformVMImageMultipleLocationsTest()
{
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
// starting the test.
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
// Replicate the user image to "West US" and wait until the replication process is completed.
ComputeImageConfig compCfg = new ComputeImageConfig
{
Offer = "test",
Sku = "test",
Version = "test"
};
MarketplaceImageConfig marketCfg = null;
vmPowershellCmdlets.SetAzurePlatformVMImageReplicate(image, new string[] { location1, location2 }, compCfg, marketCfg);
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
WaitForReplicationComplete(image);
// Make the replicated image public and wait until the PIR image shows up.
vmPowershellCmdlets.SetAzurePlatformVMImagePublic(image);
OSImageContext pirImage = WaitForPIRAppear(image, publisher);
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
// Check the locations of the PIR image.
string pirlocations = vmPowershellCmdlets.GetAzureVMImage(pirImage.ImageName)[0].Location;
Assert.IsTrue(pirlocations.Contains(location1));
Assert.IsTrue(pirlocations.Contains(location2));
Assert.IsFalse(pirlocations.Contains(location3));
// Switch to the normal User and check the PIR image.
SwitchToNormalUser();
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureVMImage, image));
WaitForPIRAppear(image, publisher);
// Switch to the publisher and make the PIR image private
SwitchToPublisher();
vmPowershellCmdlets.SetAzurePlatformVMImagePrivate(image);
// Switch to the normal User and wait until the PIR image disapper
SwitchToNormalUser();
WaitForPIRDisappear(pirImage.ImageName);
// Switch to the publisher and remove the PIR image.
SwitchToPublisher();
vmPowershellCmdlets.RemoveAzurePlatformVMImage(image);
Assert.AreEqual(0, vmPowershellCmdlets.GetAzurePlatformVMImage(image).ReplicationProgress.Count);
PrintOSImageDetailsContext(vmPowershellCmdlets.GetAzurePlatformVMImage(image));
pass = true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
/// <summary>
/// This test covers Get-AzurePlatformVMImage, Set-AzurePlatformVMImage and Remove-AzurePlatformVMImage cmdlets
/// </summary>
[TestMethod(), TestCategory("PIRTest"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get,Set,Remove)-AzurePlatformVMImage)")]
public void AzurePlatformVMImageScenarioTest()
{
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string vmName = Utilities.GetUniqueShortName("pirtestvm");
string svcName = Utilities.GetUniqueShortName("pirtestservice");
try
{
SwitchToNormalUser();
try
{
vmPowershellCmdlets.GetAzureStorageAccount(storageNormalUser);
}
catch (Exception e)
{
if (e.ToString().Contains("ResourceNotFound"))
{
vmPowershellCmdlets.NewAzureStorageAccount(storageNormalUser, location1);
}
else
{
Console.WriteLine(e.ToString());
throw;
}
}
vmPowershellCmdlets.SetAzureSubscription(normaluser, normaluserSubId, storageNormalUser);
// Replicate the user image to "West US" and wait until the replication process is completed.
SwitchToPublisher();
ComputeImageConfig compCfg = new ComputeImageConfig
{
Offer = "test",
Sku = "test",
Version = "test"
};
MarketplaceImageConfig marketCfg = null;
vmPowershellCmdlets.SetAzurePlatformVMImageReplicate(image, new string[] { location1 }, compCfg, marketCfg);
// Make the replicated image public and wait until the PIR image shows up.
vmPowershellCmdlets.SetAzurePlatformVMImagePublic(image);
OSImageContext pirImage = WaitForPIRAppear(image, publisher);
// Switch to the normal User and check the PIR image.
SwitchToNormalUser();
WaitForPIRAppear(image, publisher);
// Create a VM using the PIR image
vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, svcName, pirImage.ImageName, username, password, location1);
Console.WriteLine("VM, {0}, is successfully created using the uploaded PIR image", vmPowershellCmdlets.GetAzureVM(vmName, svcName).Name);
// Remove the service and VM
vmPowershellCmdlets.RemoveAzureService(svcName);
// Switch to the publisher and remove the PIR image
SwitchToPublisher();
vmPowershellCmdlets.RemoveAzurePlatformVMImage(image);
pass = true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
private void SwitchToPublisher()
{
vmPowershellCmdlets.SetDefaultAzureSubscription(publisher);
}
private void SwitchToNormalUser()
{
vmPowershellCmdlets.SetDefaultAzureSubscription(normaluser);
}
private void WaitForReplicationComplete(string imageName)
{
DateTime startTime = DateTime.Now;
OSImageDetailsContext state;
try
{
do
{
state = vmPowershellCmdlets.GetAzurePlatformVMImage(imageName);
foreach(var repro in state.ReplicationProgress)
{
Console.WriteLine(repro.ToString());
}
}
while (!state.ReplicationProgress.TrueForAll((s) => (s.Progress.Equals("100"))));
Console.WriteLine("Replication completed after {0} minutes.", (DateTime.Now - startTime).TotalMinutes);
PrintOSImageDetailsContext(state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw;
}
}
private OSImageContext WaitForPIRAppear(string imageName, string publisherName, int waitTimeInMin = 1, int maxWaitTimeInMin = 30)
{
DateTime startTime = DateTime.Now;
while (true)
{
Collection<OSImageContext> vmImages = vmPowershellCmdlets.GetAzureVMImage();
foreach (OSImageContext image in vmImages)
{
if (Utilities.MatchKeywords(image.ImageName, new[]{imageName}, false) >= 0 && image.PublisherName.Equals(publisherName))
{
Console.WriteLine("MATCHED PIR image found after {0} minutes:", (DateTime.Now - startTime).TotalMinutes);
PrintContext<OSImageContext>(image);
return image;
}
}
if ((DateTime.Now - startTime).TotalMinutes < maxWaitTimeInMin)
{
Thread.Sleep(waitTimeInMin * 1000 * 60);
}
else
{
Assert.Fail("Cannot get PIR image, {0}, within {1} minutes!", imageName, maxWaitTimeInMin);
}
}
}
private bool WaitForPIRDisappear(string imageName, int waitTimeInMin = 1, int maxWaitTimeInMin = 30)
{
DateTime startTime = DateTime.Now;
while (true)
{
try
{
OSImageContext imageContext = vmPowershellCmdlets.GetAzureVMImage(imageName)[0];
if ((DateTime.Now - startTime).TotalMinutes < maxWaitTimeInMin)
{
Thread.Sleep(waitTimeInMin * 1000 * 60);
}
else
{
Assert.Fail("Still has image, {0}, after {1} minutes!", imageName, maxWaitTimeInMin);
}
}
catch (Exception e)
{
if (e.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("Image {0} disappered after {1} minutes.", imageName, (DateTime.Now - startTime).TotalMinutes);
return true;
}
else
{
Console.WriteLine(e.ToString());
throw;
}
}
}
}
private void PrintContext<T>(T obj)
{
Type type = typeof(T);
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
string typeName = property.PropertyType.FullName;
if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable"))
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
}
}
}
private void PrintOSImageDetailsContext(OSImageDetailsContext context)
{
PrintContext<OSImageContext>(context);
foreach (var repro in context.ReplicationProgress)
{
Console.WriteLine("ReplicationProgress: {0}", repro.ToString());
}
if (context.ReplicationProgress.Count == 0)
{
Console.WriteLine("There is no replication!");
}
Console.WriteLine("IsCorrupted {0}", context.IsCorrupted);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class SignerInfo
{
public int Version { get; }
public SubjectIdentifier SignerIdentifier { get; }
private readonly Oid _digestAlgorithm;
private readonly AttributeAsn[] _signedAttributes;
private readonly ReadOnlyMemory<byte>? _signedAttributesMemory;
private readonly Oid _signatureAlgorithm;
private readonly ReadOnlyMemory<byte>? _signatureAlgorithmParameters;
private readonly ReadOnlyMemory<byte> _signature;
private readonly AttributeAsn[] _unsignedAttributes;
private readonly SignedCms _document;
private X509Certificate2 _signerCertificate;
private SignerInfo _parentSignerInfo;
private CryptographicAttributeObjectCollection _parsedSignedAttrs;
private CryptographicAttributeObjectCollection _parsedUnsignedAttrs;
internal SignerInfo(ref SignerInfoAsn parsedData, SignedCms ownerDocument)
{
Version = parsedData.Version;
SignerIdentifier = new SubjectIdentifier(parsedData.Sid);
_digestAlgorithm = parsedData.DigestAlgorithm.Algorithm;
_signedAttributesMemory = parsedData.SignedAttributes;
_signatureAlgorithm = parsedData.SignatureAlgorithm.Algorithm;
_signatureAlgorithmParameters = parsedData.SignatureAlgorithm.Parameters;
_signature = parsedData.SignatureValue;
_unsignedAttributes = parsedData.UnsignedAttributes;
if (_signedAttributesMemory.HasValue)
{
SignedAttributesSet signedSet = SignedAttributesSet.Decode(
_signedAttributesMemory.Value,
AsnEncodingRules.BER);
_signedAttributes = signedSet.SignedAttributes;
Debug.Assert(_signedAttributes != null);
}
_document = ownerDocument;
}
public CryptographicAttributeObjectCollection SignedAttributes
{
get
{
if (_parsedSignedAttrs == null)
{
_parsedSignedAttrs = MakeAttributeCollection(_signedAttributes);
}
return _parsedSignedAttrs;
}
}
public CryptographicAttributeObjectCollection UnsignedAttributes
{
get
{
if (_parsedUnsignedAttrs == null)
{
_parsedUnsignedAttrs = MakeAttributeCollection(_unsignedAttributes);
}
return _parsedUnsignedAttrs;
}
}
internal ReadOnlyMemory<byte> GetSignatureMemory() => _signature;
public byte[] GetSignature() => _signature.ToArray();
public X509Certificate2 Certificate
{
get
{
if (_signerCertificate == null)
{
_signerCertificate = FindSignerCertificate();
}
return _signerCertificate;
}
}
public SignerInfoCollection CounterSignerInfos
{
get
{
// We only support one level of counter signing.
if (_parentSignerInfo != null ||
_unsignedAttributes == null ||
_unsignedAttributes.Length == 0)
{
return new SignerInfoCollection();
}
return GetCounterSigners(_unsignedAttributes);
}
}
public Oid DigestAlgorithm => new Oid(_digestAlgorithm);
public Oid SignatureAlgorithm => new Oid(_signatureAlgorithm);
public void AddUnsignedAttribute(AsnEncodedData unsignedAttribute)
{
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
ref SignedDataAsn signedData = ref _document.GetRawData();
ref SignerInfoAsn mySigner = ref signedData.SignerInfos[myIdx];
int existingAttribute = mySigner.UnsignedAttributes == null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid);
if (existingAttribute == -1)
{
// create a new attribute
AttributeAsn newUnsignedAttr = new AttributeAsn(unsignedAttribute);
int newAttributeIdx;
if (mySigner.UnsignedAttributes == null)
{
newAttributeIdx = 0;
mySigner.UnsignedAttributes = new AttributeAsn[1];
}
else
{
newAttributeIdx = mySigner.UnsignedAttributes.Length;
Array.Resize(ref mySigner.UnsignedAttributes, newAttributeIdx + 1);
}
mySigner.UnsignedAttributes[newAttributeIdx] = newUnsignedAttr;
}
else
{
// merge with existing attribute
ref AttributeAsn modifiedAttr = ref mySigner.UnsignedAttributes[existingAttribute];
int newIndex = modifiedAttr.AttrValues.Length;
Array.Resize(ref modifiedAttr.AttrValues, newIndex + 1);
modifiedAttr.AttrValues[newIndex] = unsignedAttribute.RawData;
}
// Re-normalize the document
_document.Reencode();
}
public void RemoveUnsignedAttribute(AsnEncodedData unsignedAttribute)
{
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
ref SignedDataAsn signedData = ref _document.GetRawData();
ref SignerInfoAsn mySigner = ref signedData.SignerInfos[myIdx];
(int outerIndex, int innerIndex) = FindAttributeLocation(mySigner.UnsignedAttributes, unsignedAttribute, out bool isOnlyValue);
if (outerIndex == -1 || innerIndex == -1)
{
throw new CryptographicException(SR.Cryptography_Cms_NoAttributeFound);
}
if (isOnlyValue)
{
PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes, outerIndex);
}
else
{
PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes[outerIndex].AttrValues, innerIndex);
}
// Re-normalize the document
_document.Reencode();
}
private SignerInfoCollection GetCounterSigners(AttributeAsn[] unsignedAttrs)
{
// Since each "attribute" can have multiple "attribute values" there's no real
// correlation to a predictive size here.
List<SignerInfo> signerInfos = new List<SignerInfo>();
foreach (AttributeAsn attributeAsn in unsignedAttrs)
{
if (attributeAsn.AttrType.Value == Oids.CounterSigner)
{
foreach (ReadOnlyMemory<byte> attrValue in attributeAsn.AttrValues)
{
SignerInfoAsn parsedData = SignerInfoAsn.Decode(attrValue, AsnEncodingRules.BER);
SignerInfo signerInfo = new SignerInfo(ref parsedData, _document)
{
_parentSignerInfo = this
};
signerInfos.Add(signerInfo);
}
}
}
return new SignerInfoCollection(signerInfos.ToArray());
}
public void ComputeCounterSignature()
{
throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert);
}
public void ComputeCounterSignature(CmsSigner signer)
{
if (_parentSignerInfo != null)
throw new CryptographicException(SR.Cryptography_Cms_NoCounterCounterSigner);
if (signer == null)
throw new ArgumentNullException(nameof(signer));
signer.CheckCertificateValue();
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
// Make sure that we're using the most up-to-date version of this that we can.
SignerInfo effectiveThis = _document.SignerInfos[myIdx];
X509Certificate2Collection chain;
SignerInfoAsn newSignerInfo = signer.Sign(effectiveThis._signature, null, false, out chain);
AttributeAsn newUnsignedAttr;
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
newSignerInfo.Encode(writer);
newUnsignedAttr = new AttributeAsn
{
AttrType = new Oid(Oids.CounterSigner, Oids.CounterSigner),
AttrValues = new[] { new ReadOnlyMemory<byte>(writer.Encode()) },
};
}
ref SignedDataAsn signedData = ref _document.GetRawData();
ref SignerInfoAsn mySigner = ref signedData.SignerInfos[myIdx];
int newExtensionIdx;
if (mySigner.UnsignedAttributes == null)
{
mySigner.UnsignedAttributes = new AttributeAsn[1];
newExtensionIdx = 0;
}
else
{
newExtensionIdx = mySigner.UnsignedAttributes.Length;
Array.Resize(ref mySigner.UnsignedAttributes, newExtensionIdx + 1);
}
mySigner.UnsignedAttributes[newExtensionIdx] = newUnsignedAttr;
_document.UpdateCertificatesFromAddition(chain);
// Re-normalize the document
_document.Reencode();
}
public void RemoveCounterSignature(int index)
{
if (index < 0)
{
// In NetFx RemoveCounterSignature doesn't bounds check, but the helper it calls does.
// In the helper the argument is called "childIndex".
throw new ArgumentOutOfRangeException("childIndex");
}
// The SignerInfo class is a projection of data contained within the SignedCms.
// The projection is applied at construction time, and is not live.
// So RemoveCounterSignature modifies _document, not this.
// (Because that's what NetFx does)
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
// We've been removed.
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
ref SignedDataAsn parentData = ref _document.GetRawData();
ref SignerInfoAsn myData = ref parentData.SignerInfos[myIdx];
if (myData.UnsignedAttributes == null)
{
throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
}
int removeAttrIdx = -1;
int removeValueIndex = -1;
bool removeWholeAttr = false;
int csIndex = 0;
AttributeAsn[] unsignedAttrs = myData.UnsignedAttributes;
for (var i = 0; i < unsignedAttrs.Length; i++)
{
AttributeAsn attributeAsn = unsignedAttrs[i];
if (attributeAsn.AttrType.Value == Oids.CounterSigner)
{
if (index < csIndex + attributeAsn.AttrValues.Length)
{
removeAttrIdx = i;
removeValueIndex = index - csIndex;
if (removeValueIndex == 0 && attributeAsn.AttrValues.Length == 1)
{
removeWholeAttr = true;
}
break;
}
csIndex += attributeAsn.AttrValues.Length;
}
}
if (removeAttrIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
}
// The easy path:
if (removeWholeAttr)
{
// Empty needs to normalize to null.
if (unsignedAttrs.Length == 1)
{
myData.UnsignedAttributes = null;
}
else
{
PkcsHelpers.RemoveAt(ref myData.UnsignedAttributes, removeAttrIdx);
}
}
else
{
PkcsHelpers.RemoveAt(ref unsignedAttrs[removeAttrIdx].AttrValues, removeValueIndex);
}
}
public void RemoveCounterSignature(SignerInfo counterSignerInfo)
{
if (counterSignerInfo == null)
throw new ArgumentNullException(nameof(counterSignerInfo));
SignerInfoCollection docSigners = _document.SignerInfos;
int index = docSigners.FindIndexForSigner(this);
if (index < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
SignerInfo liveThis = docSigners[index];
index = liveThis.CounterSignerInfos.FindIndexForSigner(counterSignerInfo);
if (index < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
RemoveCounterSignature(index);
}
public void CheckSignature(bool verifySignatureOnly) =>
CheckSignature(new X509Certificate2Collection(), verifySignatureOnly);
public void CheckSignature(X509Certificate2Collection extraStore, bool verifySignatureOnly)
{
if (extraStore == null)
throw new ArgumentNullException(nameof(extraStore));
X509Certificate2 certificate = Certificate;
if (certificate == null)
{
certificate = FindSignerCertificate(SignerIdentifier, extraStore);
if (certificate == null)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
}
Verify(extraStore, certificate, verifySignatureOnly);
}
public void CheckHash()
{
if (_signatureAlgorithm.Value != Oids.NoSignature)
{
throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters);
}
if (!CheckHash(compatMode: false) && !CheckHash(compatMode: true))
{
throw new CryptographicException(SR.Cryptography_BadSignature);
}
}
private bool CheckHash(bool compatMode)
{
using (IncrementalHash hasher = PrepareDigest(compatMode))
{
if (hasher == null)
{
Debug.Assert(compatMode, $"{nameof(PrepareDigest)} returned null for the primary check");
return false;
}
byte[] expectedSignature = hasher.GetHashAndReset();
return _signature.Span.SequenceEqual(expectedSignature);
}
}
private X509Certificate2 FindSignerCertificate()
{
return FindSignerCertificate(SignerIdentifier, _document.Certificates);
}
private static X509Certificate2 FindSignerCertificate(
SubjectIdentifier signerIdentifier,
X509Certificate2Collection extraStore)
{
if (extraStore == null || extraStore.Count == 0)
{
return null;
}
X509Certificate2Collection filtered = null;
X509Certificate2 match = null;
switch (signerIdentifier.Type)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
X509IssuerSerial issuerSerial = (X509IssuerSerial)signerIdentifier.Value;
filtered = extraStore.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
foreach (X509Certificate2 cert in filtered)
{
if (cert.IssuerName.Name == issuerSerial.IssuerName)
{
match = cert;
break;
}
}
break;
}
case SubjectIdentifierType.SubjectKeyIdentifier:
{
filtered = extraStore.Find(X509FindType.FindBySubjectKeyIdentifier, signerIdentifier.Value, false);
if (filtered.Count > 0)
{
match = filtered[0];
}
break;
}
}
if (filtered != null)
{
foreach (X509Certificate2 cert in filtered)
{
if (!ReferenceEquals(cert, match))
{
cert.Dispose();
}
}
}
return match;
}
private IncrementalHash PrepareDigest(bool compatMode)
{
HashAlgorithmName hashAlgorithmName = GetDigestAlgorithm();
IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName);
if (_parentSignerInfo == null)
{
// Windows compatibility: If a document was loaded in detached mode,
// but had content, hash both parts of the content.
if (_document.Detached)
{
ref SignedDataAsn documentData = ref _document.GetRawData();
ReadOnlyMemory<byte>? embeddedContent = documentData.EncapContentInfo.Content;
if (embeddedContent != null)
{
// Unwrap the OCTET STRING manually, because of PKCS#7 compatibility.
// https://tools.ietf.org/html/rfc5652#section-5.2.1
ReadOnlyMemory<byte> hashableContent = SignedCms.GetContent(
embeddedContent.Value,
documentData.EncapContentInfo.ContentType);
hasher.AppendData(hashableContent.Span);
}
}
hasher.AppendData(_document.GetHashableContentSpan());
}
else
{
hasher.AppendData(_parentSignerInfo._signature.Span);
}
// A Counter-Signer always requires signed attributes.
// If any signed attributes are present, message-digest is required.
bool invalid = _parentSignerInfo != null || _signedAttributes != null;
if (_signedAttributes != null)
{
byte[] contentDigest = hasher.GetHashAndReset();
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
// Some CMS implementations exist which do not sort the attributes prior to
// generating the signature. While they are not, technically, validly signed,
// Windows and OpenSSL both support trying in the document order rather than
// a sorted order. To accomplish this we will build as a SEQUENCE OF, but feed
// the SET OF into the hasher.
if (compatMode)
{
writer.PushSequence();
}
else
{
writer.PushSetOf();
}
foreach (AttributeAsn attr in _signedAttributes)
{
attr.Encode(writer);
// .NET Framework doesn't seem to validate the content type attribute,
// so we won't, either.
if (attr.AttrType.Value == Oids.MessageDigest)
{
CryptographicAttributeObject obj = MakeAttribute(attr);
if (obj.Values.Count != 1)
{
throw new CryptographicException(SR.Cryptography_BadHashValue);
}
var digestAttr = (Pkcs9MessageDigest)obj.Values[0];
if (!contentDigest.AsSpan().SequenceEqual(digestAttr.MessageDigest))
{
throw new CryptographicException(SR.Cryptography_BadHashValue);
}
invalid = false;
}
}
if (compatMode)
{
writer.PopSequence();
#if netcoreapp
Span<byte> setOfTag = stackalloc byte[1];
setOfTag[0] = 0x31;
hasher.AppendData(setOfTag);
hasher.AppendData(writer.EncodeAsSpan().Slice(1));
#else
byte[] encoded = writer.Encode();
encoded[0] = 0x31;
hasher.AppendData(encoded);
#endif
}
else
{
writer.PopSetOf();
#if netcoreapp
hasher.AppendData(writer.EncodeAsSpan());
#else
hasher.AppendData(writer.Encode());
#endif
}
}
}
else if (compatMode)
{
// If there were no signed attributes there's nothing to be compatible about.
return null;
}
if (invalid)
{
throw new CryptographicException(SR.Cryptography_Cms_MissingAuthenticatedAttribute);
}
return hasher;
}
private void Verify(
X509Certificate2Collection extraStore,
X509Certificate2 certificate,
bool verifySignatureOnly)
{
CmsSignature signatureProcessor = CmsSignature.ResolveAndVerifyKeyType(SignatureAlgorithm.Value, key: null);
if (signatureProcessor == null)
{
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, SignatureAlgorithm.Value);
}
bool signatureValid =
VerifySignature(signatureProcessor, certificate, compatMode: false) ||
VerifySignature(signatureProcessor, certificate, compatMode: true);
if (!signatureValid)
{
throw new CryptographicException(SR.Cryptography_BadSignature);
}
if (!verifySignatureOnly)
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.AddRange(extraStore);
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
if (!chain.Build(certificate))
{
X509ChainStatus status = chain.ChainStatus.FirstOrDefault();
throw new CryptographicException(SR.Cryptography_Cms_TrustFailure, status.StatusInformation);
}
// NetFx checks for either of these
const X509KeyUsageFlags SufficientFlags =
X509KeyUsageFlags.DigitalSignature |
X509KeyUsageFlags.NonRepudiation;
foreach (X509Extension ext in certificate.Extensions)
{
if (ext.Oid.Value == Oids.KeyUsage)
{
if (!(ext is X509KeyUsageExtension keyUsage))
{
keyUsage = new X509KeyUsageExtension();
keyUsage.CopyFrom(ext);
}
if ((keyUsage.KeyUsages & SufficientFlags) == 0)
{
throw new CryptographicException(SR.Cryptography_Cms_WrongKeyUsage);
}
}
}
}
}
private bool VerifySignature(
CmsSignature signatureProcessor,
X509Certificate2 certificate,
bool compatMode)
{
using (IncrementalHash hasher = PrepareDigest(compatMode))
{
if (hasher == null)
{
Debug.Assert(compatMode, $"{nameof(PrepareDigest)} returned null for the primary check");
return false;
}
#if netcoreapp
// SHA-2-512 is the biggest digest type we know about.
Span<byte> digestValue = stackalloc byte[512 / 8];
ReadOnlySpan<byte> digest = digestValue;
ReadOnlyMemory<byte> signature = _signature;
if (hasher.TryGetHashAndReset(digestValue, out int bytesWritten))
{
digest = digestValue.Slice(0, bytesWritten);
}
else
{
digest = hasher.GetHashAndReset();
}
#else
byte[] digest = hasher.GetHashAndReset();
byte[] signature = _signature.ToArray();
#endif
return signatureProcessor.VerifySignature(
digest,
signature,
DigestAlgorithm.Value,
hasher.AlgorithmName,
_signatureAlgorithmParameters,
certificate);
}
}
private HashAlgorithmName GetDigestAlgorithm()
{
return PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm.Value);
}
internal static CryptographicAttributeObjectCollection MakeAttributeCollection(AttributeAsn[] attributes)
{
var coll = new CryptographicAttributeObjectCollection();
if (attributes == null)
return coll;
foreach (AttributeAsn attribute in attributes)
{
coll.AddWithoutMerge(MakeAttribute(attribute));
}
return coll;
}
private static CryptographicAttributeObject MakeAttribute(AttributeAsn attribute)
{
Oid type = new Oid(attribute.AttrType);
AsnEncodedDataCollection valueColl = new AsnEncodedDataCollection();
foreach (ReadOnlyMemory<byte> attrValue in attribute.AttrValues)
{
valueColl.Add(PkcsHelpers.CreateBestPkcs9AttributeObjectAvailable(type, attrValue.ToArray()));
}
return new CryptographicAttributeObject(type, valueColl);
}
private static int FindAttributeIndexByOid(AttributeAsn[] attributes, Oid oid, int startIndex = 0)
{
for (int i = startIndex; i < attributes.Length; i++)
{
if (attributes[i].AttrType.Value == oid.Value)
{
return i;
}
}
return -1;
}
private static int FindAttributeValueIndexByEncodedData(ReadOnlyMemory<byte>[] attributeValues, ReadOnlySpan<byte> asnEncodedData, out bool isOnlyValue)
{
for (int i = 0; i < attributeValues.Length; i++)
{
ReadOnlySpan<byte> data = attributeValues[i].Span;
if (data.SequenceEqual(asnEncodedData))
{
isOnlyValue = attributeValues.Length == 1;
return i;
}
}
isOnlyValue = false;
return -1;
}
private static (int, int) FindAttributeLocation(AttributeAsn[] attributes, AsnEncodedData attribute, out bool isOnlyValue)
{
for (int outerIndex = 0; ; outerIndex++)
{
outerIndex = FindAttributeIndexByOid(attributes, attribute.Oid, outerIndex);
if (outerIndex == -1)
{
break;
}
int innerIndex = FindAttributeValueIndexByEncodedData(attributes[outerIndex].AttrValues, attribute.RawData, out isOnlyValue);
if (innerIndex != -1)
{
return (outerIndex, innerIndex);
}
}
isOnlyValue = false;
return (-1, -1);
}
}
}
| |
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using Elasticsearch.Net;
using Newtonsoft.Json;
namespace Nest
{
[JsonConverter(typeof(TimeJsonConverter))]
public class Time : IComparable<Time>, IEquatable<Time>
{
private const double MillisecondsInAYearApproximate = MillisecondsInADay * 365;
private const double MillisecondsInAMonthApproximate = MillisecondsInADay * 30;
private const double MillisecondsInAWeek = MillisecondsInADay * 7;
private const double MillisecondsInADay = MillisecondsInAnHour * 24;
private const double MillisecondsInAnHour = MillisecondsInAMinute * 60;
private const double MillisecondsInAMinute = MillisecondsInASecond * 60;
private const double MillisecondsInASecond = 1000;
private const double NanosecondsInAMillisecond = 100;
private const double MicrosecondsInAMillisecond = 10;
private static readonly Regex ExpressionRegex =
new Regex(@"^(?<factor>[-+]?\d+(?:\.\d+)?)\s*(?<interval>(?:y|w|d|h|m|s|ms|nanos|micros))?$",
RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
private static double FLOAT_TOLERANCE = 0.0000001;
private int? StaticTimeValue { get; }
public double? Factor { get; private set; }
public double? Milliseconds { get; private set; }
private double ApproximateMilliseconds { get; set; }
public TimeUnit? Interval { get; private set; }
public static implicit operator Time(TimeSpan span) => new Time(span);
public static implicit operator Time(double milliseconds)
{
if (Math.Abs(milliseconds - (-1)) < FLOAT_TOLERANCE) return Time.MinusOne;
if (Math.Abs(milliseconds) < FLOAT_TOLERANCE) return Time.Zero;
return new Time(milliseconds);
}
public static implicit operator Time(string expression) => new Time(expression);
public static Time MinusOne { get; } = new Time(-1, true);
public static Time Zero { get; } = new Time(0, true);
protected Time(int specialFactor, bool specialValue)
{
if (!specialValue) throw new ArgumentException("this constructor is only for static TimeValues");
this.StaticTimeValue = specialFactor;
}
public Time(TimeSpan timeSpan) { Reduce(timeSpan.TotalMilliseconds); }
public Time(double milliseconds) { Reduce(milliseconds); }
public Time(double factor, TimeUnit interval)
{
this.Factor = factor;
this.Interval = interval;
SetMilliseconds(this.Interval.Value, this.Factor.Value);
}
public Time(string timeUnit)
{
if (timeUnit.IsNullOrEmpty()) throw new ArgumentException("Time expression string is empty", nameof(timeUnit));
if (timeUnit == "-1" || timeUnit == "0")
{
this.StaticTimeValue = int.Parse(timeUnit);
return;
}
ParseExpression(timeUnit);
}
private void ParseExpression(string timeUnit)
{
var match = ExpressionRegex.Match(timeUnit);
if (!match.Success) throw new ArgumentException($"Time expression '{timeUnit}' string is invalid", nameof(timeUnit));
this.Factor = double.Parse(match.Groups["factor"].Value, CultureInfo.InvariantCulture);
var interval = match.Groups["interval"].Success ? match.Groups["interval"].Value : null;
switch (interval)
{
case null:
throw new ArgumentException($"Time expression '{timeUnit}' is missing an interval", nameof(timeUnit));
case "M":
this.Interval = TimeUnit.Month;
break;
case "m":
this.Interval = TimeUnit.Minute;
break;
default:
this.Interval = interval.ToEnum<TimeUnit>(StringComparison.OrdinalIgnoreCase);
break;
}
if (!this.Interval.HasValue)
throw new ArgumentException($"Time expression '{timeUnit}' can not be parsed to an interval", nameof(timeUnit));
SetMilliseconds(this.Interval.Value, this.Factor.Value);
}
public int CompareTo(Time other)
{
if (other == null) return 1;
if (this.StaticTimeValue.HasValue && !other.StaticTimeValue.HasValue) return -1;
if (!this.StaticTimeValue.HasValue && other.StaticTimeValue.HasValue) return 1;
if (this.StaticTimeValue.HasValue && other.StaticTimeValue.HasValue)
{
// ReSharper disable PossibleInvalidOperationException
if (this.StaticTimeValue.Value == other.StaticTimeValue.Value) return 0;
if (this.StaticTimeValue.Value < other.StaticTimeValue.Value) return -1;
return 1;
// ReSharper enable PossibleInvalidOperationException
};
if (this.ApproximateMilliseconds == other.ApproximateMilliseconds) return 0;
if (this.ApproximateMilliseconds < other.ApproximateMilliseconds) return -1;
return 1;
}
public static Time ToFirstUnitYieldingInteger(Time fractionalTime)
{
var fraction = fractionalTime.Factor.GetValueOrDefault(double.Epsilon);
if (IsIntegerGreaterThanZero(fraction)) return fractionalTime;
var ms = fractionalTime.ApproximateMilliseconds;
if (ms > MillisecondsInAWeek)
{
fraction = ms / MillisecondsInAWeek;
if (IsIntegerGreaterThanZero(fraction)) return new Time(fraction, TimeUnit.Week);
}
if (ms > MillisecondsInADay)
{
fraction = ms / MillisecondsInADay;
if (IsIntegerGreaterThanZero(fraction)) return new Time(fraction, TimeUnit.Day);
}
if (ms > MillisecondsInAnHour)
{
fraction = ms / MillisecondsInAnHour;
if (IsIntegerGreaterThanZero(fraction)) return new Time(fraction, TimeUnit.Hour);
}
if (ms > MillisecondsInAMinute)
{
fraction = ms / MillisecondsInAMinute;
if (IsIntegerGreaterThanZero(fraction)) return new Time(fraction, TimeUnit.Minute);
}
if (ms > MillisecondsInASecond)
{
fraction = ms / MillisecondsInASecond;
if (IsIntegerGreaterThanZero(fraction)) return new Time(fraction, TimeUnit.Second);
}
return new Time(ms, TimeUnit.Millisecond);
}
private static bool IsIntegerGreaterThanZero(double d) => Math.Abs(d % 1) < double.Epsilon;
public static bool operator <(Time left, Time right) => left.CompareTo(right) < 0;
public static bool operator <=(Time left, Time right) => left.CompareTo(right) < 0 || left.Equals(right);
public static bool operator >(Time left, Time right) => left.CompareTo(right) > 0;
public static bool operator >=(Time left, Time right) => left.CompareTo(right) > 0 || left.Equals(right);
public static bool operator ==(Time left, Time right) =>
ReferenceEquals(left, null) ? ReferenceEquals(right, null) : left.Equals(right);
public static bool operator !=(Time left, Time right) => !(left == right);
public TimeSpan ToTimeSpan()
{
if (this.StaticTimeValue.HasValue) throw new Exception("Static time values like -1 or 0 have no logical TimeSpan representation");
//should not happen will throw in constructor
if (!this.Interval.HasValue) throw new Exception("TimeUnit has no interval so you can not call ToTimeStamp on it");
switch (this.Interval.Value)
{
case TimeUnit.Microseconds:
// ReSharper disable once PossibleInvalidOperationException
var microTicks = (long)this.Factor.Value * 10;
return new TimeSpan(microTicks);
case TimeUnit.Nanoseconds:
var nanoTicks = (long)this.Factor.Value / 100;
// ReSharper disable once PossibleInvalidOperationException
return new TimeSpan(nanoTicks);
default:
return TimeSpan.FromMilliseconds(this.ApproximateMilliseconds);
}
}
public override string ToString()
{
if (this.StaticTimeValue.HasValue)
return this.StaticTimeValue.Value.ToString();
if (!this.Factor.HasValue)
return "<bad Time object should not happen>";
var factor = this.Factor.Value.ToString("0.##", CultureInfo.InvariantCulture);
return (this.Interval.HasValue) ? factor + this.Interval.Value.GetStringValue() : factor;
}
public bool Equals(Time other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (this.StaticTimeValue.HasValue && !other.StaticTimeValue.HasValue) return false;
if (!this.StaticTimeValue.HasValue && other.StaticTimeValue.HasValue) return false;
if (this.StaticTimeValue.HasValue && other.StaticTimeValue.HasValue)
return this.StaticTimeValue == other.StaticTimeValue;
return Math.Abs(this.ApproximateMilliseconds - other.ApproximateMilliseconds) < 0.00001;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Time) obj);
}
public override int GetHashCode()
{
if (this.StaticTimeValue.HasValue) return this.StaticTimeValue.Value.GetHashCode();
return this.ApproximateMilliseconds.GetHashCode();
}
private void SetMilliseconds(TimeUnit interval, double factor)
{
this.Milliseconds = GetExactMilliseconds(interval, factor) ;
this.ApproximateMilliseconds = GetApproximateMilliseconds(interval, factor, this.Milliseconds.Value);
}
private double GetExactMilliseconds(TimeUnit interval, double factor)
{
switch (interval)
{
case TimeUnit.Week:
return factor * MillisecondsInAWeek;
case TimeUnit.Day:
return factor * MillisecondsInADay;
case TimeUnit.Hour:
return factor * MillisecondsInAnHour;
case TimeUnit.Minute:
return factor * MillisecondsInAMinute;
case TimeUnit.Second:
return factor * MillisecondsInASecond;
case TimeUnit.Microseconds:
return factor / MicrosecondsInAMillisecond;
case TimeUnit.Nanoseconds:
return factor / NanosecondsInAMillisecond;
case TimeUnit.Year:
case TimeUnit.Month:
// Cannot calculate exact milliseconds for non-fixed intervals
return -1;
default: // ms
return factor;
}
}
private double GetApproximateMilliseconds(TimeUnit interval, double factor, double fallback)
{
switch (interval)
{
case TimeUnit.Year:
return factor * MillisecondsInAYearApproximate;
case TimeUnit.Month:
return factor * MillisecondsInAMonthApproximate;
default:
return fallback;
}
}
private void Reduce(double ms)
{
this.Milliseconds = ms;
this.ApproximateMilliseconds = ms;
if (ms >= MillisecondsInAWeek)
{
Factor = ms / MillisecondsInAWeek;
Interval = TimeUnit.Week;
}
else if (ms >= MillisecondsInADay)
{
Factor = ms / MillisecondsInADay;
Interval = TimeUnit.Day;
}
else if (ms >= MillisecondsInAnHour)
{
Factor = ms / MillisecondsInAnHour;
Interval = TimeUnit.Hour;
}
else if (ms >= MillisecondsInAMinute)
{
Factor = ms / MillisecondsInAMinute;
Interval = TimeUnit.Minute;
}
else if (ms >= MillisecondsInASecond)
{
Factor = ms / MillisecondsInASecond;
Interval = TimeUnit.Second;
}
else
{
Factor = ms;
Interval = TimeUnit.Millisecond;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.SS.Util;
namespace TestCases.SS.Formula.Functions
{
using NPOI.HSSF;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NUnit.Framework;
using System;
using TestCases.HSSF;
/**
* Test cases for COUNT(), COUNTA() COUNTIF(), COUNTBLANK()
*
* @author Josh Micich
*/
[TestFixture]
public class TestCountFuncs
{
private static String NULL = null;
/// <summary>
/// Some of the tests are depending on the american culture.
/// </summary>
[SetUp]
public void InitializeCultere()
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
}
[Test]
public void TestCountBlank()
{
AreaEval range;
ValueEval[] values;
values = new ValueEval[] {
new NumberEval(0),
new StringEval(""), // note - does match blank
BoolEval.TRUE,
BoolEval.FALSE,
ErrorEval.DIV_ZERO,
BlankEval.instance,
};
range = EvalFactory.CreateAreaEval("A1:B3", values);
ConfirmCountBlank(2, range);
values = new ValueEval[] {
new NumberEval(0),
new StringEval(""), // note - does match blank
BlankEval.instance,
BoolEval.FALSE,
BoolEval.TRUE,
BlankEval.instance,
};
range = EvalFactory.CreateAreaEval("A1:B3", values);
ConfirmCountBlank(3, range);
}
[Test]
public void TestCountA()
{
ValueEval[] args;
args = new ValueEval[] {
new NumberEval(0),
};
ConfirmCountA(1, args);
args = new ValueEval[] {
new NumberEval(0),
new NumberEval(0),
new StringEval(""),
};
ConfirmCountA(3, args);
args = new ValueEval[] {
EvalFactory.CreateAreaEval("D2:F5", new ValueEval[12]),
};
ConfirmCountA(12, args);
args = new ValueEval[] {
EvalFactory.CreateAreaEval("D1:F5", new ValueEval[15]),
EvalFactory.CreateRefEval("A1"),
EvalFactory.CreateAreaEval("A1:G6", new ValueEval[42]),
new NumberEval(0),
};
ConfirmCountA(59, args);
}
[Test]
public void TestCountIf()
{
AreaEval range;
ValueEval[] values;
// when criteria is a bool value
values = new ValueEval[] {
new NumberEval(0),
new StringEval("TRUE"), // note - does not match bool TRUE
BoolEval.TRUE,
BoolEval.FALSE,
BoolEval.TRUE,
BlankEval.instance,
};
range = EvalFactory.CreateAreaEval("A1:B3", values);
ConfirmCountIf(2, range, BoolEval.TRUE);
// when criteria is numeric
values = new ValueEval[] {
new NumberEval(0),
new StringEval("2"),
new StringEval("2.001"),
new NumberEval(2),
new NumberEval(2),
BoolEval.TRUE,
};
range = EvalFactory.CreateAreaEval("A1:B3", values);
ConfirmCountIf(3, range, new NumberEval(2));
// note - same results when criteria is a string that Parses as the number with the same value
ConfirmCountIf(3, range, new StringEval("2.00"));
// when criteria is an expression (starting with a comparison operator)
ConfirmCountIf(2, range, new StringEval(">1"));
// when criteria is an expression (starting with a comparison operator)
ConfirmCountIf(2, range, new StringEval(">0.5"));
}
[Test]
public void TestCriteriaPredicateNe_Bug46647()
{
IMatchPredicate mp = Countif.CreateCriteriaPredicate(new StringEval("<>aa"), 0, 0);
Assert.IsNotNull(mp);
StringEval seA = new StringEval("aa"); // this should not match the criteria '<>aa'
StringEval seB = new StringEval("bb"); // this should match
if (mp.Matches(seA) && !mp.Matches(seB))
{
throw new AssertionException("Identified bug 46647");
}
Assert.IsFalse(mp.Matches(seA));
Assert.IsTrue(mp.Matches(seB));
// general Tests for not-equal (<>) operator
AreaEval range;
ValueEval[] values;
values = new ValueEval[] {
new StringEval("aa"),
new StringEval("def"),
new StringEval("aa"),
new StringEval("ghi"),
new StringEval("aa"),
new StringEval("aa"),
};
range = EvalFactory.CreateAreaEval("A1:A6", values);
ConfirmCountIf(2, range, new StringEval("<>aa"));
values = new ValueEval[] {
new StringEval("ab"),
new StringEval("aabb"),
new StringEval("aa"), // match
new StringEval("abb"),
new StringEval("aab"),
new StringEval("ba"), // match
};
range = EvalFactory.CreateAreaEval("A1:A6", values);
ConfirmCountIf(2, range, new StringEval("<>a*b"));
values = new ValueEval[] {
new NumberEval(222),
new NumberEval(222),
new NumberEval(111),
new StringEval("aa"),
new StringEval("111"),
};
range = EvalFactory.CreateAreaEval("A1:A5", values);
ConfirmCountIf(4, range, new StringEval("<>111"));
}
/**
* String criteria in COUNTIF are case insensitive;
* for example, the string "apples" and the string "APPLES" will match the same cells.
*/
[Test]
public void TestCaseInsensitiveStringComparison()
{
AreaEval range;
ValueEval[] values;
values = new ValueEval[] {
new StringEval("no"),
new StringEval("NO"),
new StringEval("No"),
new StringEval("Yes")
};
range = EvalFactory.CreateAreaEval("A1:A4", values);
ConfirmCountIf(3, range, new StringEval("no"));
ConfirmCountIf(3, range, new StringEval("NO"));
ConfirmCountIf(3, range, new StringEval("No"));
}
/**
* special case where the criteria argument is a cell reference
*/
[Test]
public void TestCountIfWithCriteriaReference()
{
ValueEval[] values = {
new NumberEval(22),
new NumberEval(25),
new NumberEval(21),
new NumberEval(25),
new NumberEval(25),
new NumberEval(25),
};
AreaEval arg0 = EvalFactory.CreateAreaEval("C1:C6", values);
ValueEval criteriaArg = EvalFactory.CreateRefEval("A1", new NumberEval(25));
ValueEval[] args = { arg0, criteriaArg, };
double actual = NumericFunctionInvoker.Invoke(new Countif(), args);
Assert.AreEqual(4, actual, 0D);
}
private static void ConfirmCountA(int expected, ValueEval[] args)
{
double result = NumericFunctionInvoker.Invoke(new Counta(), args);
Assert.AreEqual(expected, result, 0);
}
private static void ConfirmCountIf(int expected, AreaEval range, ValueEval criteria)
{
ValueEval[] args = { range, criteria, };
double result = NumericFunctionInvoker.Invoke(new Countif(), args);
Assert.AreEqual(expected, result, 0);
}
private static void ConfirmCountBlank(int expected, AreaEval range)
{
ValueEval[] args = { range };
double result = NumericFunctionInvoker.Invoke(new Countblank(), args);
Assert.AreEqual(expected, result, 0);
}
private static IMatchPredicate CreateCriteriaPredicate(ValueEval ev)
{
return Countif.CreateCriteriaPredicate(ev, 0, 0);
}
/**
* the criteria arg is mostly handled by {@link OperandResolver#getSingleValue(NPOI.SS.Formula.Eval.ValueEval, int, int)}}
*/
[Test]
public void TestCountifAreaCriteria()
{
int srcColIx = 2; // anything but column A
ValueEval v0 = new NumberEval(2.0);
ValueEval v1 = new StringEval("abc");
ValueEval v2 = ErrorEval.DIV_ZERO;
AreaEval ev = EvalFactory.CreateAreaEval("A10:A12", new ValueEval[] { v0, v1, v2, });
IMatchPredicate mp;
mp = Countif.CreateCriteriaPredicate(ev, 9, srcColIx);
ConfirmPredicate(true, mp, srcColIx);
ConfirmPredicate(false, mp, "abc");
ConfirmPredicate(false, mp, ErrorEval.DIV_ZERO);
mp = Countif.CreateCriteriaPredicate(ev, 10, srcColIx);
ConfirmPredicate(false, mp, srcColIx);
ConfirmPredicate(true, mp, "abc");
ConfirmPredicate(false, mp, ErrorEval.DIV_ZERO);
mp = Countif.CreateCriteriaPredicate(ev, 11, srcColIx);
ConfirmPredicate(false, mp, srcColIx);
ConfirmPredicate(false, mp, "abc");
ConfirmPredicate(true, mp, ErrorEval.DIV_ZERO);
ConfirmPredicate(false, mp, ErrorEval.VALUE_INVALID);
// tricky: indexing outside of A10:A12
// even this #VALUE! error Gets used by COUNTIF as valid criteria
mp = Countif.CreateCriteriaPredicate(ev, 12, srcColIx);
ConfirmPredicate(false, mp, srcColIx);
ConfirmPredicate(false, mp, "abc");
ConfirmPredicate(false, mp, ErrorEval.DIV_ZERO);
ConfirmPredicate(true, mp, ErrorEval.VALUE_INVALID);
}
[Test]
public void TestCountifEmptyStringCriteria()
{
IMatchPredicate mp;
// pred '=' matches blank cell but not empty string
mp = CreateCriteriaPredicate(new StringEval("="));
ConfirmPredicate(false, mp, "");
ConfirmPredicate(true, mp, NULL);
// pred '' matches both blank cell but not empty string
mp = CreateCriteriaPredicate(new StringEval(""));
ConfirmPredicate(true, mp, "");
ConfirmPredicate(true, mp, NULL);
// pred '<>' matches empty string but not blank cell
mp = CreateCriteriaPredicate(new StringEval("<>"));
ConfirmPredicate(false, mp, NULL);
ConfirmPredicate(true, mp, "");
}
[Test]
public void TestCountifComparisons()
{
IMatchPredicate mp;
mp = CreateCriteriaPredicate(new StringEval(">5"));
ConfirmPredicate(false, mp, 4);
ConfirmPredicate(false, mp, 5);
ConfirmPredicate(true, mp, 6);
mp = CreateCriteriaPredicate(new StringEval("<=5"));
ConfirmPredicate(true, mp, 4);
ConfirmPredicate(true, mp, 5);
ConfirmPredicate(false, mp, 6);
ConfirmPredicate(false, mp, "4.9");
ConfirmPredicate(false, mp, "4.9t");
ConfirmPredicate(false, mp, "5.1");
ConfirmPredicate(false, mp, NULL);
mp = CreateCriteriaPredicate(new StringEval("=abc"));
ConfirmPredicate(true, mp, "abc");
mp = CreateCriteriaPredicate(new StringEval("=42"));
ConfirmPredicate(false, mp, 41);
ConfirmPredicate(true, mp, 42);
ConfirmPredicate(true, mp, "42");
mp = CreateCriteriaPredicate(new StringEval(">abc"));
ConfirmPredicate(false, mp, 4);
ConfirmPredicate(false, mp, "abc");
ConfirmPredicate(true, mp, "abd");
mp = CreateCriteriaPredicate(new StringEval(">4t3"));
ConfirmPredicate(false, mp, 4);
ConfirmPredicate(false, mp, 500);
ConfirmPredicate(true, mp, "500");
ConfirmPredicate(true, mp, "4t4");
}
/**
* the criteria arg value can be an error code (the error does not
* propagate to the COUNTIF result).
*/
[Test]
public void TestCountifErrorCriteria()
{
IMatchPredicate mp;
mp = CreateCriteriaPredicate(new StringEval("#REF!"));
ConfirmPredicate(false, mp, 4);
ConfirmPredicate(false, mp, "#REF!");
ConfirmPredicate(true, mp, ErrorEval.REF_INVALID);
mp = CreateCriteriaPredicate(new StringEval("<#VALUE!"));
ConfirmPredicate(false, mp, 4);
ConfirmPredicate(false, mp, "#DIV/0!");
ConfirmPredicate(false, mp, "#REF!");
ConfirmPredicate(true, mp, ErrorEval.DIV_ZERO);
ConfirmPredicate(false, mp, ErrorEval.REF_INVALID);
// not quite an error literal, should be treated as plain text
mp = CreateCriteriaPredicate(new StringEval("<=#REF!a"));
ConfirmPredicate(false, mp, 4);
ConfirmPredicate(true, mp, "#DIV/0!");
ConfirmPredicate(true, mp, "#REF!");
ConfirmPredicate(false, mp, ErrorEval.DIV_ZERO);
ConfirmPredicate(false, mp, ErrorEval.REF_INVALID);
}
/**
* Bug #51498 - Check that CountIf behaves correctly for GTE, LTE
* and NEQ cases
*/
[Test]
public void TestCountifBug51498()
{
int REF_COL = 4;
int EVAL_COL = 3;
HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook("51498.xls");
IFormulaEvaluator evaluator = workbook.GetCreationHelper().CreateFormulaEvaluator();
ISheet sheet = workbook.GetSheetAt(0);
// numeric criteria
for (int i = 0; i < 8; i++)
{
CellValue expected = evaluator.Evaluate(sheet.GetRow(i).GetCell(REF_COL));
CellValue actual = evaluator.Evaluate(sheet.GetRow(i).GetCell(EVAL_COL));
Assert.AreEqual(expected.FormatAsString(), actual.FormatAsString());
}
// boolean criteria
for (int i = 0; i < 8; i++)
{
HSSFCell cellFmla = (HSSFCell)sheet.GetRow(i).GetCell(8);
HSSFCell cellRef = (HSSFCell)sheet.GetRow(i).GetCell(9);
double expectedValue = cellRef.NumericCellValue;
double actualValue = evaluator.Evaluate(cellFmla).NumberValue;
Assert.AreEqual(expectedValue, actualValue, 0.0001,
"Problem with a formula at " +
new CellReference(cellFmla).FormatAsString() + "[" + cellFmla.CellFormula + "] ");
}
// string criteria
for (int i = 1; i < 9; i++)
{
ICell cellFmla = sheet.GetRow(i).GetCell(13);
ICell cellRef = sheet.GetRow(i).GetCell(14);
double expectedValue = cellRef.NumericCellValue;
double actualValue = evaluator.Evaluate(cellFmla).NumberValue;
Assert.AreEqual(expectedValue, actualValue, 0.0001,
"Problem with a formula at " +
new CellReference(cellFmla).FormatAsString() + "[" + cellFmla.CellFormula + "] ");
}
}
[Test]
public void TestWildCards()
{
IMatchPredicate mp;
mp = CreateCriteriaPredicate(new StringEval("a*b"));
ConfirmPredicate(false, mp, "abc");
ConfirmPredicate(true, mp, "ab");
ConfirmPredicate(true, mp, "axxb");
ConfirmPredicate(false, mp, "xab");
mp = CreateCriteriaPredicate(new StringEval("a?b"));
ConfirmPredicate(false, mp, "abc");
ConfirmPredicate(false, mp, "ab");
ConfirmPredicate(false, mp, "axxb");
ConfirmPredicate(false, mp, "xab");
ConfirmPredicate(true, mp, "axb");
mp = CreateCriteriaPredicate(new StringEval("a~?"));
ConfirmPredicate(false, mp, "a~a");
ConfirmPredicate(false, mp, "a~?");
ConfirmPredicate(true, mp, "a?");
mp = CreateCriteriaPredicate(new StringEval("~*a"));
ConfirmPredicate(false, mp, "~aa");
ConfirmPredicate(false, mp, "~*a");
ConfirmPredicate(true, mp, "*a");
mp = CreateCriteriaPredicate(new StringEval("12?12"));
ConfirmPredicate(false, mp, 12812);
ConfirmPredicate(true, mp, "12812");
ConfirmPredicate(false, mp, "128812");
}
[Test]
public void TestNotQuiteWildCards()
{
IMatchPredicate mp;
// make sure special reg-ex chars are treated like normal chars
mp = CreateCriteriaPredicate(new StringEval("a.b"));
ConfirmPredicate(false, mp, "aab");
ConfirmPredicate(true, mp, "a.b");
mp = CreateCriteriaPredicate(new StringEval("a~b"));
ConfirmPredicate(false, mp, "ab");
ConfirmPredicate(false, mp, "axb");
ConfirmPredicate(false, mp, "a~~b");
ConfirmPredicate(true, mp, "a~b");
mp = CreateCriteriaPredicate(new StringEval(">a*b"));
ConfirmPredicate(false, mp, "a(b");
ConfirmPredicate(true, mp, "aab");
ConfirmPredicate(false, mp, "a*a");
ConfirmPredicate(true, mp, "a*c");
}
private static void ConfirmPredicate(bool expectedResult, IMatchPredicate matchPredicate, int value)
{
Assert.AreEqual(expectedResult, matchPredicate.Matches(new NumberEval(value)));
}
private static void ConfirmPredicate(bool expectedResult, IMatchPredicate matchPredicate, String value)
{
ValueEval ev = (value == null) ? BlankEval.instance : (ValueEval)new StringEval(value);
Assert.AreEqual(expectedResult, matchPredicate.Matches(ev));
}
private static void ConfirmPredicate(bool expectedResult, IMatchPredicate matchPredicate, ErrorEval value)
{
Assert.AreEqual(expectedResult, matchPredicate.Matches(value));
}
[Test]
public void TestCountifFromSpreadsheet()
{
TestCountFunctionFromSpreadsheet("countifExamples.xls", 1, 2, 3, "countif");
}
/**
* Two COUNTIF examples taken from
* http://office.microsoft.com/en-us/excel-help/countif-function-HP010069840.aspx?CTT=5&origin=HA010277524
*/
[Test]
public void TestCountifExamples()
{
HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("countifExamples.xls");
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
HSSFSheet sheet1 = (HSSFSheet)wb.GetSheet("MSDN Example 1");
for (int rowIx = 7; rowIx <= 12; rowIx++)
{
HSSFRow row = (HSSFRow)sheet1.GetRow(rowIx - 1);
HSSFCell cellA = (HSSFCell)row.GetCell(0); // cell containing a formula with COUNTIF
Assert.AreEqual(CellType.Formula, cellA.CellType);
HSSFCell cellC = (HSSFCell)row.GetCell(2); // cell with a reference value
Assert.AreEqual(CellType.Numeric, cellC.CellType);
CellValue cv = fe.Evaluate(cellA);
double actualValue = cv.NumberValue;
double expectedValue = cellC.NumericCellValue;
Assert.AreEqual(expectedValue, actualValue, 0.0001,
"Problem with a formula at " + new CellReference(cellA).FormatAsString()
+ ": " + cellA.CellFormula + " :"
+ "Expected = (" + expectedValue + ") Actual=(" + actualValue + ") ");
}
HSSFSheet sheet2 = (HSSFSheet)wb.GetSheet("MSDN Example 2");
for (int rowIx = 9; rowIx <= 14; rowIx++)
{
HSSFRow row = (HSSFRow)sheet2.GetRow(rowIx - 1);
HSSFCell cellA = (HSSFCell)row.GetCell(0); // cell containing a formula with COUNTIF
Assert.AreEqual(CellType.Formula, cellA.CellType);
HSSFCell cellC = (HSSFCell)row.GetCell(2); // cell with a reference value
Assert.AreEqual(CellType.Numeric, cellC.CellType);
CellValue cv = fe.Evaluate(cellA);
double actualValue = cv.NumberValue;
double expectedValue = cellC.NumericCellValue;
Assert.AreEqual(expectedValue, actualValue, 0.0001,
"Problem with a formula at " +
new CellReference(cellA).FormatAsString() + "[" + cellA.CellFormula + "]: "
+ "Expected = (" + expectedValue + ") Actual=(" + actualValue + ") ");
}
}
[Test]
public void TestCountBlankFromSpreadsheet()
{
TestCountFunctionFromSpreadsheet("countblankExamples.xls", 1, 3, 4, "countblank");
}
private static void TestCountFunctionFromSpreadsheet(String FILE_NAME, int START_ROW_IX, int COL_IX_ACTUAL, int COL_IX_EXPECTED, String functionName)
{
int failureCount = 0;
HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook(FILE_NAME);
ISheet sheet = wb.GetSheetAt(0);
HSSFFormulaEvaluator fe = new HSSFFormulaEvaluator(wb);
int maxRow = sheet.LastRowNum;
for (int rowIx = START_ROW_IX; rowIx < maxRow; rowIx++)
{
IRow row = sheet.GetRow(rowIx);
if (row == null)
{
continue;
}
ICell cell = row.GetCell(COL_IX_ACTUAL);
CellValue cv = fe.Evaluate(cell);
double actualValue = cv.NumberValue;
double expectedValue = row.GetCell(COL_IX_EXPECTED).NumericCellValue;
if (actualValue != expectedValue)
{
System.Console.Error.WriteLine("Problem with Test case on row " + (rowIx + 1) + " "
+ "Expected = (" + expectedValue + ") Actual=(" + actualValue + ") ");
failureCount++;
}
}
if (failureCount > 0)
{
throw new AssertionException(failureCount + " " + functionName
+ " Evaluations failed. See stderr for more details");
}
}
}
}
| |
// Python Tools for Visual Studio
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.PythonTools.Parsing.Ast {
public class FunctionDefinition : ScopeStatement {
protected Statement _body;
private readonly NameExpression/*!*/ _name;
private readonly Parameter[] _parameters;
private Expression _returnAnnotation;
private DecoratorStatement _decorators;
private bool _generator; // The function is a generator
private bool _coroutine;
private bool _isLambda;
private PythonVariable _variable; // The variable corresponding to the function name or null for lambdas
internal PythonVariable _nameVariable; // the variable that refers to the global __name__
internal bool _hasReturn;
private int _headerIndex;
private int _defIndex;
internal static readonly object WhitespaceAfterAsync = new object();
public FunctionDefinition(NameExpression name, Parameter[] parameters)
: this(name, parameters, (Statement)null) {
}
public FunctionDefinition(NameExpression name, Parameter[] parameters, Statement body, DecoratorStatement decorators = null) {
if (name == null) {
_name = new NameExpression("<lambda>");
_isLambda = true;
} else {
_name = name;
}
_parameters = parameters;
_body = body;
_decorators = decorators;
}
public bool IsLambda {
get {
return _isLambda;
}
}
public IList<Parameter> Parameters {
get { return _parameters; }
}
internal override int ArgCount {
get {
return _parameters.Length;
}
}
public Expression ReturnAnnotation {
get { return _returnAnnotation; }
set { _returnAnnotation = value; }
}
public override Statement Body {
get { return _body; }
}
internal void SetBody(Statement body) {
_body = body;
}
public int HeaderIndex {
get { return _headerIndex; }
set { _headerIndex = value; }
}
public int DefIndex {
get { return _defIndex; }
set { _defIndex = value; }
}
public override string/*!*/ Name {
get { return _name.Name ?? ""; }
}
public NameExpression NameExpression {
get { return _name; }
}
public DecoratorStatement Decorators {
get { return _decorators; }
internal set { _decorators = value; }
}
/// <summary>
/// True if the function is a generator. Generators contain at least one yield
/// expression and instead of returning a value when called they return a generator
/// object which implements the iterator protocol.
/// </summary>
public bool IsGenerator {
get { return _generator; }
set { _generator = value; }
}
/// <summary>
/// True if the function is a coroutine. Coroutines are defined using
/// 'async def'.
/// </summary>
public bool IsCoroutine {
get { return _coroutine; }
set { _coroutine = value; }
}
/// <summary>
/// Gets the variable that this function is assigned to.
/// </summary>
public PythonVariable Variable {
get { return _variable; }
set { _variable = value; }
}
/// <summary>
/// Gets the variable reference for the specific assignment to the variable for this function definition.
/// </summary>
public PythonReference GetVariableReference(PythonAst ast) {
return GetVariableReference(this, ast);
}
internal override bool ExposesLocalVariable(PythonVariable variable) {
return NeedsLocalsDictionary;
}
internal override bool TryBindOuter(ScopeStatement from, string name, bool allowGlobals, out PythonVariable variable) {
// Functions expose their locals to direct access
ContainsNestedFreeVariables = true;
if (TryGetVariable(name, out variable)) {
variable.AccessedInNestedScope = true;
if (variable.Kind == VariableKind.Local || variable.Kind == VariableKind.Parameter) {
from.AddFreeVariable(variable, true);
for (ScopeStatement scope = from.Parent; scope != this; scope = scope.Parent) {
scope.AddFreeVariable(variable, false);
}
AddCellVariable(variable);
} else if(allowGlobals) {
from.AddReferencedGlobal(name);
}
return true;
}
return false;
}
internal override PythonVariable BindReference(PythonNameBinder binder, string name) {
PythonVariable variable;
// First try variables local to this scope
if (TryGetVariable(name, out variable) && variable.Kind != VariableKind.Nonlocal) {
if (variable.Kind == VariableKind.Global) {
AddReferencedGlobal(name);
}
return variable;
}
// Try to bind in outer scopes
for (ScopeStatement parent = Parent; parent != null; parent = parent.Parent) {
if (parent.TryBindOuter(this, name, true, out variable)) {
return variable;
}
}
return null;
}
internal override void Bind(PythonNameBinder binder) {
base.Bind(binder);
Verify(binder);
}
private void Verify(PythonNameBinder binder) {
if (ContainsImportStar && IsClosure) {
binder.ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"import * is not allowed in function '{0}' because it is a nested function",
Name),
this);
}
if (ContainsImportStar && Parent is FunctionDefinition) {
binder.ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"import * is not allowed in function '{0}' because it is a nested function",
Name),
this);
}
if (ContainsImportStar && ContainsNestedFreeVariables) {
binder.ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"import * is not allowed in function '{0}' because it contains a nested function with free variables",
Name),
this);
}
if (ContainsUnqualifiedExec && ContainsNestedFreeVariables) {
binder.ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"unqualified exec is not allowed in function '{0}' because it contains a nested function with free variables",
Name),
this);
}
if (ContainsUnqualifiedExec && IsClosure) {
binder.ReportSyntaxError(
String.Format(
System.Globalization.CultureInfo.InvariantCulture,
"unqualified exec is not allowed in function '{0}' because it is a nested function",
Name),
this);
}
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_parameters != null) {
foreach (Parameter p in _parameters) {
p.Walk(walker);
}
}
if (_decorators != null) {
_decorators.Walk(walker);
}
if (_body != null) {
_body.Walk(walker);
}
if (_returnAnnotation != null) {
_returnAnnotation.Walk(walker);
}
}
walker.PostWalk(this);
}
public SourceLocation Header {
get { return GlobalParent.IndexToLocation(_headerIndex); }
}
public override string GetLeadingWhiteSpace(PythonAst ast) {
if (Decorators != null) {
return Decorators.GetLeadingWhiteSpace(ast);
}
return base.GetLeadingWhiteSpace(ast);
}
public override void SetLeadingWhiteSpace(PythonAst ast, string whiteSpace) {
if (Decorators != null) {
Decorators.SetLeadingWhiteSpace(ast, whiteSpace);
return;
}
base.SetLeadingWhiteSpace(ast, whiteSpace);
}
internal override void AppendCodeStringStmt(StringBuilder res, PythonAst ast, CodeFormattingOptions format) {
var decorateWhiteSpace = this.GetNamesWhiteSpace(ast);
if (Decorators != null) {
Decorators.AppendCodeString(res, ast, format);
}
format.ReflowComment(res, this.GetProceedingWhiteSpaceDefaultNull(ast));
if (IsCoroutine) {
res.Append("async");
res.Append(NodeAttributes.GetWhiteSpace(this, ast, WhitespaceAfterAsync));
}
res.Append("def");
var name = this.GetVerbatimImage(ast) ?? Name;
if (!String.IsNullOrEmpty(name)) {
res.Append(this.GetSecondWhiteSpace(ast));
res.Append(name);
if (!this.IsIncompleteNode(ast)) {
format.Append(
res,
format.SpaceBeforeFunctionDeclarationParen,
" ",
"",
this.GetThirdWhiteSpaceDefaultNull(ast)
);
res.Append('(');
if (Parameters.Count != 0) {
var commaWhiteSpace = this.GetListWhiteSpace(ast);
ParamsToString(res,
ast,
commaWhiteSpace,
format,
format.SpaceWithinFunctionDeclarationParens != null ?
format.SpaceWithinFunctionDeclarationParens.Value ? " " : "" :
null
);
}
string namedOnly = this.GetExtraVerbatimText(ast);
if (namedOnly != null) {
res.Append(namedOnly);
}
if (!this.IsMissingCloseGrouping(ast)) {
format.Append(
res,
Parameters.Count != 0 ?
format.SpaceWithinFunctionDeclarationParens :
format.SpaceWithinEmptyParameterList,
" ",
"",
this.GetFourthWhiteSpaceDefaultNull(ast)
);
res.Append(')');
}
if (ReturnAnnotation != null) {
format.Append(
res,
format.SpaceAroundAnnotationArrow,
" ",
"",
this.GetFifthWhiteSpace(ast)
);
res.Append("->");
_returnAnnotation.AppendCodeString(
res,
ast,
format,
format.SpaceAroundAnnotationArrow != null ?
format.SpaceAroundAnnotationArrow.Value ? " " : "" :
null
);
}
if (Body != null) {
Body.AppendCodeString(res, ast, format);
}
}
}
}
internal void ParamsToString(StringBuilder res, PythonAst ast, string[] commaWhiteSpace, CodeFormattingOptions format, string initialLeadingWhiteSpace = null) {
for (int i = 0; i < Parameters.Count; i++) {
if (i > 0) {
if (commaWhiteSpace != null) {
res.Append(commaWhiteSpace[i - 1]);
}
res.Append(',');
}
Parameters[i].AppendCodeString(res, ast, format, initialLeadingWhiteSpace);
initialLeadingWhiteSpace = null;
}
if (commaWhiteSpace != null && commaWhiteSpace.Length == Parameters.Count && Parameters.Count != 0) {
// trailing comma
res.Append(commaWhiteSpace[commaWhiteSpace.Length - 1]);
res.Append(",");
}
}
}
}
| |
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Text;
using Thrift.Transport;
using System.Collections;
using System.IO;
using System.Collections.Generic;
namespace Thrift.Protocol
{
public class TCompactProtocol : TProtocol
{
private static TStruct ANONYMOUS_STRUCT = new TStruct("");
private static TField TSTOP = new TField("", TType.Stop, (short)0);
private static byte[] ttypeToCompactType = new byte[16];
private const byte PROTOCOL_ID = 0x82;
private const byte VERSION = 1;
private const byte VERSION_MASK = 0x1f; // 0001 1111
private const byte TYPE_MASK = 0xE0; // 1110 0000
private const byte TYPE_BITS = 0x07; // 0000 0111
private const int TYPE_SHIFT_AMOUNT = 5;
/// <summary>
/// All of the on-wire type codes.
/// </summary>
private static class Types
{
public const byte STOP = 0x00;
public const byte BOOLEAN_TRUE = 0x01;
public const byte BOOLEAN_FALSE = 0x02;
public const byte BYTE = 0x03;
public const byte I16 = 0x04;
public const byte I32 = 0x05;
public const byte I64 = 0x06;
public const byte DOUBLE = 0x07;
public const byte BINARY = 0x08;
public const byte LIST = 0x09;
public const byte SET = 0x0A;
public const byte MAP = 0x0B;
public const byte STRUCT = 0x0C;
}
/// <summary>
/// Used to keep track of the last field for the current and previous structs,
/// so we can do the delta stuff.
/// </summary>
private Stack<short> lastField_ = new Stack<short>(15);
private short lastFieldId_ = 0;
/// <summary>
/// If we encounter a boolean field begin, save the TField here so it can
/// have the value incorporated.
/// </summary>
private Nullable<TField> booleanField_;
/// <summary>
/// If we Read a field header, and it's a boolean field, save the boolean
/// value here so that ReadBool can use it.
/// </summary>
private Nullable<Boolean> boolValue_;
#region CompactProtocol Factory
public class Factory : TProtocolFactory
{
public Factory() { }
public TProtocol GetProtocol(TTransport trans)
{
return new TCompactProtocol(trans);
}
}
#endregion
public TCompactProtocol(TTransport trans)
: base(trans)
{
ttypeToCompactType[(int)TType.Stop] = Types.STOP;
ttypeToCompactType[(int)TType.Bool] = Types.BOOLEAN_TRUE;
ttypeToCompactType[(int)TType.Byte] = Types.BYTE;
ttypeToCompactType[(int)TType.I16] = Types.I16;
ttypeToCompactType[(int)TType.I32] = Types.I32;
ttypeToCompactType[(int)TType.I64] = Types.I64;
ttypeToCompactType[(int)TType.Double] = Types.DOUBLE;
ttypeToCompactType[(int)TType.String] = Types.BINARY;
ttypeToCompactType[(int)TType.List] = Types.LIST;
ttypeToCompactType[(int)TType.Set] = Types.SET;
ttypeToCompactType[(int)TType.Map] = Types.MAP;
ttypeToCompactType[(int)TType.Struct] = Types.STRUCT;
}
public void reset()
{
lastField_.Clear();
lastFieldId_ = 0;
}
#region Write Methods
/// <summary>
/// Writes a byte without any possibility of all that field header nonsense.
/// Used internally by other writing methods that know they need to Write a byte.
/// </summary>
private byte[] byteDirectBuffer = new byte[1];
private void WriteByteDirect(byte b)
{
byteDirectBuffer[0] = b;
trans.Write(byteDirectBuffer);
}
/// <summary>
/// Writes a byte without any possibility of all that field header nonsense.
/// </summary>
private void WriteByteDirect(int n)
{
WriteByteDirect((byte)n);
}
/// <summary>
/// Write an i32 as a varint. Results in 1-5 bytes on the wire.
/// TODO: make a permanent buffer like WriteVarint64?
/// </summary>
byte[] i32buf = new byte[5];
private void WriteVarint32(uint n)
{
int idx = 0;
while (true)
{
if ((n & ~0x7F) == 0)
{
i32buf[idx++] = (byte)n;
// WriteByteDirect((byte)n);
break;
// return;
}
else
{
i32buf[idx++] = (byte)((n & 0x7F) | 0x80);
// WriteByteDirect((byte)((n & 0x7F) | 0x80));
n >>= 7;
}
}
trans.Write(i32buf, 0, idx);
}
/// <summary>
/// Write a message header to the wire. Compact Protocol messages contain the
/// protocol version so we can migrate forwards in the future if need be.
/// </summary>
public override void WriteMessageBegin(TMessage message)
{
WriteByteDirect(PROTOCOL_ID);
WriteByteDirect((byte)((VERSION & VERSION_MASK) | ((((uint)message.Type) << TYPE_SHIFT_AMOUNT) & TYPE_MASK)));
WriteVarint32((uint)message.SeqID);
WriteString(message.Name);
}
/// <summary>
/// Write a struct begin. This doesn't actually put anything on the wire. We
/// use it as an opportunity to put special placeholder markers on the field
/// stack so we can get the field id deltas correct.
/// </summary>
public override void WriteStructBegin(TStruct strct)
{
lastField_.Push(lastFieldId_);
lastFieldId_ = 0;
}
/// <summary>
/// Write a struct end. This doesn't actually put anything on the wire. We use
/// this as an opportunity to pop the last field from the current struct off
/// of the field stack.
/// </summary>
public override void WriteStructEnd()
{
lastFieldId_ = lastField_.Pop();
}
/// <summary>
/// Write a field header containing the field id and field type. If the
/// difference between the current field id and the last one is small (< 15),
/// then the field id will be encoded in the 4 MSB as a delta. Otherwise, the
/// field id will follow the type header as a zigzag varint.
/// </summary>
public override void WriteFieldBegin(TField field)
{
if (field.Type == TType.Bool)
{
// we want to possibly include the value, so we'll wait.
booleanField_ = field;
}
else
{
WriteFieldBeginInternal(field, 0xFF);
}
}
/// <summary>
/// The workhorse of WriteFieldBegin. It has the option of doing a
/// 'type override' of the type header. This is used specifically in the
/// boolean field case.
/// </summary>
private void WriteFieldBeginInternal(TField field, byte typeOverride)
{
// short lastField = lastField_.Pop();
// if there's a type override, use that.
byte typeToWrite = typeOverride == 0xFF ? getCompactType(field.Type) : typeOverride;
// check if we can use delta encoding for the field id
if (field.ID > lastFieldId_ && field.ID - lastFieldId_ <= 15)
{
// Write them together
WriteByteDirect((field.ID - lastFieldId_) << 4 | typeToWrite);
}
else
{
// Write them separate
WriteByteDirect(typeToWrite);
WriteI16(field.ID);
}
lastFieldId_ = field.ID;
// lastField_.push(field.id);
}
/// <summary>
/// Write the STOP symbol so we know there are no more fields in this struct.
/// </summary>
public override void WriteFieldStop()
{
WriteByteDirect(Types.STOP);
}
/// <summary>
/// Write a map header. If the map is empty, omit the key and value type
/// headers, as we don't need any additional information to skip it.
/// </summary>
public override void WriteMapBegin(TMap map)
{
if (map.Count == 0)
{
WriteByteDirect(0);
}
else
{
WriteVarint32((uint)map.Count);
WriteByteDirect(getCompactType(map.KeyType) << 4 | getCompactType(map.ValueType));
}
}
/// <summary>
/// Write a list header.
/// </summary>
public override void WriteListBegin(TList list)
{
WriteCollectionBegin(list.ElementType, list.Count);
}
/// <summary>
/// Write a set header.
/// </summary>
public override void WriteSetBegin(TSet set)
{
WriteCollectionBegin(set.ElementType, set.Count);
}
/// <summary>
/// Write a boolean value. Potentially, this could be a boolean field, in
/// which case the field header info isn't written yet. If so, decide what the
/// right type header is for the value and then Write the field header.
/// Otherwise, Write a single byte.
/// </summary>
public override void WriteBool(Boolean b)
{
if (booleanField_ != null)
{
// we haven't written the field header yet
WriteFieldBeginInternal(booleanField_.Value, b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE);
booleanField_ = null;
}
else
{
// we're not part of a field, so just Write the value.
WriteByteDirect(b ? Types.BOOLEAN_TRUE : Types.BOOLEAN_FALSE);
}
}
/// <summary>
/// Write a byte. Nothing to see here!
/// </summary>
public override void WriteByte(sbyte b)
{
WriteByteDirect((byte)b);
}
/// <summary>
/// Write an I16 as a zigzag varint.
/// </summary>
public override void WriteI16(short i16)
{
WriteVarint32(intToZigZag(i16));
}
/// <summary>
/// Write an i32 as a zigzag varint.
/// </summary>
public override void WriteI32(int i32)
{
WriteVarint32(intToZigZag(i32));
}
/// <summary>
/// Write an i64 as a zigzag varint.
/// </summary>
public override void WriteI64(long i64)
{
WriteVarint64(longToZigzag(i64));
}
/// <summary>
/// Write a double to the wire as 8 bytes.
/// </summary>
public override void WriteDouble(double dub)
{
byte[] data = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
fixedLongToBytes(BitConverter.DoubleToInt64Bits(dub), data, 0);
trans.Write(data);
}
/// <summary>
/// Write a string to the wire with a varint size preceding.
/// </summary>
public override void WriteString(string str)
{
byte[] bytes = UTF8Encoding.UTF8.GetBytes(str);
WriteBinary(bytes, 0, bytes.Length);
}
/// <summary>
/// Write a byte array, using a varint for the size.
/// </summary>
public override void WriteBinary(byte[] bin)
{
WriteBinary(bin, 0, bin.Length);
}
private void WriteBinary(byte[] buf, int offset, int length)
{
WriteVarint32((uint)length);
trans.Write(buf, offset, length);
}
//
// These methods are called by structs, but don't actually have any wire
// output or purpose.
//
public override void WriteMessageEnd() { }
public override void WriteMapEnd() { }
public override void WriteListEnd() { }
public override void WriteSetEnd() { }
public override void WriteFieldEnd() { }
//
// Internal writing methods
//
/// <summary>
/// Abstract method for writing the start of lists and sets. List and sets on
/// the wire differ only by the type indicator.
/// </summary>
protected void WriteCollectionBegin(TType elemType, int size)
{
if (size <= 14)
{
WriteByteDirect(size << 4 | getCompactType(elemType));
}
else
{
WriteByteDirect(0xf0 | getCompactType(elemType));
WriteVarint32((uint)size);
}
}
/// <summary>
/// Write an i64 as a varint. Results in 1-10 bytes on the wire.
/// </summary>
byte[] varint64out = new byte[10];
private void WriteVarint64(ulong n)
{
int idx = 0;
while (true)
{
if ((n & ~(ulong)0x7FL) == 0)
{
varint64out[idx++] = (byte)n;
break;
}
else
{
varint64out[idx++] = ((byte)((n & 0x7F) | 0x80));
n >>= 7;
}
}
trans.Write(varint64out, 0, idx);
}
/// <summary>
/// Convert l into a zigzag long. This allows negative numbers to be
/// represented compactly as a varint.
/// </summary>
private ulong longToZigzag(long n)
{
return (ulong)(n << 1) ^ (ulong)(n >> 63);
}
/// <summary>
/// Convert n into a zigzag int. This allows negative numbers to be
/// represented compactly as a varint.
/// </summary>
private uint intToZigZag(int n)
{
return (uint)(n << 1) ^ (uint)(n >> 31);
}
/// <summary>
/// Convert a long into little-endian bytes in buf starting at off and going
/// until off+7.
/// </summary>
private void fixedLongToBytes(long n, byte[] buf, int off)
{
buf[off + 0] = (byte)(n & 0xff);
buf[off + 1] = (byte)((n >> 8) & 0xff);
buf[off + 2] = (byte)((n >> 16) & 0xff);
buf[off + 3] = (byte)((n >> 24) & 0xff);
buf[off + 4] = (byte)((n >> 32) & 0xff);
buf[off + 5] = (byte)((n >> 40) & 0xff);
buf[off + 6] = (byte)((n >> 48) & 0xff);
buf[off + 7] = (byte)((n >> 56) & 0xff);
}
#endregion
#region ReadMethods
/// <summary>
/// Read a message header.
/// </summary>
public override TMessage ReadMessageBegin()
{
byte protocolId = (byte)ReadByte();
if (protocolId != PROTOCOL_ID)
{
throw new TProtocolException("Expected protocol id " + PROTOCOL_ID.ToString("X") + " but got " + protocolId.ToString("X"));
}
byte versionAndType = (byte)ReadByte();
byte version = (byte)(versionAndType & VERSION_MASK);
if (version != VERSION)
{
throw new TProtocolException("Expected version " + VERSION + " but got " + version);
}
byte type = (byte)((versionAndType >> TYPE_SHIFT_AMOUNT) & TYPE_BITS);
int seqid = (int)ReadVarint32();
string messageName = ReadString();
return new TMessage(messageName, (TMessageType)type, seqid);
}
/// <summary>
/// Read a struct begin. There's nothing on the wire for this, but it is our
/// opportunity to push a new struct begin marker onto the field stack.
/// </summary>
public override TStruct ReadStructBegin()
{
lastField_.Push(lastFieldId_);
lastFieldId_ = 0;
return ANONYMOUS_STRUCT;
}
/// <summary>
/// Doesn't actually consume any wire data, just removes the last field for
/// this struct from the field stack.
/// </summary>
public override void ReadStructEnd()
{
// consume the last field we Read off the wire.
lastFieldId_ = lastField_.Pop();
}
/// <summary>
/// Read a field header off the wire.
/// </summary>
public override TField ReadFieldBegin()
{
byte type = (byte)ReadByte();
// if it's a stop, then we can return immediately, as the struct is over.
if (type == Types.STOP)
{
return TSTOP;
}
short fieldId;
// mask off the 4 MSB of the type header. it could contain a field id delta.
short modifier = (short)((type & 0xf0) >> 4);
if (modifier == 0)
{
// not a delta. look ahead for the zigzag varint field id.
fieldId = ReadI16();
}
else
{
// has a delta. add the delta to the last Read field id.
fieldId = (short)(lastFieldId_ + modifier);
}
TField field = new TField("", getTType((byte)(type & 0x0f)), fieldId);
// if this happens to be a boolean field, the value is encoded in the type
if (isBoolType(type))
{
// save the boolean value in a special instance variable.
boolValue_ = (byte)(type & 0x0f) == Types.BOOLEAN_TRUE ? true : false;
}
// push the new field onto the field stack so we can keep the deltas going.
lastFieldId_ = field.ID;
return field;
}
/// <summary>
/// Read a map header off the wire. If the size is zero, skip Reading the key
/// and value type. This means that 0-length maps will yield TMaps without the
/// "correct" types.
/// </summary>
public override TMap ReadMapBegin()
{
int size = (int)ReadVarint32();
byte keyAndValueType = size == 0 ? (byte)0 : (byte)ReadByte();
return new TMap(getTType((byte)(keyAndValueType >> 4)), getTType((byte)(keyAndValueType & 0xf)), size);
}
/// <summary>
/// Read a list header off the wire. If the list size is 0-14, the size will
/// be packed into the element type header. If it's a longer list, the 4 MSB
/// of the element type header will be 0xF, and a varint will follow with the
/// true size.
/// </summary>
public override TList ReadListBegin()
{
byte size_and_type = (byte)ReadByte();
int size = (size_and_type >> 4) & 0x0f;
if (size == 15)
{
size = (int)ReadVarint32();
}
TType type = getTType(size_and_type);
return new TList(type, size);
}
/// <summary>
/// Read a set header off the wire. If the set size is 0-14, the size will
/// be packed into the element type header. If it's a longer set, the 4 MSB
/// of the element type header will be 0xF, and a varint will follow with the
/// true size.
/// </summary>
public override TSet ReadSetBegin()
{
return new TSet(ReadListBegin());
}
/// <summary>
/// Read a boolean off the wire. If this is a boolean field, the value should
/// already have been Read during ReadFieldBegin, so we'll just consume the
/// pre-stored value. Otherwise, Read a byte.
/// </summary>
public override Boolean ReadBool()
{
if (boolValue_ != null)
{
bool result = boolValue_.Value;
boolValue_ = null;
return result;
}
return ReadByte() == Types.BOOLEAN_TRUE;
}
byte[] byteRawBuf = new byte[1];
/// <summary>
/// Read a single byte off the wire. Nothing interesting here.
/// </summary>
public override sbyte ReadByte()
{
trans.ReadAll(byteRawBuf, 0, 1);
return (sbyte)byteRawBuf[0];
}
/// <summary>
/// Read an i16 from the wire as a zigzag varint.
/// </summary>
public override short ReadI16()
{
return (short)zigzagToInt(ReadVarint32());
}
/// <summary>
/// Read an i32 from the wire as a zigzag varint.
/// </summary>
public override int ReadI32()
{
return zigzagToInt(ReadVarint32());
}
/// <summary>
/// Read an i64 from the wire as a zigzag varint.
/// </summary>
public override long ReadI64()
{
return zigzagToLong(ReadVarint64());
}
/// <summary>
/// No magic here - just Read a double off the wire.
/// </summary>
public override double ReadDouble()
{
byte[] longBits = new byte[8];
trans.ReadAll(longBits, 0, 8);
return BitConverter.Int64BitsToDouble(bytesToLong(longBits));
}
/// <summary>
/// Reads a byte[] (via ReadBinary), and then UTF-8 decodes it.
/// </summary>
public override string ReadString()
{
int length = (int)ReadVarint32();
if (length == 0)
{
return "";
}
return Encoding.UTF8.GetString(ReadBinary(length));
}
/// <summary>
/// Read a byte[] from the wire.
/// </summary>
public override byte[] ReadBinary()
{
int length = (int)ReadVarint32();
if (length == 0) return new byte[0];
byte[] buf = new byte[length];
trans.ReadAll(buf, 0, length);
return buf;
}
/// <summary>
/// Read a byte[] of a known length from the wire.
/// </summary>
private byte[] ReadBinary(int length)
{
if (length == 0) return new byte[0];
byte[] buf = new byte[length];
trans.ReadAll(buf, 0, length);
return buf;
}
//
// These methods are here for the struct to call, but don't have any wire
// encoding.
//
public override void ReadMessageEnd() { }
public override void ReadFieldEnd() { }
public override void ReadMapEnd() { }
public override void ReadListEnd() { }
public override void ReadSetEnd() { }
//
// Internal Reading methods
//
/// <summary>
/// Read an i32 from the wire as a varint. The MSB of each byte is set
/// if there is another byte to follow. This can Read up to 5 bytes.
/// </summary>
private uint ReadVarint32()
{
uint result = 0;
int shift = 0;
while (true)
{
byte b = (byte)ReadByte();
result |= (uint)(b & 0x7f) << shift;
if ((b & 0x80) != 0x80) break;
shift += 7;
}
return result;
}
/// <summary>
/// Read an i64 from the wire as a proper varint. The MSB of each byte is set
/// if there is another byte to follow. This can Read up to 10 bytes.
/// </summary>
private ulong ReadVarint64()
{
int shift = 0;
ulong result = 0;
while (true)
{
byte b = (byte)ReadByte();
result |= (ulong)(b & 0x7f) << shift;
if ((b & 0x80) != 0x80) break;
shift += 7;
}
return result;
}
#endregion
//
// encoding helpers
//
/// <summary>
/// Convert from zigzag int to int.
/// </summary>
private int zigzagToInt(uint n)
{
return (int)(n >> 1) ^ (-(int)(n & 1));
}
/// <summary>
/// Convert from zigzag long to long.
/// </summary>
private long zigzagToLong(ulong n)
{
return (long)(n >> 1) ^ (-(long)(n & 1));
}
/// <summary>
/// Note that it's important that the mask bytes are long literals,
/// otherwise they'll default to ints, and when you shift an int left 56 bits,
/// you just get a messed up int.
/// </summary>
private long bytesToLong(byte[] bytes)
{
return
((bytes[7] & 0xffL) << 56) |
((bytes[6] & 0xffL) << 48) |
((bytes[5] & 0xffL) << 40) |
((bytes[4] & 0xffL) << 32) |
((bytes[3] & 0xffL) << 24) |
((bytes[2] & 0xffL) << 16) |
((bytes[1] & 0xffL) << 8) |
((bytes[0] & 0xffL));
}
//
// type testing and converting
//
private Boolean isBoolType(byte b)
{
int lowerNibble = b & 0x0f;
return lowerNibble == Types.BOOLEAN_TRUE || lowerNibble == Types.BOOLEAN_FALSE;
}
/// <summary>
/// Given a TCompactProtocol.Types constant, convert it to its corresponding
/// TType value.
/// </summary>
private TType getTType(byte type)
{
switch ((byte)(type & 0x0f))
{
case Types.STOP:
return TType.Stop;
case Types.BOOLEAN_FALSE:
case Types.BOOLEAN_TRUE:
return TType.Bool;
case Types.BYTE:
return TType.Byte;
case Types.I16:
return TType.I16;
case Types.I32:
return TType.I32;
case Types.I64:
return TType.I64;
case Types.DOUBLE:
return TType.Double;
case Types.BINARY:
return TType.String;
case Types.LIST:
return TType.List;
case Types.SET:
return TType.Set;
case Types.MAP:
return TType.Map;
case Types.STRUCT:
return TType.Struct;
default:
throw new TProtocolException("don't know what type: " + (byte)(type & 0x0f));
}
}
/// <summary>
/// Given a TType value, find the appropriate TCompactProtocol.Types constant.
/// </summary>
private byte getCompactType(TType ttype)
{
return ttypeToCompactType[(int)ttype];
}
}
}
| |
// 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.Runtime;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.NativeFormat;
namespace Internal.Runtime.TypeLoader
{
public sealed partial class TypeLoaderEnvironment
{
private const int DynamicTypeTlsOffsetFlag = unchecked((int)0x80000000);
// To keep the synchronization simple, we execute all TLS registration/lookups under a global lock
private Lock _threadStaticsLock = new Lock();
// Counter to keep track of generated offsets for TLS cells of dynamic types;
private int _maxTlsCells = 0;
private LowLevelDictionary<RuntimeTypeHandle, uint> _dynamicGenericsThreadStatics = new LowLevelDictionary<RuntimeTypeHandle, uint>();
private LowLevelDictionary<uint, int> _dynamicGenericsThreadStaticSizes = new LowLevelDictionary<uint, int>();
// Various functions in static access need to create permanent pointers for use by thread static lookup.
#region GC/Non-GC Statics
/// <summary>
/// Get a pointer to the nongc static field data of a type. This function works for dynamic
/// types, reflectable types, and for all generic types
/// </summary>
public IntPtr TryGetNonGcStaticFieldDataDirect(RuntimeTypeHandle runtimeTypeHandle)
{
unsafe
{
EEType* typeAsEEType = runtimeTypeHandle.ToEETypePtr();
// Non-generic, non-dynamic types need special handling.
if (!typeAsEEType->IsDynamicType && !typeAsEEType->IsGeneric)
{
if (typeAsEEType->HasCctor)
{
// The non-gc area for a type is immediately following its cctor context if it has one
IntPtr dataAddress = TryGetStaticClassConstructionContext(runtimeTypeHandle);
if (dataAddress != IntPtr.Zero)
{
return (IntPtr)(((byte*)dataAddress.ToPointer()) + sizeof(System.Runtime.CompilerServices.StaticClassConstructionContext));
}
}
else
{
// If the type does not have a Cctor context, search for the field on the type in the field map which has the lowest offset,
// yet has the the correct type of storage.
IntPtr staticAddress;
if (TryGetStaticFieldBaseFromFieldAccessMap(runtimeTypeHandle, FieldAccessStaticDataKind.NonGC, out staticAddress))
{
return staticAddress;
}
}
}
}
IntPtr nonGcStaticsAddress;
IntPtr gcStaticsAddress;
if (TryGetStaticsInfoForNamedType(runtimeTypeHandle, out nonGcStaticsAddress, out gcStaticsAddress))
{
return nonGcStaticsAddress;
}
// The indirected helper function can be used to find all dynamic types not found via
// TryGetStaticsInfoForNamedType as well as generics
IntPtr ptrToStaticFieldData = TryGetNonGcStaticFieldData(runtimeTypeHandle);
if (ptrToStaticFieldData == IntPtr.Zero)
{
return IntPtr.Zero;
}
else
{
unsafe
{
return *(IntPtr*)ptrToStaticFieldData;
}
}
}
/// <summary>
/// Get a pointer to a pointer to the nongc static field data of a type. This function works for all generic types
/// </summary>
public IntPtr TryGetNonGcStaticFieldData(RuntimeTypeHandle runtimeTypeHandle)
{
unsafe
{
// Non-generic, non-dynamic static data is found via the FieldAccessMap
EEType* typeAsEEType = runtimeTypeHandle.ToEETypePtr();
// Non-generic, non-dynamic types need special handling.
Debug.Assert(typeAsEEType->IsDynamicType || typeAsEEType->IsGeneric);
}
// Search hashtable for static entry
ExternalReferencesTable staticInfoLookup;
var parser = GetStaticInfo(runtimeTypeHandle, out staticInfoLookup);
if (!parser.IsNull)
{
var index = parser.GetUnsignedForBagElementKind(BagElementKind.NonGcStaticData);
return index.HasValue ? staticInfoLookup.GetIntPtrFromIndex(index.Value) : IntPtr.Zero;
}
// Not found in hashtable... must be a dynamically created type
Debug.Assert(runtimeTypeHandle.IsDynamicType());
unsafe
{
EEType* typeAsEEType = runtimeTypeHandle.ToEETypePtr();
if ((typeAsEEType->RareFlags & EETypeRareFlags.IsDynamicTypeWithNonGcStatics) != 0)
{
return typeAsEEType->DynamicNonGcStaticsData;
}
}
// Type has no non-GC statics
return IntPtr.Zero;
}
/// <summary>
/// Get a pointer to the gc static field data of a type. This function works for dynamic
/// types, reflectable types, and for all generic types
/// </summary>
public IntPtr TryGetGcStaticFieldDataDirect(RuntimeTypeHandle runtimeTypeHandle)
{
unsafe
{
// Non-generic, non-dynamic static data is found via the FieldAccessMap
EEType* typeAsEEType = runtimeTypeHandle.ToEETypePtr();
// Non-generic, non-dynamic types need special handling.
if (!typeAsEEType->IsDynamicType && !typeAsEEType->IsGeneric)
{
//search for the field on the type in the field map which has the lowest offset,
// yet has the the correct type of storage.
IntPtr staticAddress;
if (TryGetStaticFieldBaseFromFieldAccessMap(runtimeTypeHandle, FieldAccessStaticDataKind.GC, out staticAddress))
{
return staticAddress;
}
else
{
return IntPtr.Zero;
}
}
}
IntPtr nonGcStaticsAddress;
IntPtr gcStaticsAddress;
if (TryGetStaticsInfoForNamedType(runtimeTypeHandle, out nonGcStaticsAddress, out gcStaticsAddress))
{
return gcStaticsAddress;
}
// The indirected helper function can be used to find all dynamic types not found via
// TryGetStaticsInfoForNamedType as well as generics
IntPtr ptrToStaticFieldData = TryGetGcStaticFieldData(runtimeTypeHandle);
if (ptrToStaticFieldData == IntPtr.Zero)
{
return IntPtr.Zero;
}
else
{
unsafe
{
return *(IntPtr*)ptrToStaticFieldData;
}
}
}
/// <summary>
/// Get a pointer to a pointer to the gc static field data of a type. This function works for all generic types
/// </summary>
public IntPtr TryGetGcStaticFieldData(RuntimeTypeHandle runtimeTypeHandle)
{
unsafe
{
// Non-generic, non-dynamic static data is found via the FieldAccessMap
EEType* typeAsEEType = runtimeTypeHandle.ToEETypePtr();
// Non-generic, non-dynamic types need special handling.
Debug.Assert(typeAsEEType->IsDynamicType || typeAsEEType->IsGeneric);
}
// Search hashtable for static entry
ExternalReferencesTable staticInfoLookup;
var parser = GetStaticInfo(runtimeTypeHandle, out staticInfoLookup);
if (!parser.IsNull)
{
var index = parser.GetUnsignedForBagElementKind(BagElementKind.GcStaticData);
return index.HasValue ? staticInfoLookup.GetIntPtrFromIndex(index.Value) : IntPtr.Zero;
}
// Not found in hashtable... must be a dynamically created type
Debug.Assert(runtimeTypeHandle.IsDynamicType());
unsafe
{
EEType* typeAsEEType = runtimeTypeHandle.ToEETypePtr();
if ((typeAsEEType->RareFlags & EETypeRareFlags.IsDynamicTypeWithGcStatics) != 0)
{
return typeAsEEType->DynamicGcStaticsData;
}
}
// Type has no GC statics
return IntPtr.Zero;
}
#endregion
#region Thread Statics
public int TryGetThreadStaticsSizeForDynamicType(int index, out int numTlsCells)
{
Debug.Assert((index & DynamicTypeTlsOffsetFlag) == DynamicTypeTlsOffsetFlag);
numTlsCells = _maxTlsCells;
using (LockHolder.Hold(_threadStaticsLock))
{
int storageSize;
if (_dynamicGenericsThreadStaticSizes.TryGetValue((uint)index, out storageSize))
return storageSize;
}
Debug.Assert(false);
return 0;
}
public uint GetNextThreadStaticsOffsetValue()
{
// Highest bit of the TLS offset used as a flag to indicate that it's a special TLS offset of a dynamic type
var result = 0x80000000 | (uint)_maxTlsCells;
// Use checked arithmetics to ensure there aren't any overflows/truncations
_maxTlsCells = checked(_maxTlsCells + 1);
return result;
}
public void RegisterDynamicThreadStaticsInfo(RuntimeTypeHandle runtimeTypeHandle, uint offsetValue, int storageSize)
{
bool registered = false;
Debug.Assert(offsetValue != 0 && storageSize > 0 && runtimeTypeHandle.IsDynamicType());
_threadStaticsLock.Acquire();
try
{
// Sanity check to make sure we do not register thread statics for the same type more than once
uint temp;
Debug.Assert(!_dynamicGenericsThreadStatics.TryGetValue(runtimeTypeHandle, out temp) && storageSize > 0);
_dynamicGenericsThreadStatics.Add(runtimeTypeHandle, offsetValue);
_dynamicGenericsThreadStaticSizes.Add(offsetValue, storageSize);
registered = true;
}
finally
{
if (!registered)
{
_dynamicGenericsThreadStatics.Remove(runtimeTypeHandle);
_dynamicGenericsThreadStaticSizes.Remove(offsetValue);
}
_threadStaticsLock.Release();
}
}
public unsafe IntPtr TryGetTlsIndexDictionaryCellForType(RuntimeTypeHandle runtimeTypeHandle)
{
IntPtr result;
if ((result = TryGetTlsIndexDictionaryCellForStaticType(runtimeTypeHandle)) == IntPtr.Zero)
if ((result = TryGetTlsIndexDictionaryCellForDynamicType(runtimeTypeHandle)) == IntPtr.Zero)
return IntPtr.Zero;
return result;
}
public IntPtr TryGetTlsOffsetDictionaryCellForType(RuntimeTypeHandle runtimeTypeHandle)
{
IntPtr result;
if ((result = TryGetTlsOffsetDictionaryCellForStaticType(runtimeTypeHandle)) == IntPtr.Zero)
if ((result = TryGetTlsOffsetDictionaryCellForDynamicType(runtimeTypeHandle)) == IntPtr.Zero)
return IntPtr.Zero;
return result;
}
#endregion
#region Privates
// get the statics hash table, external references, and static info table for a module
// TODO multi-file: consider whether we want to cache this info
private unsafe bool GetStaticsInfoHashtable(NativeFormatModuleInfo module, out NativeHashtable staticsInfoHashtable, out ExternalReferencesTable externalReferencesLookup, out ExternalReferencesTable staticInfoLookup)
{
byte* pBlob;
uint cbBlob;
staticsInfoHashtable = default(NativeHashtable);
externalReferencesLookup = default(ExternalReferencesTable);
staticInfoLookup = default(ExternalReferencesTable);
// Load statics info hashtable
if (!module.TryFindBlob(ReflectionMapBlob.StaticsInfoHashtable, out pBlob, out cbBlob))
return false;
NativeReader reader = new NativeReader(pBlob, cbBlob);
NativeParser parser = new NativeParser(reader, 0);
if (!externalReferencesLookup.InitializeNativeReferences(module))
return false;
if (!staticInfoLookup.InitializeNativeStatics(module))
return false;
staticsInfoHashtable = new NativeHashtable(parser);
return true;
}
private NativeParser GetStaticInfo(RuntimeTypeHandle instantiatedType, out ExternalReferencesTable staticsInfoLookup)
{
TypeManagerHandle moduleHandle = RuntimeAugments.GetModuleFromTypeHandle(instantiatedType);
NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(moduleHandle);
NativeHashtable staticsInfoHashtable;
ExternalReferencesTable externalReferencesLookup;
if (!GetStaticsInfoHashtable(module, out staticsInfoHashtable, out externalReferencesLookup, out staticsInfoLookup))
return new NativeParser();
int lookupHashcode = instantiatedType.GetHashCode();
var enumerator = staticsInfoHashtable.Lookup(lookupHashcode);
NativeParser entryParser;
while (!(entryParser = enumerator.GetNext()).IsNull)
{
RuntimeTypeHandle parsedInstantiatedType = externalReferencesLookup.GetRuntimeTypeHandleFromIndex(entryParser.GetUnsigned());
if (!parsedInstantiatedType.Equals(instantiatedType))
continue;
return entryParser;
}
return new NativeParser();
}
private unsafe IntPtr TryCreateDictionaryCellWithValue(uint value)
{
return PermanentAllocatedMemoryBlobs.GetPointerToUInt(value);
}
public unsafe bool TryGetThreadStaticStartOffset(RuntimeTypeHandle runtimeTypeHandle, out int threadStaticsStartOffset)
{
threadStaticsStartOffset = -1;
if (runtimeTypeHandle.IsDynamicType())
{
// Specific TLS storage is allocated for each dynamic type. There is no starting offset since it's not a
// TLS storage block shared by multiple types.
threadStaticsStartOffset = 0;
return true;
}
else
{
IntPtr ptrToTlsOffset = TryGetTlsOffsetDictionaryCellForStaticType(runtimeTypeHandle);
if (ptrToTlsOffset == IntPtr.Zero)
return false;
threadStaticsStartOffset = *(int*)ptrToTlsOffset;
return true;
}
}
private IntPtr TryGetTlsIndexDictionaryCellForStaticType(RuntimeTypeHandle runtimeTypeHandle)
{
// Search hashtable for static entry
ExternalReferencesTable staticsInfoLookup;
var parser = GetStaticInfo(runtimeTypeHandle, out staticsInfoLookup);
if (!parser.IsNull)
{
var index = parser.GetUnsignedForBagElementKind(BagElementKind.ThreadStaticIndex);
return index.HasValue ? staticsInfoLookup.GetIntPtrFromIndex(index.Value) : IntPtr.Zero;
}
return IntPtr.Zero;
}
private IntPtr TryGetTlsOffsetDictionaryCellForStaticType(RuntimeTypeHandle runtimeTypeHandle)
{
// Search hashtable for static entry
ExternalReferencesTable staticsInfoLookup;
var parser = GetStaticInfo(runtimeTypeHandle, out staticsInfoLookup);
if (!parser.IsNull)
{
var index = parser.GetUnsignedForBagElementKind(BagElementKind.ThreadStaticOffset);
return index.HasValue ? staticsInfoLookup.GetIntPtrFromIndex(index.Value) : IntPtr.Zero;
}
return IntPtr.Zero;
}
private IntPtr TryGetTlsIndexDictionaryCellForDynamicType(RuntimeTypeHandle runtimeTypeHandle)
{
// Use TLS index of 0 for dynamic types (the index won't really be used)
Debug.Assert(runtimeTypeHandle.IsDynamicType());
return TryCreateDictionaryCellWithValue(0);
}
private IntPtr TryGetTlsOffsetDictionaryCellForDynamicType(RuntimeTypeHandle runtimeTypeHandle)
{
Debug.Assert(runtimeTypeHandle.IsDynamicType());
using (LockHolder.Hold(_threadStaticsLock))
{
uint offsetValue;
if (_dynamicGenericsThreadStatics.TryGetValue(runtimeTypeHandle, out offsetValue))
return TryCreateDictionaryCellWithValue(offsetValue);
}
return IntPtr.Zero;
}
#endregion
}
}
| |
// Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Collections.Generic;
using System.Globalization;
using NodaTime.Calendars;
using NodaTime.Globalization;
using NodaTime.Test.Text;
using NUnit.Framework;
namespace NodaTime.Test.Globalization
{
public class NodaFormatInfoTest
{
private static readonly CultureInfo enUs = CultureInfo.GetCultureInfo("en-US");
private static readonly CultureInfo enGb = CultureInfo.GetCultureInfo("en-GB");
// Just check we can actually build a NodaFormatInfo for every culture, outside
// text-specific tests.
[Test]
[TestCaseSource(typeof(Cultures), nameof(Cultures.AllCultures))]
public void ConvertCulture(CultureInfo culture)
{
NodaFormatInfo.GetFormatInfo(culture);
}
[Test]
public void TestCachingWithReadOnly()
{
var original = new CultureInfo("en-US");
// Use a read-only wrapper so that it gets cached
var wrapper = CultureInfo.ReadOnly(original);
var nodaWrapper1 = NodaFormatInfo.GetFormatInfo(wrapper);
var nodaWrapper2 = NodaFormatInfo.GetFormatInfo(wrapper);
Assert.AreSame(nodaWrapper1, nodaWrapper2);
}
[Test]
public void TestCachingWithClonedCulture()
{
var original = new CultureInfo("en-US");
var clone = (CultureInfo) original.Clone();
Assert.AreEqual(original.Name, clone.Name);
var dayNames = clone.DateTimeFormat.DayNames;
dayNames[1] = "@@@";
clone.DateTimeFormat.DayNames = dayNames;
// Fool Noda Time into believing both are read-only, so it can use a cache...
original = CultureInfo.ReadOnly(original);
clone = CultureInfo.ReadOnly(clone);
var nodaOriginal = NodaFormatInfo.GetFormatInfo(original);
var nodaClone = NodaFormatInfo.GetFormatInfo(clone);
Assert.AreEqual(original.DateTimeFormat.DayNames[1], nodaOriginal.LongDayNames[1]);
Assert.AreEqual(clone.DateTimeFormat.DayNames[1], nodaClone.LongDayNames[1]);
// Just check we made a difference...
Assert.AreNotEqual(nodaOriginal.LongDayNames[1], nodaClone.LongDayNames[1]);
}
[Test]
public void TestConstructor()
{
var info = new NodaFormatInfo(enUs);
Assert.AreSame(enUs, info.CultureInfo);
Assert.NotNull(info.DateTimeFormat);
Assert.AreEqual(":", info.TimeSeparator);
Assert.AreEqual("/", info.DateSeparator);
Assert.IsInstanceOf<string>(info.OffsetPatternLong);
Assert.IsInstanceOf<string>(info.OffsetPatternMedium);
Assert.IsInstanceOf<string>(info.OffsetPatternShort);
Assert.AreEqual("NodaFormatInfo[en-US]", info.ToString());
}
[Test]
public void TestConstructor_null()
{
Assert.Throws<ArgumentNullException>(() => new NodaFormatInfo(null!));
}
[Test]
public void TestDateTimeFormat()
{
var format = DateTimeFormatInfo.InvariantInfo;
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(format, info.DateTimeFormat);
}
[Test]
public void TestGetFormatInfo()
{
NodaFormatInfo.ClearCache();
var info1 = NodaFormatInfo.GetFormatInfo(enUs);
Assert.NotNull(info1);
var info2 = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreSame(info1, info2);
var info3 = NodaFormatInfo.GetFormatInfo(enGb);
Assert.AreNotSame(info1, info3);
}
[Test]
public void TestGetFormatInfo_null()
{
NodaFormatInfo.ClearCache();
Assert.Throws<ArgumentNullException>(() => NodaFormatInfo.GetFormatInfo(null!));
}
[Test]
public void TestGetInstance_CultureInfo()
{
NodaFormatInfo.ClearCache();
using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance))
{
var actual = NodaFormatInfo.GetInstance(enGb);
Assert.AreSame(enGb, actual.CultureInfo);
}
}
[Test]
public void TestGetInstance_UnusableType()
{
NodaFormatInfo.ClearCache();
Assert.Throws<ArgumentException>(() => NodaFormatInfo.GetInstance(CultureInfo.InvariantCulture.NumberFormat));
}
[Test]
public void TestGetInstance_DateTimeFormatInfo()
{
NodaFormatInfo.ClearCache();
using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance))
{
var info = NodaFormatInfo.GetInstance(enGb.DateTimeFormat);
Assert.AreEqual(enGb.DateTimeFormat, info.DateTimeFormat);
Assert.AreEqual(CultureInfo.InvariantCulture, info.CultureInfo);
}
}
[Test]
public void TestGetInstance_null()
{
NodaFormatInfo.ClearCache();
using (CultureSaver.SetCultures(enUs, FailingCultureInfo.Instance))
{
var info = NodaFormatInfo.GetInstance(null);
Assert.AreEqual(CultureInfo.CurrentCulture, info.CultureInfo);
}
using (CultureSaver.SetCultures(enGb, FailingCultureInfo.Instance))
{
var info = NodaFormatInfo.GetInstance(null);
Assert.AreEqual(CultureInfo.CurrentCulture, info.CultureInfo);
}
}
[Test]
public void TestOffsetPatternLong()
{
const string pattern = "This is a test";
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(pattern, info.OffsetPatternLong);
}
[Test]
public void TestOffsetPatternMedium()
{
const string pattern = "This is a test";
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(pattern, info.OffsetPatternMedium);
}
[Test]
public void TestOffsetPatternShort()
{
const string pattern = "This is a test";
var info = new NodaFormatInfo(enUs);
Assert.AreNotEqual(pattern, info.OffsetPatternShort);
}
[Test]
public void TestGetEraNames()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
IReadOnlyList<string> names = info.GetEraNames(Era.BeforeCommon);
CollectionAssert.AreEqual(new[] { "B.C.E.", "B.C.", "BCE", "BC" }, names);
}
[Test]
public void TestGetEraNames_NoSuchEra()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreEqual(0, info.GetEraNames(new Era("Ignored", "NonExistantResource")).Count);
}
[Test]
public void TestEraGetNames_Null()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.Throws<ArgumentNullException>(() => info.GetEraNames(null!));
}
[Test]
public void TestGetEraPrimaryName()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreEqual("B.C.", info.GetEraPrimaryName(Era.BeforeCommon));
}
[Test]
public void TestGetEraPrimaryName_NoSuchEra()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.AreEqual("", info.GetEraPrimaryName(new Era("Ignored", "NonExistantResource")));
}
[Test]
public void TestEraGetEraPrimaryName_Null()
{
var info = NodaFormatInfo.GetFormatInfo(enUs);
Assert.Throws<ArgumentNullException>(() => info.GetEraPrimaryName(null!));
}
[Test]
public void TestIntegerGenitiveMonthNames()
{
// Emulate behavior of Mono 3.0.6
var culture = (CultureInfo) CultureInfo.InvariantCulture.Clone();
culture.DateTimeFormat.MonthGenitiveNames = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
culture.DateTimeFormat.AbbreviatedMonthGenitiveNames = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
var info = NodaFormatInfo.GetFormatInfo(culture);
CollectionAssert.AreEqual(info.LongMonthGenitiveNames, info.LongMonthNames);
CollectionAssert.AreEqual(info.ShortMonthGenitiveNames, info.ShortMonthNames);
}
}
}
| |
#region
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Tabster.Core.Types;
using Tabster.Printing;
#endregion
namespace Tabster.WinForms
{
public abstract class TablatureTextEditorBase : Control
{
protected TablatureTextEditorBase(TextBoxBase textBoxBase)
{
TextBoxBase = textBoxBase;
TextBoxBase.KeyDown += TextBoxBase_KeyDown;
TextBoxBase.ModifiedChanged += TextBoxBase_ModifiedChanged;
Controls.Add(textBoxBase);
}
protected TextBoxBase TextBoxBase { get; private set; }
public new Font Font
{
get { return TextBoxBase.Font; }
set { TextBoxBase.Font = value; }
}
private void TextBoxBase_ModifiedChanged(object sender, EventArgs e)
{
if (ContentsModified != null)
{
ContentsModified(this, EventArgs.Empty);
}
}
private void TextBoxBase_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.A))
{
TextBoxBase.SelectAll();
e.Handled = true;
}
}
public void ScrollToPosition(int position)
{
TextBoxBase.SelectionStart = position;
TextBoxBase.ScrollToCaret();
}
public void ScrollToLine(int finish)
{
var position = 0;
for (var i = 0; i < finish && i < TextBoxBase.Lines.Length; i++)
{
position += TextBoxBase.Lines[i].Length;
position += Environment.NewLine.Length;
}
ScrollToPosition(position);
}
public virtual void LoadTablature(IAsciiTablature tablature)
{
TextBoxBase.Text = tablature.Contents;
if (TablatureLoaded != null)
{
TablatureLoaded(this, EventArgs.Empty);
}
}
public void Clear()
{
TextBoxBase.Clear();
}
public new void Focus()
{
Focus(true);
}
public void Focus(bool selectAll)
{
TextBoxBase.Focus();
if (!selectAll)
TextBoxBase.Select(0, 0);
}
#region Properties
public new Color ForeColor
{
get { return TextBoxBase.ForeColor; }
set { TextBoxBase.ForeColor = value; }
}
public new Color BackColor
{
get { return TextBoxBase.BackColor; }
set { TextBoxBase.BackColor = value; }
}
public new string Text
{
get { return TextBoxBase.Text; }
set { TextBoxBase.Text = value; }
}
public bool ReadOnly
{
get { return TextBoxBase.ReadOnly; }
set
{
TextBoxBase.ReadOnly = value;
TextBoxBase.BackColor = SystemColors.Window;
}
}
public float FontSize
{
get { return TextBoxBase.Font.Size; }
set
{
if (value <= 0)
return;
TextBoxBase.Font = new Font(TextBoxBase.Font.FontFamily, value);
}
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool HasScrollableContents
{
get
{
var size = TextRenderer.MeasureText(TextBoxBase.Text, TextBoxBase.Font);
return size.Width >= TextBoxBase.Width || size.Height >= TextBoxBase.Height;
}
}
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Modified
{
get { return TextBoxBase.Modified; }
set { TextBoxBase.Modified = value; }
}
#endregion
#region Events
public event EventHandler ContentsModified;
public event EventHandler TablatureLoaded;
#endregion
#region Printing
public void PrintPreview(TablaturePrintDocumentSettings settings = null)
{
var documentName = string.Format("Tablature File {0}", DateTime.Now);
using (
var printDocument = new TablaturePrintDocument(new AttributedTablature {Contents = Text},
TextBoxBase.Font)
{
DocumentName = documentName,
Settings = settings ?? new TablaturePrintDocumentSettings()
})
{
using (var dialog = new PrintPreviewDialog {Document = printDocument})
{
if (dialog.ShowDialog() == DialogResult.OK)
{
printDocument.Print();
}
}
}
}
public void Print(TablaturePrintDocumentSettings settings = null)
{
var documentName = string.Format("Tablature File {0}", DateTime.Now);
using (
var printDocument = new TablaturePrintDocument(new AttributedTablature {Contents = Text},
TextBoxBase.Font)
{
DocumentName = documentName,
Settings = settings ?? new TablaturePrintDocumentSettings()
})
{
printDocument.Print();
}
}
#endregion
}
}
| |
using System;
using Skybrud.Social.Http;
using Skybrud.Social.Twitter.Endpoints.Raw;
using Skybrud.Social.Twitter.Objects;
using Skybrud.Social.Twitter.Options;
using Skybrud.Social.Twitter.Responses;
namespace Skybrud.Social.Twitter.Endpoints {
public class TwitterStatusesEndpoint {
#region Properties
/// <summary>
/// Gets a reference to the Twitter service.
/// </summary>
public TwitterService Service { get; private set; }
/// <summary>
/// Gets a reference to the raw endpoint.
/// </summary>
public TwitterStatusesRawEndpoint Raw {
get { return Service.Client.Statuses; }
}
#endregion
#region Constructors
internal TwitterStatusesEndpoint(TwitterService service) {
Service = service;
}
#endregion
#region Member methods
/// <summary>
/// Gets information about a status message (tweet) with the specified ID.
/// </summary>
/// <param name="statusId">The ID of the status message.</param>
public TwitterStatusMessageResponse GetStatusMessage(long statusId) {
return TwitterStatusMessageResponse.ParseResponse(Raw.GetStatusMessage(new TwitterStatusMessageOptions(statusId)));
}
/// <summary>
/// Gets information about a status message (tweet) with the specified ID.
/// </summary>
/// <param name="options">Options affecting the response from the Twitter API.</param>
public TwitterStatusMessageResponse GetStatusMessage(TwitterStatusMessageOptions options) {
return TwitterStatusMessageResponse.ParseResponse(Raw.GetStatusMessage(options));
}
/// <summary>
/// Posts the specified status message.
/// </summary>
/// <param name="status">The status message to send.</param>
public TwitterStatusMessageResponse PostStatusMessage(string status) {
return TwitterStatusMessageResponse.ParseResponse(Raw.PostStatusMessage(status));
}
/// <summary>
/// Posts the specified status message.
/// </summary>
/// <param name="status">The status message to send.</param>
/// <param name="replyTo">The ID of the status message to reply to.</param>
public TwitterStatusMessageResponse PostStatusMessage(string status, long? replyTo) {
return TwitterStatusMessageResponse.ParseResponse(Raw.PostStatusMessage(status, replyTo));
}
/// <summary>
/// Posts the specified status message.
/// </summary>
/// <param name="options">The options for the call to the API.</param>
public TwitterStatusMessageResponse PostStatusMessage(TwitterPostStatusMessageOptions options) {
return TwitterStatusMessageResponse.ParseResponse(Raw.PostStatusMessage(options));
}
/// <summary>
/// Gets the timeline of the user with the specified <code>userId</code>.
/// </summary>
/// <param name="userId">The ID of the user.</param>
/// <param name="count">The maximum amount of tweets to return.</param>
public TwitterTimelineResponse GetUserTimeline(long userId, int count) {
return TwitterTimelineResponse.ParseResponse(Raw.GetUserTimeline(userId, count));
}
/// <summary>
/// Gets the timeline of the user with the specified <code>userId</code>.
/// </summary>
/// <param name="userId">The ID of the user.</param>
public TwitterTimelineResponse GetUserTimeline(long userId) {
return TwitterTimelineResponse.ParseResponse(Raw.GetUserTimeline(userId));
}
/// <summary>
/// Gets the timeline of the user with the specified <code>userId</code>.
/// </summary>
/// <param name="screenName">The screen name of the user.</param>
public TwitterTimelineResponse GetUserTimeline(string screenName) {
return TwitterTimelineResponse.ParseResponse(Raw.GetUserTimeline(screenName));
}
/// <summary>
/// Gets the timeline of the user with the specified <code>userId</code>.
/// </summary>
/// <param name="screenName">The screen name of the user.</param>
/// <param name="count">The maximum amount of tweets to return.</param>
public TwitterTimelineResponse GetUserTimeline(string screenName, int count) {
return TwitterTimelineResponse.ParseResponse(Raw.GetUserTimeline(screenName, count));
}
/// <summary>
/// Gets the timeline of a user with the specified <code>options</code>.
/// </summary>
/// <param name="options">The options for the call to the API.</param>
public TwitterTimelineResponse GetUserTimeline(TwitterUserTimelineOptions options) {
return TwitterTimelineResponse.ParseResponse(Raw.GetUserTimeline(options));
}
/// <summary>
/// Gets a collection of the most recent tweets and retweets posted by the authenticating
/// user and the users they follow.
/// </summary>
public TwitterTimelineResponse GetHomeTimeline() {
return TwitterTimelineResponse.ParseResponse(Raw.GetHomeTimeline());
}
/// <summary>
/// Gets a collection of the most recent tweets and retweets posted by the authenticating
/// user and the users they follow.
/// </summary>
/// <param name="count">The maximum amount of tweets to return.</param>
public TwitterTimelineResponse GetHomeTimeline(int count) {
return TwitterTimelineResponse.ParseResponse(Raw.GetHomeTimeline(count));
}
/// <summary>
/// Gets a collection of the most recent Tweets and retweets posted by the authenticating
/// user and the users they follow.
/// </summary>
/// <param name="options">The options for the call.</param>
public TwitterTimelineResponse GetHomeTimeline(TwitterTimelineOptions options) {
return TwitterTimelineResponse.ParseResponse(Raw.GetHomeTimeline(options));
}
/// <summary>
/// Gets the most recent mentions (tweets containing the users's @screen_name) for the authenticating user.
/// </summary>
public TwitterTimelineResponse GetMentionsTimeline() {
return TwitterTimelineResponse.ParseResponse(Raw.GetMentionsTimeline());
}
/// <summary>
/// Gets the most recent mentions (tweets containing the users's @screen_name) for the authenticating user.
/// </summary>
/// <param name="count">The maximum amount of tweets to return.</param>
public TwitterTimelineResponse GetMentionsTimeline(int count) {
return TwitterTimelineResponse.ParseResponse(Raw.GetMentionsTimeline(count));
}
/// <summary>
/// Gets the most recent mentions (tweets containing the users's @screen_name) for the authenticating user.
/// </summary>
/// <param name="options">The options for the call to the API.</param>
public TwitterTimelineResponse GetMentionsTimeline(TwitterTimelineOptions options) {
return TwitterTimelineResponse.ParseResponse(Raw.GetMentionsTimeline(options));
}
/// <summary>
/// Returns the most recent tweets authored by the authenticating user that have been retweeted by others.
/// </summary>
public TwitterTimelineResponse GetRetweetsOfMe() {
return TwitterTimelineResponse.ParseResponse(Raw.GetRetweetsOfMe());
}
/// <summary>
/// Returns the most recent tweets authored by the authenticating user that have been retweeted by others.
/// </summary>
/// <param name="count">The maximum amount of tweets to return.</param>
public TwitterTimelineResponse GetRetweetsOfMe(int count) {
return TwitterTimelineResponse.ParseResponse(Raw.GetRetweetsOfMe(count));
}
/// <summary>
/// Returns the most recent tweets authored by the authenticating user that have been retweeted by others.
/// </summary>
/// <param name="options">The options for the call.</param>
public TwitterTimelineResponse GetRetweetsOfMe(TwitterTimelineOptions options) {
return TwitterTimelineResponse.ParseResponse(Raw.GetRetweetsOfMe(options));
}
/// <summary>
/// Retweets the status with the specified <code>id</code>.
/// </summary>
/// <param name="id">The ID of the tweet to be retweeted.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse Retweet(long id) {
return Retweet(id, false);
}
/// <summary>
/// Retweets the status with the specified <code>id</code>.
/// </summary>
/// <param name="id">The ID of the tweet to be retweeted.</param>
/// <param name="trimUser">When set to <code>true</code>, each tweet returned in a timeline will include a user
/// object including only the status authors numerical ID. Omit this parameter to receive the complete user
/// object.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse Retweet(long id, bool trimUser) {
return TwitterStatusMessageResponse.ParseResponse(Raw.Retweet(id, trimUser));
}
/// <summary>
/// Retweets the specified <code>status</code>.
/// </summary>
/// <param name="status">The tweet to be retweeted.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse Retweet(TwitterStatusMessage status) {
if (status == null) throw new ArgumentNullException("status");
return Retweet(status.Id, false);
}
/// <summary>
/// Retweets the specified <code>status</code>.
/// </summary>
/// <param name="status">The status to be retweeted.</param>
/// <param name="trimUser">When set to <code>true</code>, each tweet returned in a timeline will include a user
/// object including only the status authors numerical ID. Omit this parameter to receive the complete user
/// object.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse Retweet(TwitterStatusMessage status, bool trimUser) {
if (status == null) throw new ArgumentNullException("status");
return Retweet(status.Id, trimUser);
}
/// <summary>
/// Destroys the status with the specified <code>id</code>. The authenticating user must be the author of the
/// specified status. Returns the destroyed status if successful.
/// </summary>
/// <param name="id">The ID of the status to be destroyed.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse DestroyStatusMessage(long id) {
return DestroyStatusMessage(id, false);
}
/// <summary>
/// Destroys the status with the specified <code>id</code>. The authenticating user must be the author of the
/// specified status. Returns the destroyed status if successful.
/// </summary>
/// <param name="id">The ID of the status to be destroyed.</param>
/// <param name="trimUser">When set to <code>true</code>, each tweet returned in a timeline will include a user
/// object including only the status authors numerical ID. Omit this parameter to receive the complete user
/// object.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse DestroyStatusMessage(long id, bool trimUser) {
return TwitterStatusMessageResponse.ParseResponse(Raw.DestroyStatusMessage(id, trimUser));
}
/// <summary>
/// Destroys the specified <code>status</code>. The authenticating user must be the author of the
/// specified status. Returns the destroyed status if successful.
/// </summary>
/// <param name="status">The status to be destroyed.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse DestroyStatusMessage(TwitterStatusMessage status) {
if (status == null) throw new ArgumentNullException("status");
return DestroyStatusMessage(status.Id, false);
}
/// <summary>
/// Destroys the status with the specified <code>id</code>. The authenticating user must be the author of the
/// specified status. Returns the destroyed status if successful.
/// </summary>
/// <param name="status">The status to be destroyed.</param>
/// <param name="trimUser">When set to <code>true</code>, each tweet returned in a timeline will include a user
/// object including only the status authors numerical ID. Omit this parameter to receive the complete user
/// object.</param>
/// <returns>Returns the response from the API.</returns>
public TwitterStatusMessageResponse DestroyStatusMessage(TwitterStatusMessage status, bool trimUser) {
if (status == null) throw new ArgumentNullException("status");
return DestroyStatusMessage(status.Id, trimUser);
}
#endregion
}
}
| |
using UnityEngine;
using System;
public class FSprite : FFacetElementNode
{
public static float defaultAnchorX = 0.5f;
public static float defaultAnchorY = 0.5f;
protected Color _color = Futile.white;
protected Color _alphaColor = Futile.white;
protected Vector2[] _localVertices;
protected float _anchorX = defaultAnchorX;
protected float _anchorY = defaultAnchorY;
protected Rect _localRect; //localRect is the TRIMMED rect
protected Rect _textureRect; //textureRect is the UN-TRIMMED rect
protected bool _isMeshDirty = false;
protected bool _areLocalVerticesDirty = false;
protected FSprite() : base() //for overriding
{
_localVertices = new Vector2[4];
}
public FSprite (string elementName) : this(Futile.atlasManager.GetElementWithName(elementName))
{
}
public FSprite (FAtlasElement element) : base()
{
_localVertices = new Vector2[4];
Init(FFacetType.Quad, element,1);
_isAlphaDirty = true;
UpdateLocalVertices();
}
override public void HandleElementChanged()
{
_areLocalVerticesDirty = true;
UpdateLocalVertices();
}
override public void Redraw(bool shouldForceDirty, bool shouldUpdateDepth)
{
bool wasMatrixDirty = _isMatrixDirty;
bool wasAlphaDirty = _isAlphaDirty;
UpdateDepthMatrixAlpha(shouldForceDirty, shouldUpdateDepth);
if(shouldUpdateDepth)
{
UpdateFacets();
}
if(wasMatrixDirty || shouldForceDirty || shouldUpdateDepth)
{
_isMeshDirty = true;
}
if(wasAlphaDirty || shouldForceDirty)
{
_isMeshDirty = true;
_color.ApplyMultipliedAlpha(ref _alphaColor, _concatenatedAlpha);
}
if(_areLocalVerticesDirty)
{
UpdateLocalVertices();
}
if(_isMeshDirty)
{
PopulateRenderLayer();
}
}
virtual public void UpdateLocalVertices()
{
_areLocalVerticesDirty = false;
_textureRect.width = _element.sourceSize.x;
_textureRect.height = _element.sourceSize.y;
_textureRect.x = -_anchorX*_textureRect.width;
_textureRect.y = -_anchorY*_textureRect.height;
float sourceWidth = _element.sourceRect.width;
float sourceHeight = _element.sourceRect.height;
float left = _textureRect.x + _element.sourceRect.x;
float bottom = _textureRect.y + (_textureRect.height - _element.sourceRect.y - _element.sourceRect.height);
_localRect.x = left;
_localRect.y = bottom;
_localRect.width = sourceWidth;
_localRect.height = sourceHeight;
_localVertices[0].Set(left,bottom + sourceHeight);
_localVertices[1].Set(left + sourceWidth,bottom + sourceHeight);
_localVertices[2].Set(left + sourceWidth,bottom);
_localVertices[3].Set(left,bottom);
_isMeshDirty = true;
}
override public void PopulateRenderLayer()
{
if(_isOnStage && _firstFacetIndex != -1)
{
_isMeshDirty = false;
int vertexIndex0 = _firstFacetIndex*4;
int vertexIndex1 = vertexIndex0 + 1;
int vertexIndex2 = vertexIndex0 + 2;
int vertexIndex3 = vertexIndex0 + 3;
Vector3[] vertices = _renderLayer.vertices;
Vector2[] uvs = _renderLayer.uvs;
Color[] colors = _renderLayer.colors;
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0], _localVertices[0],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex1], _localVertices[1],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex2], _localVertices[2],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex3], _localVertices[3],0);
uvs[vertexIndex0] = _element.uvTopLeft;
uvs[vertexIndex1] = _element.uvTopRight;
uvs[vertexIndex2] = _element.uvBottomRight;
uvs[vertexIndex3] = _element.uvBottomLeft;
colors[vertexIndex0] = _alphaColor;
colors[vertexIndex1] = _alphaColor;
colors[vertexIndex2] = _alphaColor;
colors[vertexIndex3] = _alphaColor;
_renderLayer.HandleVertsChange();
}
}
//Note: this does not consider rotation at all!
public Rect GetTextureRectRelativeToContainer()
{
return _textureRect.CloneAndScaleThenOffset(_scaleX,_scaleY,_x,_y);
}
virtual public Rect textureRect //the full rect as if the sprite hadn't been trimmed
{
get {return _textureRect;}
}
[Obsolete("FSprite's boundsRect is obsolete, use textureRect instead")]
public Rect boundsRect
{
get {throw new NotSupportedException("boundsRect is obsolete! Use textureRect instead");}
}
virtual public Rect localRect //the rect of the actual trimmed quad drawn on screen
{
get {return _localRect;}
}
virtual public Color color
{
get { return _color; }
set
{
if(_color != value)
{
_color = value;
_isAlphaDirty = true;
}
}
}
virtual public float width
{
get { return _scaleX * _textureRect.width; }
set { _scaleX = value/_textureRect.width; _isMatrixDirty = true; }
}
virtual public float height
{
get { return _scaleY * _textureRect.height; }
set { _scaleY = value/_textureRect.height; _isMatrixDirty = true; }
}
virtual public float anchorX
{
get { return _anchorX;}
set
{
if(_anchorX != value)
{
_anchorX = value;
_areLocalVerticesDirty = true;
}
}
}
virtual public float anchorY
{
get { return _anchorY;}
set
{
if(_anchorY != value)
{
_anchorY = value;
_areLocalVerticesDirty = true;
}
}
}
//for convenience
public void SetAnchor(float newX, float newY)
{
this.anchorX = newX;
this.anchorY = newY;
}
public void SetAnchor(Vector2 newAnchor)
{
this.anchorX = newAnchor.x;
this.anchorY = newAnchor.y;
}
public Vector2 GetAnchor()
{
return new Vector2(_anchorX,_anchorY);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt163()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt163();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt163
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt16 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
Vector256<UInt16> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 3, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector256<UInt16> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt16)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<UInt16>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(3 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(3 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "")
{
if (result != values[3])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.GetElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
UInt16[] resultElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 3) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[3] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt16.WithElement(3): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AndNotInt16()
{
var test = new SimpleBinaryOpTest__AndNotInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__AndNotInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.AndNot(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.AndNot(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.AndNot(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotInt16();
var result = Avx2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
if ((short)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.Resource;
using Apache.Ignite.Core.Tests.Cache;
using NUnit.Framework;
/// <summary>
/// <see cref="IMessaging"/> tests.
/// </summary>
public sealed class MessagingTest
{
/** */
private IIgnite _grid1;
/** */
private IIgnite _grid2;
/** */
private IIgnite _grid3;
/** */
private static int _messageId;
/** Objects to test against. */
private static readonly object[] Objects = {
// Primitives.
null,
"string topic",
Guid.NewGuid(),
DateTime.Now,
byte.MinValue,
short.MaxValue,
// Enums.
CacheMode.Local,
GCCollectionMode.Forced,
// Objects.
new CacheTestKey(25),
new IgniteGuid(Guid.NewGuid(), 123),
};
/// <summary>
/// Executes before each test.
/// </summary>
[SetUp]
public void SetUp()
{
_grid1 = Ignition.Start(GetConfiguration("grid-1"));
_grid2 = Ignition.Start(GetConfiguration("grid-2"));
_grid3 = Ignition.Start(GetConfiguration("grid-3"));
Assert.AreEqual(3, _grid1.GetCluster().GetNodes().Count);
}
/// <summary>
/// Executes after each test.
/// </summary>
[TearDown]
public void TearDown()
{
try
{
TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3);
MessagingTestHelper.AssertFailures();
}
finally
{
// Stop all grids between tests to drop any hanging messages
Ignition.StopAll(true);
}
}
/// <summary>
/// Tests that any data type can be used as a message.
/// </summary>
[Test]
public void TestMessageDataTypes()
{
object lastMsg = null;
var evt = new AutoResetEvent(false);
var messaging1 = _grid1.GetMessaging();
var messaging2 = _grid2.GetMessaging();
var listener = new MessageListener<object>((nodeId, msg) =>
{
lastMsg = msg;
evt.Set();
return true;
});
foreach (var msg in Objects.Where(x => x != null))
{
var topic = "dataTypes" + Guid.NewGuid();
messaging1.LocalListen(listener, topic);
messaging2.Send(msg, topic);
evt.WaitOne(500);
Assert.AreEqual(msg, lastMsg);
messaging1.StopLocalListen(listener, topic);
}
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[Test]
public void TestLocalListen()
{
TestLocalListen(NextId());
foreach (var topic in Objects)
{
TestLocalListen(topic);
}
}
/// <summary>
/// Tests LocalListen.
/// </summary>
[SuppressMessage("ReSharper", "AccessToModifiedClosure")]
private void TestLocalListen(object topic)
{
var messaging = _grid1.GetMessaging();
var listener = MessagingTestHelper.GetListener();
messaging.LocalListen(listener, topic);
// Test sending
CheckSend(topic);
CheckSend(topic, _grid2);
CheckSend(topic, _grid3);
// Test different topic
CheckNoMessage(NextId());
CheckNoMessage(NextId(), _grid2);
// Test multiple subscriptions for the same filter
messaging.LocalListen(listener, topic);
messaging.LocalListen(listener, topic);
CheckSend(topic, repeatMultiplier: 3); // expect all messages repeated 3 times
messaging.StopLocalListen(listener, topic);
CheckSend(topic, repeatMultiplier: 2); // expect all messages repeated 2 times
messaging.StopLocalListen(listener, topic);
CheckSend(topic); // back to 1 listener
// Test message type mismatch
var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic));
Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message);
// Test end listen
MessagingTestHelper.ListenResult = false;
CheckSend(topic, single: true); // we'll receive one more and then unsubscribe because of delegate result.
CheckNoMessage(topic);
// Start again
MessagingTestHelper.ListenResult = true;
messaging.LocalListen(listener, topic);
CheckSend(topic);
// Stop
messaging.StopLocalListen(listener, topic);
CheckNoMessage(topic);
}
/// <summary>
/// Tests LocalListen with projection.
/// </summary>
[Test]
public void TestLocalListenProjection()
{
TestLocalListenProjection(NextId());
TestLocalListenProjection("prj");
foreach (var topic in Objects)
{
TestLocalListenProjection(topic);
}
}
/// <summary>
/// Tests LocalListen with projection.
/// </summary>
private void TestLocalListenProjection(object topic)
{
var grid3GotMessage = false;
var grid3Listener = new MessageListener<string>((id, x) =>
{
grid3GotMessage = true;
return true;
});
_grid3.GetMessaging().LocalListen(grid3Listener, topic);
var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging();
var clusterListener = MessagingTestHelper.GetListener();
clusterMessaging.LocalListen(clusterListener, topic);
CheckSend(msg: clusterMessaging, topic: topic);
Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages");
CheckSend(grid: _grid2, msg: clusterMessaging, topic: topic);
Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages");
clusterMessaging.StopLocalListen(clusterListener, topic);
_grid3.GetMessaging().StopLocalListen(grid3Listener, topic);
}
/// <summary>
/// Tests LocalListen in multithreaded mode.
/// </summary>
[Test]
[SuppressMessage("ReSharper", "AccessToModifiedClosure")]
[Category(TestUtils.CategoryIntensive)]
public void TestLocalListenMultithreaded()
{
const int threadCnt = 20;
const int runSeconds = 20;
var messaging = _grid1.GetMessaging();
var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() =>
{
messaging.Send(NextMessage());
Thread.Sleep(50);
}, threadCnt, runSeconds));
var sharedReceived = 0;
var sharedListener = new MessageListener<string>((id, x) =>
{
Interlocked.Increment(ref sharedReceived);
Thread.MemoryBarrier();
return true;
});
TestUtils.RunMultiThreaded(() =>
{
// Check that listen/stop work concurrently
messaging.LocalListen(sharedListener);
for (int i = 0; i < 100; i++)
{
messaging.LocalListen(sharedListener);
messaging.StopLocalListen(sharedListener);
}
var localReceived = 0;
var stopLocal = 0;
var localListener = new MessageListener<string>((id, x) =>
{
Interlocked.Increment(ref localReceived);
Thread.MemoryBarrier();
return Thread.VolatileRead(ref stopLocal) == 0;
});
messaging.LocalListen(localListener);
Thread.Sleep(100);
Thread.VolatileWrite(ref stopLocal, 1);
Thread.Sleep(1000);
var result = Thread.VolatileRead(ref localReceived);
Thread.Sleep(100);
// Check that unsubscription worked properly
Assert.AreEqual(result, Thread.VolatileRead(ref localReceived));
messaging.StopLocalListen(sharedListener);
}, threadCnt, runSeconds);
senders.Wait();
Thread.Sleep(100);
var sharedResult = Thread.VolatileRead(ref sharedReceived);
messaging.Send(NextMessage());
Thread.Sleep(MessagingTestHelper.SleepTimeout);
// Check that unsubscription worked properly
Assert.AreEqual(sharedResult, Thread.VolatileRead(ref sharedReceived));
}
/// <summary>
/// Tests RemoteListen.
/// </summary>
[Test]
public void TestRemoteListen([Values(true, false)] bool async)
{
TestRemoteListen(NextId(), async);
foreach (var topic in Objects)
{
TestRemoteListen(topic, async);
}
}
/// <summary>
/// Tests RemoteListen.
/// </summary>
private void TestRemoteListen(object topic, bool async = false)
{
var messaging =_grid1.GetMessaging();
var listener = MessagingTestHelper.GetListener();
var listenId = async
? messaging.RemoteListenAsync(listener, topic).Result
: messaging.RemoteListen(listener, topic);
// Test sending
CheckSend(topic, msg: messaging, remoteListen: true);
// Test different topic
CheckNoMessage(NextId());
// Test multiple subscriptions for the same filter
var listenId2 = async
? messaging.RemoteListenAsync(listener, topic).Result
: messaging.RemoteListen(listener, topic);
CheckSend(topic, msg: messaging, remoteListen: true, repeatMultiplier: 2); // expect twice the messages
if (async)
messaging.StopRemoteListenAsync(listenId2).Wait();
else
messaging.StopRemoteListen(listenId2);
CheckSend(topic, msg: messaging, remoteListen: true); // back to normal after unsubscription
// Test message type mismatch
var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic));
Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message);
// Test end listen
if (async)
messaging.StopRemoteListenAsync(listenId).Wait();
else
messaging.StopRemoteListen(listenId);
CheckNoMessage(topic);
}
/// <summary>
/// Tests RemoteListen with a projection.
/// </summary>
[Test]
public void TestRemoteListenProjection()
{
TestRemoteListenProjection(NextId());
foreach (var topic in Objects)
{
TestRemoteListenProjection(topic);
}
}
/// <summary>
/// Tests RemoteListen with a projection.
/// </summary>
private void TestRemoteListenProjection(object topic)
{
var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging();
var clusterListener = MessagingTestHelper.GetListener();
var listenId = clusterMessaging.RemoteListen(clusterListener, topic);
CheckSend(msg: clusterMessaging, topic: topic, remoteListen: true);
clusterMessaging.StopRemoteListen(listenId);
CheckNoMessage(topic);
}
/// <summary>
/// Tests LocalListen in multithreaded mode.
/// </summary>
[Test]
[Category(TestUtils.CategoryIntensive)]
public void TestRemoteListenMultithreaded()
{
const int threadCnt = 20;
const int runSeconds = 20;
var messaging = _grid1.GetMessaging();
var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() =>
{
MessagingTestHelper.ClearReceived(int.MaxValue);
messaging.Send(NextMessage());
Thread.Sleep(50);
}, threadCnt, runSeconds));
var sharedListener = MessagingTestHelper.GetListener();
for (int i = 0; i < 100; i++)
messaging.RemoteListen(sharedListener); // add some listeners to be stopped by filter result
TestUtils.RunMultiThreaded(() =>
{
// Check that listen/stop work concurrently
messaging.StopRemoteListen(messaging.RemoteListen(sharedListener));
}, threadCnt, runSeconds / 2);
MessagingTestHelper.ListenResult = false;
messaging.Send(NextMessage()); // send a message to make filters return false
Thread.Sleep(MessagingTestHelper.SleepTimeout); // wait for all to unsubscribe
MessagingTestHelper.ListenResult = true;
senders.Wait(); // wait for senders to stop
MessagingTestHelper.ClearReceived(int.MaxValue);
var lastMsg = NextMessage();
messaging.Send(lastMsg);
Thread.Sleep(MessagingTestHelper.SleepTimeout);
// Check that unsubscription worked properly
var sharedResult = MessagingTestHelper.ReceivedMessages.ToArray();
if (sharedResult.Length != 0)
{
Assert.Fail("Unexpected messages ({0}): {1}; last sent message: {2}", sharedResult.Length,
string.Join(",", sharedResult), lastMsg);
}
}
/// <summary>
/// Sends messages in various ways and verefies correct receival.
/// </summary>
/// <param name="topic">Topic.</param>
/// <param name="grid">The grid to use.</param>
/// <param name="msg">Messaging to use.</param>
/// <param name="remoteListen">Whether to expect remote listeners.</param>
/// <param name="single">When true, only check one message.</param>
/// <param name="repeatMultiplier">Expected message count multiplier.</param>
private void CheckSend(object topic = null, IIgnite grid = null,
IMessaging msg = null, bool remoteListen = false, bool single = false, int repeatMultiplier = 1)
{
IClusterGroup cluster;
if (msg != null)
cluster = msg.ClusterGroup;
else
{
grid = grid ?? _grid1;
msg = grid.GetMessaging();
cluster = grid.GetCluster().ForLocal();
}
// Messages will repeat due to multiple nodes listening
var expectedRepeat = repeatMultiplier * (remoteListen ? cluster.GetNodes().Count : 1);
var messages = Enumerable.Range(1, 10).Select(x => NextMessage()).OrderBy(x => x).ToList();
// Single message
MessagingTestHelper.ClearReceived(expectedRepeat);
msg.Send(messages[0], topic);
MessagingTestHelper.VerifyReceive(cluster, messages.Take(1), m => m.ToList(), expectedRepeat);
if (single)
return;
// Multiple messages (receive order is undefined)
MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat);
msg.SendAll(messages, topic);
MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat);
// Multiple messages, ordered
MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat);
messages.ForEach(x => msg.SendOrdered(x, topic, MessagingTestHelper.MessageTimeout));
if (remoteListen) // in remote scenario messages get mixed up due to different timing on different nodes
MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat);
else
MessagingTestHelper.VerifyReceive(cluster, messages, m => m.Reverse(), expectedRepeat);
}
/// <summary>
/// Checks that no message has arrived.
/// </summary>
private void CheckNoMessage(object topic, IIgnite grid = null)
{
// this will result in an exception in case of a message
MessagingTestHelper.ClearReceived(0);
(grid ?? _grid1).GetMessaging().SendAll(NextMessage(), topic);
Thread.Sleep(MessagingTestHelper.SleepTimeout);
MessagingTestHelper.AssertFailures();
}
/// <summary>
/// Gets the Ignite configuration.
/// </summary>
private static IgniteConfiguration GetConfiguration(string name)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
IgniteInstanceName = name
};
}
/// <summary>
/// Generates next message with sequential ID and current test name.
/// </summary>
private static string NextMessage()
{
var id = NextId();
return id + "_" + TestContext.CurrentContext.Test.Name;
}
/// <summary>
/// Generates next sequential ID.
/// </summary>
private static int NextId()
{
return Interlocked.Increment(ref _messageId);
}
}
/// <summary>
/// Messaging test helper class.
/// </summary>
[Serializable]
public static class MessagingTestHelper
{
/** */
public static readonly ConcurrentStack<string> ReceivedMessages = new ConcurrentStack<string>();
/** */
private static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>();
/** */
private static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0);
/** */
private static readonly ConcurrentStack<Guid> LastNodeIds = new ConcurrentStack<Guid>();
/** */
public static volatile bool ListenResult = true;
/** */
public static readonly TimeSpan MessageTimeout = TimeSpan.FromMilliseconds(5000);
/** */
public static readonly TimeSpan SleepTimeout = TimeSpan.FromMilliseconds(50);
/// <summary>
/// Clears received message information.
/// </summary>
/// <param name="expectedCount">The expected count of messages to be received.</param>
public static void ClearReceived(int expectedCount)
{
ReceivedMessages.Clear();
ReceivedEvent.Reset(expectedCount);
LastNodeIds.Clear();
}
/// <summary>
/// Verifies received messages against expected messages.
/// </summary>
/// <param name="cluster">Cluster.</param>
/// <param name="expectedMessages">Expected messages.</param>
/// <param name="resultFunc">Result transform function.</param>
/// <param name="expectedRepeat">Expected repeat count.</param>
public static void VerifyReceive(IClusterGroup cluster, IEnumerable<string> expectedMessages,
Func<IEnumerable<string>, IEnumerable<string>> resultFunc, int expectedRepeat)
{
// check if expected message count has been received; Wait returns false if there were none.
Assert.IsTrue(ReceivedEvent.Wait(MessageTimeout),
string.Format("expectedMessages: {0}, expectedRepeat: {1}, remaining: {2}",
expectedMessages, expectedRepeat, ReceivedEvent.CurrentCount));
expectedMessages = expectedMessages.SelectMany(x => Enumerable.Repeat(x, expectedRepeat));
Assert.AreEqual(expectedMessages, resultFunc(ReceivedMessages));
// check that all messages came from local node.
var localNodeId = cluster.Ignite.GetCluster().GetLocalNode().Id;
Assert.AreEqual(localNodeId, LastNodeIds.Distinct().Single());
AssertFailures();
}
/// <summary>
/// Gets the message listener.
/// </summary>
/// <returns>New instance of message listener.</returns>
public static IMessageListener<string> GetListener()
{
return new RemoteListener();
}
/// <summary>
/// Combines accumulated failures and throws an assertion, if there are any.
/// Clears accumulated failures.
/// </summary>
public static void AssertFailures()
{
if (Failures.Any())
Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y)));
Failures.Clear();
}
/// <summary>
/// Remote listener.
/// </summary>
private class RemoteListener : IMessageListener<string>
{
/** <inheritdoc /> */
public bool Invoke(Guid nodeId, string message)
{
try
{
LastNodeIds.Push(nodeId);
ReceivedMessages.Push(message);
ReceivedEvent.Signal();
return ListenResult;
}
catch (Exception ex)
{
// When executed on remote nodes, these exceptions will not go to sender,
// so we have to accumulate them.
Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", message, nodeId, ex));
throw;
}
}
}
}
/// <summary>
/// Test message filter.
/// </summary>
[Serializable]
public class MessageListener<T> : IMessageListener<T>
{
/** */
private readonly Func<Guid, T, bool> _invoke;
#pragma warning disable 649
/** Grid. */
[InstanceResource]
// ReSharper disable once UnassignedField.Local
private IIgnite _grid;
#pragma warning restore 649
/// <summary>
/// Initializes a new instance of the <see cref="MessageListener{T}"/> class.
/// </summary>
/// <param name="invoke">The invoke delegate.</param>
public MessageListener(Func<Guid, T, bool> invoke)
{
_invoke = invoke;
}
/** <inheritdoc /> */
public bool Invoke(Guid nodeId, T message)
{
Assert.IsNotNull(_grid);
return _invoke(nodeId, message);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.IoT.Hub.Service.Models;
namespace Azure.IoT.Hub.Service
{
/// <summary>
/// Devices client to interact with devices and device twins including CRUD operations and method invocations.
/// See <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-twin-getstarted"> Getting started with device identity</see>.
/// </summary>
public class DevicesClient
{
private const string HubDeviceQuery = "select * from devices";
private readonly DevicesRestClient _devicesRestClient;
private readonly QueryClient _queryClient;
private readonly BulkRegistryRestClient _bulkRegistryClient;
/// <summary>
/// Initializes a new instance of DevicesClient.
/// </summary>
protected DevicesClient()
{
}
/// <summary>
/// Initializes a new instance of DevicesClient.
/// <param name="devicesRestClient"> The REST client to perform device, device twin, and bulk operations. </param>
/// <param name="queryClient"> The convenience layer query client to perform query operations for the device. </param>
/// <param name="bulkRegistryClient"> The convenience layer client to perform bulk operations on devices. </param>
/// </summary>
internal DevicesClient(DevicesRestClient devicesRestClient, QueryClient queryClient, BulkRegistryRestClient bulkRegistryClient)
{
Argument.AssertNotNull(devicesRestClient, nameof(devicesRestClient));
Argument.AssertNotNull(queryClient, nameof(queryClient));
Argument.AssertNotNull(bulkRegistryClient, nameof(bulkRegistryClient));
_devicesRestClient = devicesRestClient;
_queryClient = queryClient;
_bulkRegistryClient = bulkRegistryClient;
}
/// <summary>
/// Create or update a device identity.
/// </summary>
/// <param name="deviceIdentity">the device identity to create or update.</param>
/// <param name="precondition">The condition on which to perform this operation.
/// In case of create, the condition must be equal to <see cref="IfMatchPrecondition.IfMatch"/>.
/// In case of update, if no ETag is present on the device, then the condition must be equal to <see cref="IfMatchPrecondition.UnconditionalIfMatch"/>.
/// </param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The created device identity and the http response <see cref="Response{T}"/>.</returns>
/// <code snippet="Snippet:IotHubCreateDeviceIdentity" language="csharp">
/// Response<DeviceIdentity> response = await IoTHubServiceClient.Devices.CreateOrUpdateIdentityAsync(deviceIdentity);
///
/// SampleLogger.PrintSuccess($"Successfully create a new device identity with Id: '{response.Value.DeviceId}', ETag: '{response.Value.Etag}'");
/// </code>
/// <code snippet="Snippet:IotHubUpdateDeviceIdentity" language="csharp">
/// Response<DeviceIdentity> getResponse = await IoTHubServiceClient.Devices.GetIdentityAsync(deviceId);
///
/// DeviceIdentity deviceIdentity = getResponse.Value;
/// Console.WriteLine($"Current device identity: DeviceId: '{deviceIdentity.DeviceId}', Status: '{deviceIdentity.Status}', ETag: '{deviceIdentity.Etag}'");
///
/// Console.WriteLine($"Updating device identity with Id: '{deviceIdentity.DeviceId}'. Disabling device so it cannot connect to IoT Hub.");
/// deviceIdentity.Status = DeviceStatus.Disabled;
///
/// Response<DeviceIdentity> response = await IoTHubServiceClient.Devices.CreateOrUpdateIdentityAsync(deviceIdentity);
///
/// DeviceIdentity updatedDevice = response.Value;
///
/// SampleLogger.PrintSuccess($"Successfully updated device identity: DeviceId: '{updatedDevice.DeviceId}', DeviceId: '{updatedDevice.DeviceId}', Status: '{updatedDevice.Status}', ETag: '{updatedDevice.Etag}'");
/// </code>
public virtual Task<Response<DeviceIdentity>> CreateOrUpdateIdentityAsync(
DeviceIdentity deviceIdentity,
IfMatchPrecondition precondition = IfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(deviceIdentity, nameof(deviceIdentity));
string ifMatchHeaderValue = IfMatchPreconditionExtensions.GetIfMatchHeaderValue(precondition, deviceIdentity.Etag);
return _devicesRestClient.CreateOrUpdateIdentityAsync(deviceIdentity.DeviceId, deviceIdentity, ifMatchHeaderValue, cancellationToken);
}
/// <summary>
/// Create or update a device identity.
/// </summary>
/// <param name="deviceIdentity">the device identity to create or update.</param>
/// <param name="precondition">The condition on which to perform this operation.
/// In case of create, the condition must be equal to <see cref="IfMatchPrecondition.IfMatch"/>.
/// In case of update, if no ETag is present on the device, then the condition must be equal to <see cref="IfMatchPrecondition.UnconditionalIfMatch"/>.
/// </param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The created device identity and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<DeviceIdentity> CreateOrUpdateIdentity(
DeviceIdentity deviceIdentity,
IfMatchPrecondition precondition = IfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(deviceIdentity, nameof(deviceIdentity));
string ifMatchHeaderValue = IfMatchPreconditionExtensions.GetIfMatchHeaderValue(precondition, deviceIdentity.Etag);
return _devicesRestClient.CreateOrUpdateIdentity(deviceIdentity.DeviceId, deviceIdentity, ifMatchHeaderValue, cancellationToken);
}
/// <summary>
/// Get a single device identity.
/// </summary>
/// <param name="deviceId">The unique identifier of the device identity to get.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The retrieved device identity and the http response <see cref="Response{T}"/>.</returns>
/// <code snippet="Snippet:IotHubGetDeviceIdentity" language="csharp">
/// Response<DeviceIdentity> response = await IoTHubServiceClient.Devices.GetIdentityAsync(deviceId);
///
/// DeviceIdentity deviceIdentity = response.Value;
///
/// SampleLogger.PrintSuccess($"\t- Device Id: '{deviceIdentity.DeviceId}', ETag: '{deviceIdentity.Etag}'");
/// </code>
public virtual Task<Response<DeviceIdentity>> GetIdentityAsync(string deviceId, CancellationToken cancellationToken = default)
{
return _devicesRestClient.GetIdentityAsync(deviceId, cancellationToken);
}
/// <summary>
/// Get a single device identity.
/// </summary>
/// <param name="deviceId">The unique identifier of the device identity to get.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The retrieved device identity and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<DeviceIdentity> GetIdentity(string deviceId, CancellationToken cancellationToken = default)
{
return _devicesRestClient.GetIdentity(deviceId, cancellationToken);
}
/// <summary>
/// Delete a single device identity.
/// </summary>
/// <param name="deviceIdentity">the device identity to delete. If no ETag is present on the device, then the condition must be equal to <see cref="IfMatchPrecondition.UnconditionalIfMatch"/>."/>.</param>
/// <param name="precondition">The condition on which to delete the device.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The http response <see cref="Response{T}"/>.</returns>
/// <code snippet="Snippet:IotHubDeleteDeviceIdentity" language="csharp">
/// Response response = await IoTHubServiceClient.Devices.DeleteIdentityAsync(deviceIdentity);
///
/// SampleLogger.PrintSuccess($"Successfully deleted device identity with Id: '{deviceIdentity.DeviceId}'");
/// </code>
public virtual Task<Response> DeleteIdentityAsync(
DeviceIdentity deviceIdentity,
IfMatchPrecondition precondition = IfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(deviceIdentity, nameof(deviceIdentity));
string ifMatchHeaderValue = IfMatchPreconditionExtensions.GetIfMatchHeaderValue(precondition, deviceIdentity.Etag);
return _devicesRestClient.DeleteIdentityAsync(deviceIdentity.DeviceId, ifMatchHeaderValue, cancellationToken);
}
/// <summary>
/// Delete a single device identity.
/// </summary>
/// <param name="deviceIdentity">the device identity to delete. If no ETag is present on the device, then the condition must be equal to <see cref="IfMatchPrecondition.UnconditionalIfMatch"/>.</param>
/// <param name="precondition">The condition on which to delete the device.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The http response <see cref="Response{T}"/>.</returns>
public virtual Response DeleteIdentity(
DeviceIdentity deviceIdentity,
IfMatchPrecondition precondition = IfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(deviceIdentity, nameof(deviceIdentity));
string ifMatchHeaderValue = IfMatchPreconditionExtensions.GetIfMatchHeaderValue(precondition, deviceIdentity.Etag);
return _devicesRestClient.DeleteIdentity(deviceIdentity.DeviceId, ifMatchHeaderValue, cancellationToken);
}
/// <summary>
/// Create multiple devices with an initial twin. A maximum of 100 creations can be done per call, and each creation must have a unique device identity. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="devices">The pairs of devices and their twins that will be created. For fields such as deviceId
/// where device and twin have a definition, the device value will override the twin value.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Task<Response<BulkRegistryOperationResponse>> CreateIdentitiesWithTwinAsync(IDictionary<DeviceIdentity, TwinData> devices, CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = devices
.Select(x => new ExportImportDevice()
{
Id = x.Key.DeviceId,
Authentication = x.Key.Authentication,
Capabilities = x.Key.Capabilities,
DeviceScope = x.Key.DeviceScope,
Status = string.Equals(ExportImportDeviceStatus.Disabled.ToString(), x.Key.Status?.ToString(), StringComparison.OrdinalIgnoreCase)
? ExportImportDeviceStatus.Disabled
: ExportImportDeviceStatus.Enabled,
StatusReason = x.Key.StatusReason,
ImportMode = ExportImportDeviceImportMode.Create
}.WithTags(x.Value.Tags).WithPropertiesFrom(x.Value.Properties));
return _bulkRegistryClient.UpdateRegistryAsync(registryOperations, cancellationToken);
}
/// <summary>
/// Create multiple devices with an initial twin. A maximum of 100 creations can be done per call, and each creation must have a unique device identity. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="devices">The pairs of devices and their twins that will be created. For fields such as deviceId
/// where device and twin have a definition, the device value will override the twin value.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<BulkRegistryOperationResponse> CreateIdentitiesWithTwin(IDictionary<DeviceIdentity, TwinData> devices, CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = devices
.Select(x => new ExportImportDevice()
{
Id = x.Key.DeviceId,
Authentication = x.Key.Authentication,
Capabilities = x.Key.Capabilities,
DeviceScope = x.Key.DeviceScope,
Status = string.Equals(ExportImportDeviceStatus.Disabled.ToString(), x.Key.Status?.ToString(), StringComparison.OrdinalIgnoreCase)
? ExportImportDeviceStatus.Disabled
: ExportImportDeviceStatus.Enabled,
StatusReason = x.Key.StatusReason,
ImportMode = ExportImportDeviceImportMode.Create
}.WithTags(x.Value.Tags).WithPropertiesFrom(x.Value.Properties));
return _bulkRegistryClient.UpdateRegistry(registryOperations, cancellationToken);
}
/// <summary>
/// Create multiple devices. A maximum of 100 creations can be done per call, and each device identity must be unique. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="deviceIdentities">The device identities to create.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Task<Response<BulkRegistryOperationResponse>> CreateIdentitiesAsync(IEnumerable<DeviceIdentity> deviceIdentities, CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = deviceIdentities
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
Authentication = x.Authentication,
Capabilities = x.Capabilities,
DeviceScope = x.DeviceScope,
Status = string.Equals(ExportImportDeviceStatus.Disabled.ToString(), x.Status?.ToString(), StringComparison.OrdinalIgnoreCase)
? ExportImportDeviceStatus.Disabled
: ExportImportDeviceStatus.Enabled,
StatusReason = x.StatusReason,
ImportMode = ExportImportDeviceImportMode.Create
});
return _bulkRegistryClient.UpdateRegistryAsync(registryOperations, cancellationToken);
}
/// <summary>
/// Create multiple devices. A maximum of 100 creations can be done per call, and each device identity must be unique. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="deviceIdentities">The device identities to create.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<BulkRegistryOperationResponse> CreateIdentities(IEnumerable<DeviceIdentity> deviceIdentities, CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = deviceIdentities
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
Authentication = x.Authentication,
Capabilities = x.Capabilities,
DeviceScope = x.DeviceScope,
Status = string.Equals(ExportImportDeviceStatus.Disabled.ToString(), x.Status?.ToString(), StringComparison.OrdinalIgnoreCase)
? ExportImportDeviceStatus.Disabled
: ExportImportDeviceStatus.Enabled,
StatusReason = x.StatusReason,
ImportMode = ExportImportDeviceImportMode.Create
});
return _bulkRegistryClient.UpdateRegistry(registryOperations, cancellationToken);
}
/// <summary>
/// Update multiple devices. A maximum of 100 updates can be done per call, and each operation must be done on a different identity. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>..
/// </summary>
/// <param name="deviceIdentities">The devices to update.</param>
/// <param name="precondition">The condition on which to update each device identity.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Task<Response<BulkRegistryOperationResponse>> UpdateIdentitiesAsync(
IEnumerable<DeviceIdentity> deviceIdentities,
BulkIfMatchPrecondition precondition = BulkIfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = deviceIdentities
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
Authentication = x.Authentication,
Capabilities = x.Capabilities,
DeviceScope = x.DeviceScope,
ETag = x.Etag,
Status = string.Equals(ExportImportDeviceStatus.Disabled.ToString(), x.Status?.ToString(), StringComparison.OrdinalIgnoreCase)
? ExportImportDeviceStatus.Disabled
: ExportImportDeviceStatus.Enabled,
StatusReason = x.StatusReason,
ImportMode = precondition == BulkIfMatchPrecondition.Unconditional ? ExportImportDeviceImportMode.Update : ExportImportDeviceImportMode.UpdateIfMatchETag
});
return _bulkRegistryClient.UpdateRegistryAsync(registryOperations, cancellationToken);
}
/// <summary>
/// Update multiple devices. A maximum of 100 updates can be done per call, and each operation must be done on a different identity. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="deviceIdentities">The devices to update.</param>
/// <param name="precondition">The condition on which to update each device identity.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<BulkRegistryOperationResponse> UpdateIdentities(
IEnumerable<DeviceIdentity> deviceIdentities,
BulkIfMatchPrecondition precondition = BulkIfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = deviceIdentities
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
Authentication = x.Authentication,
Capabilities = x.Capabilities,
DeviceScope = x.DeviceScope,
ETag = x.Etag,
Status = string.Equals(ExportImportDeviceStatus.Disabled.ToString(), x.Status?.ToString(), StringComparison.OrdinalIgnoreCase)
? ExportImportDeviceStatus.Disabled
: ExportImportDeviceStatus.Enabled,
StatusReason = x.StatusReason,
ImportMode = precondition == BulkIfMatchPrecondition.Unconditional ? ExportImportDeviceImportMode.Update : ExportImportDeviceImportMode.UpdateIfMatchETag
});
return _bulkRegistryClient.UpdateRegistry(registryOperations, cancellationToken);
}
/// <summary>
/// Delete multiple devices. A maximum of 100 deletions can be done per call. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="deviceIdentities">The devices to delete.</param>
/// <param name="precondition">The condition on which to delete each device identity.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk deletion and the http response <see cref="Response{T}"/>.</returns>
public virtual Task<Response<BulkRegistryOperationResponse>> DeleteIdentitiesAsync(
IEnumerable<DeviceIdentity> deviceIdentities,
BulkIfMatchPrecondition precondition = BulkIfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = deviceIdentities
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
ETag = x.Etag,
ImportMode = precondition == BulkIfMatchPrecondition.Unconditional
? ExportImportDeviceImportMode.Delete
: ExportImportDeviceImportMode.DeleteIfMatchETag
});
return _bulkRegistryClient.UpdateRegistryAsync(registryOperations, cancellationToken);
}
/// <summary>
/// Delete multiple devices. A maximum of 100 deletions can be done per call. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="deviceIdentities">The devices to delete.</param>
/// <param name="precondition">The condition on which to delete each device identity.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk deletion and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<BulkRegistryOperationResponse> DeleteIdentities(
IEnumerable<DeviceIdentity> deviceIdentities,
BulkIfMatchPrecondition precondition = BulkIfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = deviceIdentities
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
ETag = x.Etag,
ImportMode = precondition == BulkIfMatchPrecondition.Unconditional
? ExportImportDeviceImportMode.Delete
: ExportImportDeviceImportMode.DeleteIfMatchETag
});
return _bulkRegistryClient.UpdateRegistry(registryOperations, cancellationToken);
}
/// <summary>
/// List a set of device twins.
/// </summary>
/// <remarks>
/// This service request returns the full set of device twins. To get a subset of device twins, you can use the <see cref="QueryClient.QueryAsync(string, int?, CancellationToken)">query API</see> that this method uses but with additional qualifiers for selection.
/// </remarks>
/// <param name="pageSize">The size of each page to be retrieved from the service. Service may override this size.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A pageable set of device twins <see cref="AsyncPageable{T}"/>.</returns>
public virtual AsyncPageable<TwinData> GetTwinsAsync(int? pageSize = null, CancellationToken cancellationToken = default)
{
return _queryClient.QueryAsync(HubDeviceQuery, pageSize, cancellationToken);
}
/// <summary>
/// List a set of device twins.
/// </summary>
/// <remarks>
/// This service request returns the full set of device twins. To get a subset of device twins, you can use the <see cref="QueryClient.Query(string, int?, CancellationToken)">query API</see> that this method uses but with additional qualifiers for selection.
/// </remarks>
/// <param name="pageSize">The size of each page to be retrieved from the service. Service may override this size.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A pageable set of device twins <see cref="Pageable{T}"/>.</returns>
public virtual Pageable<TwinData> GetTwins(int? pageSize = null, CancellationToken cancellationToken = default)
{
return _queryClient.Query(HubDeviceQuery, pageSize, cancellationToken);
}
/// <summary>
/// Get a device's twin.
/// </summary>
/// <param name="deviceId">The unique identifier of the device identity to get the twin of.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The device's twin, including reported properties and desired properties and the http response <see cref="Response{T}"/>.</returns>
/// <code snippet="Snippet:IotHubGetDeviceTwin" language="csharp">
/// Response<TwinData> response = await IoTHubServiceClient.Devices.GetTwinAsync(deviceId);
///
/// SampleLogger.PrintSuccess($"\t- Device Twin: DeviceId: '{response.Value.DeviceId}', Status: '{response.Value.Status}', ETag: '{response.Value.Etag}'");
/// </code>
public virtual Task<Response<TwinData>> GetTwinAsync(string deviceId, CancellationToken cancellationToken = default)
{
return _devicesRestClient.GetTwinAsync(deviceId, cancellationToken);
}
/// <summary>
/// Get a device's twin.
/// </summary>
/// <param name="deviceId">The unique identifier of the device identity to get the twin of.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The device's twin, including reported properties and desired properties.</returns>
public virtual Response<TwinData> GetTwin(string deviceId, CancellationToken cancellationToken = default)
{
return _devicesRestClient.GetTwin(deviceId, cancellationToken);
}
/// <summary>
/// Update a device's twin.
/// </summary>
/// <param name="twinUpdate">The properties to update. Any existing properties not referenced by this patch will be unaffected by this patch.</param>
/// <param name="precondition">The condition for which this operation will execute.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The new representation of the device twin and the http response <see cref="Response{T}"/>.</returns>
/// <code snippet="Snippet:IotHubUpdateDeviceTwin" language="csharp">
/// Response<TwinData> getResponse = await IoTHubServiceClient.Devices.GetTwinAsync(deviceId);
/// TwinData deviceTwin = getResponse.Value;
///
/// Console.WriteLine($"Updating device twin: DeviceId: '{deviceTwin.DeviceId}', ETag: '{deviceTwin.Etag}'");
/// Console.WriteLine($"Setting a new desired property {userPropName} to: '{Environment.UserName}'");
///
/// deviceTwin.Properties.Desired.Add(new KeyValuePair<string, object>(userPropName, Environment.UserName));
///
/// Response<TwinData> response = await IoTHubServiceClient.Devices.UpdateTwinAsync(deviceTwin);
///
/// TwinData updatedTwin = response.Value;
///
/// var userPropValue = (string)updatedTwin.Properties.Desired
/// .Where(p => p.Key == userPropName)
/// .First()
/// .Value;
///
/// SampleLogger.PrintSuccess($"Successfully updated device twin: DeviceId: '{updatedTwin.DeviceId}', desired property: ['{userPropName}': '{userPropValue}'], ETag: '{updatedTwin.Etag}',");
/// </code>
public virtual Task<Response<TwinData>> UpdateTwinAsync(TwinData twinUpdate, IfMatchPrecondition precondition = IfMatchPrecondition.IfMatch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(twinUpdate, nameof(twinUpdate));
string ifMatchHeaderValue = IfMatchPreconditionExtensions.GetIfMatchHeaderValue(precondition, twinUpdate.Etag);
return _devicesRestClient.UpdateTwinAsync(twinUpdate.DeviceId, twinUpdate, ifMatchHeaderValue, cancellationToken);
}
/// <summary>
/// Update a device's twin.
/// </summary>
/// <param name="twinUpdate">The properties to update. Any existing properties not referenced by this patch will be unaffected by this patch.</param>
/// <param name="precondition">The condition for which this operation will execute.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The new representation of the device twin and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<TwinData> UpdateTwin(TwinData twinUpdate, IfMatchPrecondition precondition = IfMatchPrecondition.IfMatch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(twinUpdate, nameof(twinUpdate));
string ifMatchHeaderValue = IfMatchPreconditionExtensions.GetIfMatchHeaderValue(precondition, twinUpdate.Etag);
return _devicesRestClient.UpdateTwin(twinUpdate.DeviceId, twinUpdate, ifMatchHeaderValue, cancellationToken);
}
/// <summary>
/// Update multiple devices' twins. A maximum of 100 updates can be done per call, and each operation must be done on a different device twin. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="twinUpdates">The new twins to replace the twins on existing devices.</param>
/// <param name="precondition">The condition on which to update each device twin.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Task<Response<BulkRegistryOperationResponse>> UpdateTwinsAsync(
IEnumerable<TwinData> twinUpdates,
BulkIfMatchPrecondition precondition = BulkIfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = twinUpdates
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
TwinETag = x.Etag,
ImportMode = precondition == BulkIfMatchPrecondition.Unconditional ? ExportImportDeviceImportMode.UpdateTwin : ExportImportDeviceImportMode.UpdateTwinIfMatchETag
}.WithTags(x.Tags).WithPropertiesFrom(x.Properties));
return _bulkRegistryClient.UpdateRegistryAsync(registryOperations, cancellationToken);
}
/// <summary>
/// Update multiple devices' twins. A maximum of 100 updates can be done per call, and each operation must be done on a different device twin. For larger scale operations, consider using <see href="https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities">IoT Hub jobs</see>.
/// </summary>
/// <param name="twinUpdates">The new twins to replace the twins on existing devices.</param>
/// <param name="precondition">The condition on which to update each device twin.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the bulk operation and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<BulkRegistryOperationResponse> UpdateTwins(
IEnumerable<TwinData> twinUpdates,
BulkIfMatchPrecondition precondition = BulkIfMatchPrecondition.IfMatch,
CancellationToken cancellationToken = default)
{
IEnumerable<ExportImportDevice> registryOperations = twinUpdates
.Select(x => new ExportImportDevice()
{
Id = x.DeviceId,
TwinETag = x.Etag,
ImportMode = precondition == BulkIfMatchPrecondition.Unconditional
? ExportImportDeviceImportMode.UpdateTwin
: ExportImportDeviceImportMode.UpdateTwinIfMatchETag
}.WithTags(x.Tags).WithPropertiesFrom(x.Properties));
return _bulkRegistryClient.UpdateRegistry(registryOperations, cancellationToken);
}
/// <summary>
/// Invoke a method on a device.
/// </summary>
/// <param name="deviceId">The unique identifier of the device identity to invoke the method on.</param>
/// <param name="directMethodRequest">The details of the method to invoke.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the method invocation and the http response <see cref="Response{T}"/>.</returns>
public virtual Task<Response<CloudToDeviceMethodResponse>> InvokeMethodAsync(string deviceId, CloudToDeviceMethodRequest directMethodRequest, CancellationToken cancellationToken = default)
{
return _devicesRestClient.InvokeMethodAsync(deviceId, directMethodRequest, cancellationToken);
}
/// <summary>
/// Invoke a method on a device.
/// </summary>
/// <param name="deviceId">The unique identifier of the device identity to invoke the method on.</param>
/// <param name="directMethodRequest">The details of the method to invoke.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The result of the method invocation and the http response <see cref="Response{T}"/>.</returns>
public virtual Response<CloudToDeviceMethodResponse> InvokeMethod(string deviceId, CloudToDeviceMethodRequest directMethodRequest, CancellationToken cancellationToken = default)
{
return _devicesRestClient.InvokeMethod(deviceId, directMethodRequest, cancellationToken);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Xml.Xsl.Qil;
#if FEATURE_COMPILED_XSL
using System.Xml.Xsl.IlGen;
#endif
using System.ComponentModel;
using MS.Internal.Xml.XPath;
using System.Runtime.Versioning;
namespace System.Xml.Xsl.Runtime
{
/// <summary>
/// XmlQueryRuntime is passed as the first parameter to all generated query methods.
///
/// XmlQueryRuntime contains runtime support for generated ILGen queries:
/// 1. Stack of output writers (stack handles nested document construction)
/// 2. Manages list of all xml types that are used within the query
/// 3. Manages list of all atomized names that are used within the query
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class XmlQueryRuntime
{
// Early-Bound Library Objects
private readonly XmlQueryContext _ctxt;
private XsltLibrary _xsltLib;
private readonly EarlyBoundInfo[] _earlyInfo;
private readonly object[] _earlyObjects;
// Global variables and parameters
private readonly string[] _globalNames;
private readonly object[] _globalValues;
// Names, prefix mappings, and name filters
private readonly XmlNameTable _nameTableQuery;
private readonly string[] _atomizedNames; // Names after atomization
private readonly XmlNavigatorFilter[] _filters; // Name filters (contain atomized names)
private readonly StringPair[][] _prefixMappingsList; // Lists of prefix mappings (used to resolve computed names)
// Xml types
private readonly XmlQueryType[] _types;
// Collations
private readonly XmlCollation[] _collations;
// Document ordering
private readonly DocumentOrderComparer _docOrderCmp;
// Indexes
private ArrayList[] _indexes;
// Output construction
private XmlQueryOutput _output;
private readonly Stack<XmlQueryOutput> _stkOutput;
//-----------------------------------------------
// Constructors
//-----------------------------------------------
/// <summary>
/// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately).
/// </summary>
internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt)
{
Debug.Assert(data != null);
string[] names = data.Names;
Int32Pair[] filters = data.Filters;
WhitespaceRuleLookup wsRules;
int i;
// Early-Bound Library Objects
wsRules = (data.WhitespaceRules != null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null;
_ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules);
_xsltLib = null;
_earlyInfo = data.EarlyBound;
_earlyObjects = (_earlyInfo != null) ? new object[_earlyInfo.Length] : null;
// Global variables and parameters
_globalNames = data.GlobalNames;
_globalValues = (_globalNames != null) ? new object[_globalNames.Length] : null;
// Names
_nameTableQuery = _ctxt.QueryNameTable;
_atomizedNames = null;
if (names != null)
{
// Atomize all names in "nameTableQuery". Use names from the default data source's
// name table when possible.
XmlNameTable nameTableDefault = _ctxt.DefaultNameTable;
_atomizedNames = new string[names.Length];
if (nameTableDefault != _nameTableQuery && nameTableDefault != null)
{
// Ensure that atomized names from the default data source are added to the
// name table used in this query
for (i = 0; i < names.Length; i++)
{
string name = nameTableDefault.Get(names[i]);
_atomizedNames[i] = _nameTableQuery.Add(name ?? names[i]);
}
}
else
{
// Enter names into nametable used in this query
for (i = 0; i < names.Length; i++)
_atomizedNames[i] = _nameTableQuery.Add(names[i]);
}
}
// Name filters
_filters = null;
if (filters != null)
{
// Construct name filters. Each pair of integers in the filters[] array specifies the
// (localName, namespaceUri) of the NameFilter to be created.
_filters = new XmlNavigatorFilter[filters.Length];
for (i = 0; i < filters.Length; i++)
_filters[i] = XmlNavNameFilter.Create(_atomizedNames[filters[i].Left], _atomizedNames[filters[i].Right]);
}
// Prefix maping lists
_prefixMappingsList = data.PrefixMappingsList;
// Xml types
_types = data.Types;
// Xml collations
_collations = data.Collations;
// Document ordering
_docOrderCmp = new DocumentOrderComparer();
// Indexes
_indexes = null;
// Output construction
_stkOutput = new Stack<XmlQueryOutput>(16);
_output = new XmlQueryOutput(this, seqWrt);
}
//-----------------------------------------------
// Debugger Utility Methods
//-----------------------------------------------
/// <summary>
/// Return array containing the names of all the global variables and parameters used in this query, in this format:
/// {namespace}prefix:local-name
/// </summary>
public string[] DebugGetGlobalNames()
{
return _globalNames;
}
/// <summary>
/// Get the value of a global value having the specified name. Always return the global value as a list of XPathItem.
/// Return null if there is no global value having the specified name.
/// </summary>
public IList DebugGetGlobalValue(string name)
{
for (int idx = 0; idx < _globalNames.Length; idx++)
{
if (_globalNames[idx] == name)
{
Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed.");
Debug.Assert(_globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios.");
return (IList)_globalValues[idx];
}
}
return null;
}
/// <summary>
/// Set the value of a global value having the specified name. If there is no such value, this method is a no-op.
/// </summary>
public void DebugSetGlobalValue(string name, object value)
{
for (int idx = 0; idx < _globalNames.Length; idx++)
{
if (_globalNames[idx] == name)
{
Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed.");
Debug.Assert(_globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios.");
// Always convert "value" to a list of XPathItem using the item* converter
_globalValues[idx] = (IList<XPathItem>)XmlAnyListConverter.ItemList.ChangeType(value, typeof(XPathItem[]), null);
break;
}
}
}
/// <summary>
/// Convert sequence to it's appropriate XSLT type and return to caller.
/// </summary>
public object DebugGetXsltValue(IList seq)
{
if (seq != null && seq.Count == 1)
{
XPathItem item = seq[0] as XPathItem;
if (item != null && !item.IsNode)
{
return item.TypedValue;
}
else if (item is RtfNavigator)
{
return ((RtfNavigator)item).ToNavigator();
}
}
return seq;
}
//-----------------------------------------------
// Early-Bound Library Objects
//-----------------------------------------------
internal const BindingFlags EarlyBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
internal const BindingFlags LateBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
/// <summary>
/// Return the object that manages external user context information such as data sources, parameters, extension objects, etc.
/// </summary>
public XmlQueryContext ExternalContext
{
get { return _ctxt; }
}
/// <summary>
/// Return the object that manages the state needed to implement various Xslt functions.
/// </summary>
public XsltLibrary XsltFunctions
{
get
{
if (_xsltLib == null)
{
_xsltLib = new XsltLibrary(this);
}
return _xsltLib;
}
}
/// <summary>
/// Get the early-bound extension object identified by "index". If it does not yet exist, create an instance using the
/// corresponding ConstructorInfo.
/// </summary>
public object GetEarlyBoundObject(int index)
{
object obj;
Debug.Assert(_earlyObjects != null && index < _earlyObjects.Length, "Early bound object does not exist");
obj = _earlyObjects[index];
if (obj == null)
{
// Early-bound object does not yet exist, so create it now
obj = _earlyInfo[index].CreateObject();
_earlyObjects[index] = obj;
}
return obj;
}
/// <summary>
/// Return true if the early bound object identified by "namespaceUri" contains a method that matches "name".
/// </summary>
public bool EarlyBoundFunctionExists(string name, string namespaceUri)
{
if (_earlyInfo == null)
return false;
for (int idx = 0; idx < _earlyInfo.Length; idx++)
{
if (namespaceUri == _earlyInfo[idx].NamespaceUri)
return new XmlExtensionFunction(name, namespaceUri, -1, _earlyInfo[idx].EarlyBoundType, EarlyBoundFlags).CanBind();
}
return false;
}
//-----------------------------------------------
// Global variables and parameters
//-----------------------------------------------
/// <summary>
/// Return true if the global value specified by idxValue was previously computed.
/// </summary>
public bool IsGlobalComputed(int index)
{
return _globalValues[index] != null;
}
/// <summary>
/// Return the value that is bound to the global variable or parameter specified by idxValue.
/// If the value has not yet been computed, then compute it now and store it in this.globalValues.
/// </summary>
public object GetGlobalValue(int index)
{
Debug.Assert(IsGlobalComputed(index), "Cannot get the value of a global value until it has been computed.");
return _globalValues[index];
}
/// <summary>
/// Return the value that is bound to the global variable or parameter specified by idxValue.
/// If the value has not yet been computed, then compute it now and store it in this.globalValues.
/// </summary>
public void SetGlobalValue(int index, object value)
{
Debug.Assert(!IsGlobalComputed(index), "Global value should only be set once.");
_globalValues[index] = value;
}
//-----------------------------------------------
// Names, prefix mappings, and name filters
//-----------------------------------------------
/// <summary>
/// Return the name table used to atomize all names used by the query.
/// </summary>
public XmlNameTable NameTable
{
get { return _nameTableQuery; }
}
/// <summary>
/// Get the atomized name at the specified index in the array of names.
/// </summary>
public string GetAtomizedName(int index)
{
Debug.Assert(_atomizedNames != null);
return _atomizedNames[index];
}
/// <summary>
/// Get the name filter at the specified index in the array of filters.
/// </summary>
public XmlNavigatorFilter GetNameFilter(int index)
{
Debug.Assert(_filters != null);
return _filters[index];
}
/// <summary>
/// XPathNodeType.All: Filters all nodes
/// XPathNodeType.Attribute: Filters attributes
/// XPathNodeType.Namespace: Not allowed
/// XPathNodeType.XXX: Filters all nodes *except* those having XPathNodeType.XXX
/// </summary>
public XmlNavigatorFilter GetTypeFilter(XPathNodeType nodeType)
{
if (nodeType == XPathNodeType.All)
return XmlNavNeverFilter.Create();
if (nodeType == XPathNodeType.Attribute)
return XmlNavAttrFilter.Create();
return XmlNavTypeFilter.Create(nodeType);
}
/// <summary>
/// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved,
/// then throw an error. Return an XmlQualifiedName.
/// </summary>
public XmlQualifiedName ParseTagName(string tagName, int indexPrefixMappings)
{
string prefix, localName, ns;
// Parse the tagName as a prefix, localName pair and resolve the prefix
ParseTagName(tagName, indexPrefixMappings, out prefix, out localName, out ns);
return new XmlQualifiedName(localName, ns);
}
/// <summary>
/// Parse the specified tag name (foo:bar). Return an XmlQualifiedName consisting of the parsed local name
/// and the specified namespace.
/// </summary>
public XmlQualifiedName ParseTagName(string tagName, string ns)
{
string prefix, localName;
// Parse the tagName as a prefix, localName pair
ValidateNames.ParseQNameThrow(tagName, out prefix, out localName);
return new XmlQualifiedName(localName, ns);
}
/// <summary>
/// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved,
/// then throw an error. Return the prefix, localName, and namespace URI.
/// </summary>
internal void ParseTagName(string tagName, int idxPrefixMappings, out string prefix, out string localName, out string ns)
{
Debug.Assert(_prefixMappingsList != null);
// Parse the tagName as a prefix, localName pair
ValidateNames.ParseQNameThrow(tagName, out prefix, out localName);
// Map the prefix to a namespace URI
ns = null;
foreach (StringPair pair in _prefixMappingsList[idxPrefixMappings])
{
if (prefix == pair.Left)
{
ns = pair.Right;
break;
}
}
// Throw exception if prefix could not be resolved
if (ns == null)
{
// Check for mappings that are always in-scope
if (prefix.Length == 0)
ns = "";
else if (prefix.Equals("xml"))
ns = XmlReservedNs.NsXml;
// It is not correct to resolve xmlns prefix in XPath but removing it would be a breaking change.
else if (prefix.Equals("xmlns"))
ns = XmlReservedNs.NsXmlNs;
else
throw new XslTransformException(SR.Xslt_InvalidPrefix, prefix);
}
}
/// <summary>
/// Return true if the nav1's LocalName and NamespaceURI properties equal nav2's corresponding properties.
/// </summary>
public bool IsQNameEqual(XPathNavigator n1, XPathNavigator n2)
{
if ((object)n1.NameTable == (object)n2.NameTable)
{
// Use atomized comparison
return (object)n1.LocalName == (object)n2.LocalName && (object)n1.NamespaceURI == (object)n2.NamespaceURI;
}
return (n1.LocalName == n2.LocalName) && (n1.NamespaceURI == n2.NamespaceURI);
}
/// <summary>
/// Return true if the specified navigator's LocalName and NamespaceURI properties equal the argument names.
/// </summary>
public bool IsQNameEqual(XPathNavigator navigator, int indexLocalName, int indexNamespaceUri)
{
if ((object)navigator.NameTable == (object)_nameTableQuery)
{
// Use atomized comparison
return ((object)GetAtomizedName(indexLocalName) == (object)navigator.LocalName &&
(object)GetAtomizedName(indexNamespaceUri) == (object)navigator.NamespaceURI);
}
// Use string comparison
return (GetAtomizedName(indexLocalName) == navigator.LocalName) && (GetAtomizedName(indexNamespaceUri) == navigator.NamespaceURI);
}
/// <summary>
/// Get the Xml query type at the specified index in the array of types.
/// </summary>
internal XmlQueryType GetXmlType(int idxType)
{
Debug.Assert(_types != null);
return _types[idxType];
}
/// <summary>
/// Forward call to ChangeTypeXsltArgument(XmlQueryType, object, Type).
/// </summary>
public object ChangeTypeXsltArgument(int indexType, object value, Type destinationType)
{
return ChangeTypeXsltArgument(GetXmlType(indexType), value, destinationType);
}
/// <summary>
/// Convert from the Clr type of "value" to Clr type "destinationType" using V1 Xslt rules.
/// These rules include converting any Rtf values to Nodes.
/// </summary>
internal object ChangeTypeXsltArgument(XmlQueryType xmlType, object value, Type destinationType)
{
#if FEATURE_COMPILED_XSL
Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()),
"Values passed to ChangeTypeXsltArgument should be in ILGen's default Clr representation.");
#endif
Debug.Assert(destinationType == XsltConvert.ObjectType || !destinationType.IsAssignableFrom(value.GetType()),
"No need to call ChangeTypeXsltArgument since value is already assignable to destinationType " + destinationType);
switch (xmlType.TypeCode)
{
case XmlTypeCode.String:
if (destinationType == XsltConvert.DateTimeType)
value = XsltConvert.ToDateTime((string)value);
break;
case XmlTypeCode.Double:
if (destinationType != XsltConvert.DoubleType)
value = Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture);
break;
case XmlTypeCode.Node:
Debug.Assert(xmlType != XmlQueryTypeFactory.Node && xmlType != XmlQueryTypeFactory.NodeS,
"Rtf values should have been eliminated by caller.");
if (destinationType == XsltConvert.XPathNodeIteratorType)
{
value = new XPathArrayIterator((IList)value);
}
else if (destinationType == XsltConvert.XPathNavigatorArrayType)
{
// Copy sequence to XPathNavigator[]
IList<XPathNavigator> seq = (IList<XPathNavigator>)value;
XPathNavigator[] navArray = new XPathNavigator[seq.Count];
for (int i = 0; i < seq.Count; i++)
navArray[i] = seq[i];
value = navArray;
}
break;
case XmlTypeCode.Item:
{
// Only typeof(object) is supported as a destination type
if (destinationType != XsltConvert.ObjectType)
throw new XslTransformException(SR.Xslt_UnsupportedClrType, destinationType.Name);
// Convert to default, backwards-compatible representation
// 1. NodeSet: System.Xml.XPath.XPathNodeIterator
// 2. Rtf: System.Xml.XPath.XPathNavigator
// 3. Other: Default V1 representation
IList<XPathItem> seq = (IList<XPathItem>)value;
if (seq.Count == 1)
{
XPathItem item = seq[0];
if (item.IsNode)
{
// Node or Rtf
RtfNavigator rtf = item as RtfNavigator;
if (rtf != null)
value = rtf.ToNavigator();
else
value = new XPathArrayIterator((IList)value);
}
else
{
// Atomic value
value = item.TypedValue;
}
}
else
{
// Nodeset
value = new XPathArrayIterator((IList)value);
}
break;
}
}
Debug.Assert(destinationType.IsAssignableFrom(value.GetType()), "ChangeType from type " + value.GetType().Name + " to type " + destinationType.Name + " failed");
return value;
}
/// <summary>
/// Forward call to ChangeTypeXsltResult(XmlQueryType, object)
/// </summary>
public object ChangeTypeXsltResult(int indexType, object value)
{
return ChangeTypeXsltResult(GetXmlType(indexType), value);
}
/// <summary>
/// Convert from the Clr type of "value" to the default Clr type that ILGen uses to represent the xml type, using
/// the conversion rules of the xml type.
/// </summary>
internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value)
{
if (value == null)
throw new XslTransformException(SR.Xslt_ItemNull, string.Empty);
switch (xmlType.TypeCode)
{
case XmlTypeCode.String:
if (value.GetType() == XsltConvert.DateTimeType)
value = XsltConvert.ToString((DateTime)value);
break;
case XmlTypeCode.Double:
if (value.GetType() != XsltConvert.DoubleType)
value = ((IConvertible)value).ToDouble(null);
break;
case XmlTypeCode.Node:
if (!xmlType.IsSingleton)
{
XPathArrayIterator iter = value as XPathArrayIterator;
// Special-case XPathArrayIterator in order to avoid copies
if (iter != null && iter.AsList is XmlQueryNodeSequence)
{
value = iter.AsList as XmlQueryNodeSequence;
}
else
{
// Iterate over list and ensure it only contains nodes
XmlQueryNodeSequence seq = new XmlQueryNodeSequence();
IList list = value as IList;
if (list != null)
{
for (int i = 0; i < list.Count; i++)
seq.Add(EnsureNavigator(list[i]));
}
else
{
foreach (object o in (IEnumerable)value)
seq.Add(EnsureNavigator(o));
}
value = seq;
}
// Always sort node-set by document order
value = ((XmlQueryNodeSequence)value).DocOrderDistinct(_docOrderCmp);
}
break;
case XmlTypeCode.Item:
{
Type sourceType = value.GetType();
IXPathNavigable navigable;
// If static type is item, then infer type based on dynamic value
switch (XsltConvert.InferXsltType(sourceType).TypeCode)
{
case XmlTypeCode.Boolean:
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), value));
break;
case XmlTypeCode.Double:
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), ((IConvertible)value).ToDouble(null)));
break;
case XmlTypeCode.String:
if (sourceType == XsltConvert.DateTimeType)
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), XsltConvert.ToString((DateTime)value)));
else
value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), value));
break;
case XmlTypeCode.Node:
// Support XPathNavigator[]
value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value);
break;
case XmlTypeCode.Item:
// Support XPathNodeIterator
if (value is XPathNodeIterator)
{
value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value);
break;
}
// Support IXPathNavigable and XPathNavigator
navigable = value as IXPathNavigable;
if (navigable != null)
{
if (value is XPathNavigator)
value = new XmlQueryNodeSequence((XPathNavigator)value);
else
value = new XmlQueryNodeSequence(navigable.CreateNavigator());
break;
}
throw new XslTransformException(SR.Xslt_UnsupportedClrType, sourceType.Name);
}
break;
}
}
#if FEATURE_COMPILED_XSL
Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Xml type " + xmlType + " is not represented in ILGen as " + value.GetType().Name);
#endif
return value;
}
/// <summary>
/// Ensure that "value" is a navigator and not null.
/// </summary>
private static XPathNavigator EnsureNavigator(object value)
{
XPathNavigator nav = value as XPathNavigator;
if (nav == null)
throw new XslTransformException(SR.Xslt_ItemNull, string.Empty);
return nav;
}
/// <summary>
/// Return true if the type of every item in "seq" matches the xml type identified by "idxType".
/// </summary>
public bool MatchesXmlType(IList<XPathItem> seq, int indexType)
{
XmlQueryType typBase = GetXmlType(indexType);
XmlQueryCardinality card = seq.Count switch
{
0 => XmlQueryCardinality.Zero,
1 => XmlQueryCardinality.One,
_ => XmlQueryCardinality.More,
};
if (!(card <= typBase.Cardinality))
return false;
typBase = typBase.Prime;
for (int i = 0; i < seq.Count; i++)
{
if (!CreateXmlType(seq[0]).IsSubtypeOf(typBase))
return false;
}
return true;
}
/// <summary>
/// Return true if the type of "item" matches the xml type identified by "idxType".
/// </summary>
public bool MatchesXmlType(XPathItem item, int indexType)
{
return CreateXmlType(item).IsSubtypeOf(GetXmlType(indexType));
}
/// <summary>
/// Return true if the type of "seq" is a subtype of a singleton type identified by "code".
/// </summary>
public bool MatchesXmlType(IList<XPathItem> seq, XmlTypeCode code)
{
if (seq.Count != 1)
return false;
return MatchesXmlType(seq[0], code);
}
/// <summary>
/// Return true if the type of "item" is a subtype of the type identified by "code".
/// </summary>
public bool MatchesXmlType(XPathItem item, XmlTypeCode code)
{
// All atomic type codes appear after AnyAtomicType
if (code > XmlTypeCode.AnyAtomicType)
return !item.IsNode && item.XmlType.TypeCode == code;
// Handle node code and AnyAtomicType
switch (code)
{
case XmlTypeCode.AnyAtomicType: return !item.IsNode;
case XmlTypeCode.Node: return item.IsNode;
case XmlTypeCode.Item: return true;
default:
if (!item.IsNode)
return false;
switch (((XPathNavigator)item).NodeType)
{
case XPathNodeType.Root: return code == XmlTypeCode.Document;
case XPathNodeType.Element: return code == XmlTypeCode.Element;
case XPathNodeType.Attribute: return code == XmlTypeCode.Attribute;
case XPathNodeType.Namespace: return code == XmlTypeCode.Namespace;
case XPathNodeType.Text: return code == XmlTypeCode.Text;
case XPathNodeType.SignificantWhitespace: return code == XmlTypeCode.Text;
case XPathNodeType.Whitespace: return code == XmlTypeCode.Text;
case XPathNodeType.ProcessingInstruction: return code == XmlTypeCode.ProcessingInstruction;
case XPathNodeType.Comment: return code == XmlTypeCode.Comment;
}
break;
}
Debug.Fail("XmlTypeCode " + code + " was not fully handled.");
return false;
}
/// <summary>
/// Create an XmlQueryType that represents the type of "item".
/// </summary>
private XmlQueryType CreateXmlType(XPathItem item)
{
if (item.IsNode)
{
// Rtf
RtfNavigator rtf = item as RtfNavigator;
if (rtf != null)
return XmlQueryTypeFactory.Node;
// Node
XPathNavigator nav = (XPathNavigator)item;
switch (nav.NodeType)
{
case XPathNodeType.Root:
case XPathNodeType.Element:
if (nav.XmlType == null)
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), XmlSchemaComplexType.UntypedAnyType, false);
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, nav.SchemaInfo.SchemaElement.IsNillable);
case XPathNodeType.Attribute:
if (nav.XmlType == null)
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), DatatypeImplementation.UntypedAtomicType, false);
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, false);
}
return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.Wildcard, XmlSchemaComplexType.AnyType, false);
}
// Atomic value
return XmlQueryTypeFactory.Type((XmlSchemaSimpleType)item.XmlType, true);
}
//-----------------------------------------------
// Xml collations
//-----------------------------------------------
/// <summary>
/// Get a collation that was statically created.
/// </summary>
public XmlCollation GetCollation(int index)
{
Debug.Assert(_collations != null);
return _collations[index];
}
/// <summary>
/// Create a collation from a string.
/// </summary>
public XmlCollation CreateCollation(string collation)
{
return XmlCollation.Create(collation);
}
//-----------------------------------------------
// Document Ordering and Identity
//-----------------------------------------------
/// <summary>
/// Compare the relative positions of two navigators. Return -1 if navThis is before navThat, 1 if after, and
/// 0 if they are positioned to the same node.
/// </summary>
public int ComparePosition(XPathNavigator navigatorThis, XPathNavigator navigatorThat)
{
return _docOrderCmp.Compare(navigatorThis, navigatorThat);
}
/// <summary>
/// Get a comparer which guarantees a stable ordering among nodes, even those from different documents.
/// </summary>
public IList<XPathNavigator> DocOrderDistinct(IList<XPathNavigator> seq)
{
if (seq.Count <= 1)
return seq;
XmlQueryNodeSequence nodeSeq = (XmlQueryNodeSequence)seq;
if (nodeSeq == null)
nodeSeq = new XmlQueryNodeSequence(seq);
return nodeSeq.DocOrderDistinct(_docOrderCmp);
}
/// <summary>
/// Generate a unique string identifier for the specified node. Do this by asking the navigator for an identifier
/// that is unique within the document, and then prepend a document index.
/// </summary>
public string GenerateId(XPathNavigator navigator)
{
return string.Concat("ID", _docOrderCmp.GetDocumentIndex(navigator).ToString(CultureInfo.InvariantCulture), navigator.UniqueId);
}
//-----------------------------------------------
// Indexes
//-----------------------------------------------
/// <summary>
/// If an index having the specified Id has already been created over the "context" document, then return it
/// in "index" and return true. Otherwise, create a new, empty index and return false.
/// </summary>
public bool FindIndex(XPathNavigator context, int indexId, out XmlILIndex index)
{
XPathNavigator navRoot;
ArrayList docIndexes;
Debug.Assert(context != null);
// Get root of document
navRoot = context.Clone();
navRoot.MoveToRoot();
// Search pre-existing indexes in order to determine whether the specified index has already been created
if (_indexes != null && indexId < _indexes.Length)
{
docIndexes = (ArrayList)_indexes[indexId];
if (docIndexes != null)
{
// Search for an index defined over the specified document
for (int i = 0; i < docIndexes.Count; i += 2)
{
// If we find a matching document, then return the index saved in the next slot
if (((XPathNavigator)docIndexes[i]).IsSamePosition(navRoot))
{
index = (XmlILIndex)docIndexes[i + 1];
return true;
}
}
}
}
// Return a new, empty index
index = new XmlILIndex();
return false;
}
/// <summary>
/// Add a newly built index over the specified "context" document to the existing collection of indexes.
/// </summary>
public void AddNewIndex(XPathNavigator context, int indexId, XmlILIndex index)
{
XPathNavigator navRoot;
ArrayList docIndexes;
Debug.Assert(context != null);
// Get root of document
navRoot = context.Clone();
navRoot.MoveToRoot();
// Ensure that a slot exists for the new index
if (_indexes == null)
{
_indexes = new ArrayList[indexId + 4];
}
else if (indexId >= _indexes.Length)
{
// Resize array
ArrayList[] indexesNew = new ArrayList[indexId + 4];
Array.Copy(_indexes, 0, indexesNew, 0, _indexes.Length);
_indexes = indexesNew;
}
docIndexes = (ArrayList)_indexes[indexId];
if (docIndexes == null)
{
docIndexes = new ArrayList();
_indexes[indexId] = docIndexes;
}
docIndexes.Add(navRoot);
docIndexes.Add(index);
}
//-----------------------------------------------
// Output construction
//-----------------------------------------------
/// <summary>
/// Get output writer object.
/// </summary>
public XmlQueryOutput Output
{
get { return _output; }
}
/// <summary>
/// Start construction of a nested sequence of items. Return a new XmlQueryOutput that will be
/// used to construct this new sequence.
/// </summary>
public void StartSequenceConstruction(out XmlQueryOutput output)
{
// Push current writer
_stkOutput.Push(_output);
// Create new writers
output = _output = new XmlQueryOutput(this, new XmlCachedSequenceWriter());
}
/// <summary>
/// End construction of a nested sequence of items and return the items as an IList{XPathItem}
/// internal class. Return previous XmlQueryOutput.
/// </summary>
public IList<XPathItem> EndSequenceConstruction(out XmlQueryOutput output)
{
IList<XPathItem> seq = ((XmlCachedSequenceWriter)_output.SequenceWriter).ResultSequence;
// Restore previous XmlQueryOutput
output = _output = _stkOutput.Pop();
return seq;
}
/// <summary>
/// Start construction of an Rtf. Return a new XmlQueryOutput object that will be used to construct this Rtf.
/// </summary>
public void StartRtfConstruction(string baseUri, out XmlQueryOutput output)
{
// Push current writer
_stkOutput.Push(_output);
// Create new XmlQueryOutput over an Rtf writer
output = _output = new XmlQueryOutput(this, new XmlEventCache(baseUri, true));
}
/// <summary>
/// End construction of an Rtf and return it as an RtfNavigator. Return previous XmlQueryOutput object.
/// </summary>
public XPathNavigator EndRtfConstruction(out XmlQueryOutput output)
{
XmlEventCache events;
events = (XmlEventCache)_output.Writer;
// Restore previous XmlQueryOutput
output = _output = _stkOutput.Pop();
// Return Rtf as an RtfNavigator
events.EndEvents();
return new RtfTreeNavigator(events, _nameTableQuery);
}
/// <summary>
/// Construct a new RtfTextNavigator from the specified "text". This is much more efficient than calling
/// StartNodeConstruction(), StartRtf(), WriteString(), EndRtf(), and EndNodeConstruction().
/// </summary>
public XPathNavigator TextRtfConstruction(string text, string baseUri)
{
return new RtfTextNavigator(text, baseUri);
}
//-----------------------------------------------
// Miscellaneous
//-----------------------------------------------
/// <summary>
/// Report query execution information to event handler.
/// </summary>
public void SendMessage(string message)
{
_ctxt.OnXsltMessageEncountered(message);
}
/// <summary>
/// Throw an Xml exception having the specified message text.
/// </summary>
public void ThrowException(string text)
{
throw new XslTransformException(text);
}
/// <summary>
/// Position navThis to the same location as navThat.
/// </summary>
internal static XPathNavigator SyncToNavigator(XPathNavigator navigatorThis, XPathNavigator navigatorThat)
{
if (navigatorThis == null || !navigatorThis.MoveTo(navigatorThat))
return navigatorThat.Clone();
return navigatorThis;
}
/// <summary>
/// Function is called in Debug mode on each time context node change.
/// </summary>
public static int OnCurrentNodeChanged(XPathNavigator currentNode)
{
IXmlLineInfo lineInfo = currentNode as IXmlLineInfo;
// In case of a namespace node, check whether it is inherited or locally defined
if (lineInfo != null && !(currentNode.NodeType == XPathNodeType.Namespace && IsInheritedNamespace(currentNode)))
{
OnCurrentNodeChanged2(currentNode.BaseURI, lineInfo.LineNumber, lineInfo.LinePosition);
}
return 0;
}
// 'true' if current Namespace "inherited" from it's parent. Not defined locally.
private static bool IsInheritedNamespace(XPathNavigator node)
{
Debug.Assert(node.NodeType == XPathNodeType.Namespace);
XPathNavigator nav = node.Clone();
if (nav.MoveToParent())
{
if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local))
{
do
{
if ((object)nav.LocalName == (object)node.LocalName)
{
return false;
}
} while (nav.MoveToNextNamespace(XPathNamespaceScope.Local));
}
}
return true;
}
private static void OnCurrentNodeChanged2(string baseUri, int lineNumber, int linePosition) { }
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Threading;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Events;
using Umbraco.Core.Exceptions;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the ContentType Service, which is an easy access to operations involving <see cref="IContentType"/>
/// </summary>
public class ContentTypeService : ContentTypeServiceBase, IContentTypeService
{
private readonly RepositoryFactory _repositoryFactory;
private readonly IContentService _contentService;
private readonly IMediaService _mediaService;
private readonly IDatabaseUnitOfWorkProvider _uowProvider;
//Support recursive locks because some of the methods that require locking call other methods that require locking.
//for example, the Move method needs to be locked but this calls the Save method which also needs to be locked.
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public ContentTypeService(IContentService contentService, IMediaService mediaService)
: this(new PetaPocoUnitOfWorkProvider(), new RepositoryFactory(), contentService, mediaService)
{}
public ContentTypeService(RepositoryFactory repositoryFactory, IContentService contentService, IMediaService mediaService)
: this(new PetaPocoUnitOfWorkProvider(), repositoryFactory, contentService, mediaService)
{ }
public ContentTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, IContentService contentService, IMediaService mediaService)
{
_uowProvider = provider;
_repositoryFactory = repositoryFactory;
_contentService = contentService;
_mediaService = mediaService;
}
/// <summary>
/// Gets all property type aliases.
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetAllPropertyTypeAliases()
{
using (var repository = _repositoryFactory.CreateContentTypeRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetAllPropertyTypeAliases();
}
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parentId">
/// The parent to copy the content type to, default is -1 (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, int parentId = -1)
{
IContentType parent = null;
if (parentId > 0)
{
parent = GetContentType(parentId);
if (parent == null)
{
throw new InvalidOperationException("Could not find content type with id " + parentId);
}
}
return Copy(original, alias, name, parent);
}
/// <summary>
/// Copies a content type as a child under the specified parent if specified (otherwise to the root)
/// </summary>
/// <param name="original">
/// The content type to copy
/// </param>
/// <param name="alias">
/// The new alias of the content type
/// </param>
/// <param name="name">
/// The new name of the content type
/// </param>
/// <param name="parent">
/// The parent to copy the content type to, default is null (root)
/// </param>
/// <returns></returns>
public IContentType Copy(IContentType original, string alias, string name, IContentType parent)
{
Mandate.ParameterNotNull(original, "original");
Mandate.ParameterNotNullOrEmpty(alias, "alias");
if (parent != null)
{
Mandate.That(parent.HasIdentity, () => new InvalidOperationException("The parent content type must have an identity"));
}
var clone = original.DeepCloneWithResetIdentities(alias);
clone.Name = name;
var compositionAliases = clone.CompositionAliases().Except(new[] { alias }).ToList();
//remove all composition that is not it's current alias
foreach (var a in compositionAliases)
{
clone.RemoveContentType(a);
}
//if a parent is specified set it's composition and parent
if (parent != null)
{
//add a new parent composition
clone.AddContentType(parent);
clone.ParentId = parent.Id;
}
else
{
//set to root
clone.ParentId = -1;
}
Save(clone);
return clone;
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(int id)
{
using (var repository = _repositoryFactory.CreateContentTypeRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IContentType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IContentType"/> to retrieve</param>
/// <returns><see cref="IContentType"/></returns>
public IContentType GetContentType(string alias)
{
using (var repository = _repositoryFactory.CreateContentTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.Alias == alias);
var contentTypes = repository.GetByQuery(query);
return contentTypes.FirstOrDefault();
}
}
/// <summary>
/// Gets a list of all available <see cref="IContentType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetAllContentTypes(params int[] ids)
{
using (var repository = _repositoryFactory.CreateContentTypeRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of children for a <see cref="IContentType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IContentType"/> objects</returns>
public IEnumerable<IContentType> GetContentTypeChildren(int id)
{
using (var repository = _repositoryFactory.CreateContentTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
///// <summary>
///// Returns the content type descendant Ids for the content type specified
///// </summary>
///// <param name="contentTypeId"></param>
///// <returns></returns>
//internal IEnumerable<int> GetDescendantContentTypeIds(int contentTypeId)
//{
// using (var uow = _uowProvider.GetUnitOfWork())
// {
// //method to return the child content type ids for the id specified
// Func<int, int[]> getChildIds =
// parentId =>
// uow.Database.Fetch<ContentType2ContentTypeDto>("WHERE parentContentTypeId = @Id", new {Id = parentId})
// .Select(x => x.ChildId).ToArray();
// //recursively get all descendant ids
// return getChildIds(contentTypeId).FlattenList(getChildIds);
// }
//}
/// <summary>
/// Checks whether an <see cref="IContentType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>True if the content type has any children otherwise False</returns>
public bool HasChildren(int id)
{
using (var repository = _repositoryFactory.CreateContentTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IContentType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// This is called after an IContentType is saved and is used to update the content xml structures in the database
/// if they are required to be updated.
/// </summary>
/// <param name="contentTypes">A tuple of a content type and a boolean indicating if it is new (HasIdentity was false before committing)</param>
private void UpdateContentXmlStructure(params IContentTypeBase[] contentTypes)
{
var toUpdate = GetContentTypesForXmlUpdates(contentTypes).ToArray();
if (toUpdate.Any())
{
var firstType = toUpdate.First();
//if it is a content type then call the rebuilding methods or content
if (firstType is IContentType)
{
var typedContentService = _contentService as ContentService;
if (typedContentService != null)
{
typedContentService.RePublishAll(toUpdate.Select(x => x.Id).ToArray());
}
else
{
//this should never occur, the content service should always be typed but we'll check anyways.
_contentService.RePublishAll();
}
}
else if (firstType is IMediaType)
{
//if it is a media type then call the rebuilding methods for media
var typedContentService = _mediaService as MediaService;
if (typedContentService != null)
{
typedContentService.RebuildXmlStructures(toUpdate.Select(x => x.Id).ToArray());
}
}
}
}
public void Validate(IContentTypeComposition compo)
{
using (new WriteLock(Locker))
{
ValidateLocked(compo);
}
}
private void ValidateLocked(IContentTypeComposition compositionContentType)
{
// performs business-level validation of the composition
// should ensure that it is absolutely safe to save the composition
// eg maybe a property has been added, with an alias that's OK (no conflict with ancestors)
// but that cannot be used (conflict with descendants)
var contentType = compositionContentType as IContentType;
var mediaType = compositionContentType as IMediaType;
IContentTypeComposition[] allContentTypes;
if (contentType != null)
allContentTypes = GetAllContentTypes().Cast<IContentTypeComposition>().ToArray();
else if (mediaType != null)
allContentTypes = GetAllMediaTypes().Cast<IContentTypeComposition>().ToArray();
else
throw new Exception("Composition is neither IContentType nor IMediaType?");
var compositionAliases = compositionContentType.CompositionAliases();
var compositions = allContentTypes.Where(x => compositionAliases.Any(y => x.Alias.Equals(y)));
var propertyTypeAliases = compositionContentType.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).ToArray();
var indirectReferences = allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == compositionContentType.Id));
var comparer = new DelegateEqualityComparer<IContentTypeComposition>((x, y) => x.Id == y.Id, x => x.Id);
var dependencies = new HashSet<IContentTypeComposition>(compositions, comparer);
var stack = new Stack<IContentTypeComposition>();
indirectReferences.ForEach(stack.Push);//Push indirect references to a stack, so we can add recursively
while (stack.Count > 0)
{
var indirectReference = stack.Pop();
dependencies.Add(indirectReference);
//Get all compositions for the current indirect reference
var directReferences = indirectReference.ContentTypeComposition;
foreach (var directReference in directReferences)
{
if (directReference.Id == compositionContentType.Id || directReference.Alias.Equals(compositionContentType.Alias)) continue;
dependencies.Add(directReference);
//A direct reference has compositions of its own - these also need to be taken into account
var directReferenceGraph = directReference.CompositionAliases();
allContentTypes.Where(x => directReferenceGraph.Any(y => x.Alias.Equals(y, StringComparison.InvariantCultureIgnoreCase))).ForEach(c => dependencies.Add(c));
}
//Recursive lookup of indirect references
allContentTypes.Where(x => x.ContentTypeComposition.Any(y => y.Id == indirectReference.Id)).ForEach(stack.Push);
}
foreach (var dependency in dependencies)
{
if (dependency.Id == compositionContentType.Id) continue;
var contentTypeDependency = allContentTypes.FirstOrDefault(x => x.Alias.Equals(dependency.Alias, StringComparison.InvariantCultureIgnoreCase));
if (contentTypeDependency == null) continue;
var intersect = contentTypeDependency.PropertyTypes.Select(x => x.Alias.ToLowerInvariant()).Intersect(propertyTypeAliases).ToArray();
if (intersect.Length == 0) continue;
var message = string.Format("The following PropertyType aliases from the current ContentType conflict with existing PropertyType aliases: {0}.",
string.Join(", ", intersect));
throw new Exception(message);
}
}
/// <summary>
/// Saves a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IContentType contentType, int userId = 0)
{
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateContentTypeRepository(uow))
{
ValidateLocked(contentType); // throws if invalid
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
uow.Commit();
}
UpdateContentXmlStructure(contentType);
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(contentType, false), this);
Audit.Add(AuditTypes.Save, string.Format("Save ContentType performed by user"), userId, contentType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IContentType"/> objects
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to save</param>
/// <param name="userId">Optional id of the user saving the ContentType</param>
public void Save(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (SavingContentType.IsRaisedEventCancelled(new SaveEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateContentTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var contentType in asArray)
{
ValidateLocked(contentType); // throws if invalid
}
foreach (var contentType in asArray)
{
contentType.CreatorId = userId;
repository.AddOrUpdate(contentType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedContentType.RaiseEvent(new SaveEventArgs<IContentType>(asArray, false), this);
Audit.Add(AuditTypes.Save, string.Format("Save ContentTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IContentType"/> object
/// </summary>
/// <param name="contentType"><see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/></remarks>
public void Delete(IContentType contentType, int userId = 0)
{
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(contentType), this))
return;
using (new WriteLock(Locker))
{
_contentService.DeleteContentOfType(contentType.Id);
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateContentTypeRepository(uow))
{
repository.Delete(contentType);
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(contentType, false), this);
}
Audit.Add(AuditTypes.Delete, string.Format("Delete ContentType performed by user"), userId, contentType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IContentType"/> objects.
/// </summary>
/// <param name="contentTypes">Collection of <see cref="IContentType"/> to delete</param>
/// <param name="userId">Optional id of the user issueing the delete</param>
/// <remarks>
/// Deleting a <see cref="IContentType"/> will delete all the <see cref="IContent"/> objects based on this <see cref="IContentType"/>
/// </remarks>
public void Delete(IEnumerable<IContentType> contentTypes, int userId = 0)
{
var asArray = contentTypes.ToArray();
if (DeletingContentType.IsRaisedEventCancelled(new DeleteEventArgs<IContentType>(asArray), this))
return;
using (new WriteLock(Locker))
{
foreach (var contentType in asArray)
{
_contentService.DeleteContentOfType(contentType.Id);
}
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateContentTypeRepository(uow))
{
foreach (var contentType in asArray)
{
repository.Delete(contentType);
}
uow.Commit();
DeletedContentType.RaiseEvent(new DeleteEventArgs<IContentType>(asArray, false), this);
}
Audit.Add(AuditTypes.Delete, string.Format("Delete ContentTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Id
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(int id)
{
using (var repository = _repositoryFactory.CreateMediaTypeRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Gets an <see cref="IMediaType"/> object by its Alias
/// </summary>
/// <param name="alias">Alias of the <see cref="IMediaType"/> to retrieve</param>
/// <returns><see cref="IMediaType"/></returns>
public IMediaType GetMediaType(string alias)
{
using (var repository = _repositoryFactory.CreateMediaTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.Alias == alias);
var contentTypes = repository.GetByQuery(query);
return contentTypes.FirstOrDefault();
}
}
/// <summary>
/// Gets a list of all available <see cref="IMediaType"/> objects
/// </summary>
/// <param name="ids">Optional list of ids</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetAllMediaTypes(params int[] ids)
{
using (var repository = _repositoryFactory.CreateMediaTypeRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetAll(ids);
}
}
/// <summary>
/// Gets a list of children for a <see cref="IMediaType"/> object
/// </summary>
/// <param name="id">Id of the Parent</param>
/// <returns>An Enumerable list of <see cref="IMediaType"/> objects</returns>
public IEnumerable<IMediaType> GetMediaTypeChildren(int id)
{
using (var repository = _repositoryFactory.CreateMediaTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
var contentTypes = repository.GetByQuery(query);
return contentTypes;
}
}
/// <summary>
/// Checks whether an <see cref="IMediaType"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>True if the media type has any children otherwise False</returns>
public bool MediaTypeHasChildren(int id)
{
using (var repository = _repositoryFactory.CreateMediaTypeRepository(_uowProvider.GetUnitOfWork()))
{
var query = Query<IMediaType>.Builder.Where(x => x.ParentId == id);
int count = repository.Count(query);
return count > 0;
}
}
/// <summary>
/// Saves a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user saving the MediaType</param>
public void Save(IMediaType mediaType, int userId = 0)
{
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaTypeRepository(uow))
{
ValidateLocked(mediaType); // throws if invalid
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
uow.Commit();
}
UpdateContentXmlStructure(mediaType);
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(mediaType, false), this);
Audit.Add(AuditTypes.Save, string.Format("Save MediaType performed by user"), userId, mediaType.Id);
}
/// <summary>
/// Saves a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to save</param>
/// <param name="userId">Optional Id of the user savging the MediaTypes</param>
public void Save(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (SavingMediaType.IsRaisedEventCancelled(new SaveEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaTypeRepository(uow))
{
// all-or-nothing, validate them all first
foreach (var mediaType in asArray)
{
ValidateLocked(mediaType); // throws if invalid
}
foreach (var mediaType in asArray)
{
mediaType.CreatorId = userId;
repository.AddOrUpdate(mediaType);
}
//save it all in one go
uow.Commit();
}
UpdateContentXmlStructure(asArray.Cast<IContentTypeBase>().ToArray());
}
SavedMediaType.RaiseEvent(new SaveEventArgs<IMediaType>(asArray, false), this);
Audit.Add(AuditTypes.Save, string.Format("Save MediaTypes performed by user"), userId, -1);
}
/// <summary>
/// Deletes a single <see cref="IMediaType"/> object
/// </summary>
/// <param name="mediaType"><see cref="IMediaType"/> to delete</param>
/// <param name="userId">Optional Id of the user deleting the MediaType</param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IMediaType mediaType, int userId = 0)
{
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(mediaType), this))
return;
using (new WriteLock(Locker))
{
_mediaService.DeleteMediaOfType(mediaType.Id, userId);
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaTypeRepository(uow))
{
repository.Delete(mediaType);
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(mediaType, false), this);
}
Audit.Add(AuditTypes.Delete, string.Format("Delete MediaType performed by user"), userId, mediaType.Id);
}
}
/// <summary>
/// Deletes a collection of <see cref="IMediaType"/> objects
/// </summary>
/// <param name="mediaTypes">Collection of <see cref="IMediaType"/> to delete</param>
/// <param name="userId"></param>
/// <remarks>Deleting a <see cref="IMediaType"/> will delete all the <see cref="IMedia"/> objects based on this <see cref="IMediaType"/></remarks>
public void Delete(IEnumerable<IMediaType> mediaTypes, int userId = 0)
{
var asArray = mediaTypes.ToArray();
if (DeletingMediaType.IsRaisedEventCancelled(new DeleteEventArgs<IMediaType>(asArray), this))
return;
using (new WriteLock(Locker))
{
foreach (var mediaType in asArray)
{
_mediaService.DeleteMediaOfType(mediaType.Id);
}
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateMediaTypeRepository(uow))
{
foreach (var mediaType in asArray)
{
repository.Delete(mediaType);
}
uow.Commit();
DeletedMediaType.RaiseEvent(new DeleteEventArgs<IMediaType>(asArray, false), this);
}
Audit.Add(AuditTypes.Delete, string.Format("Delete MediaTypes performed by user"), userId, -1);
}
}
/// <summary>
/// Generates the complete (simplified) XML DTD.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetDtd()
{
var dtd = new StringBuilder();
dtd.AppendLine("<!DOCTYPE root [ ");
dtd.AppendLine(GetContentTypesDtd());
dtd.AppendLine("]>");
return dtd.ToString();
}
/// <summary>
/// Generates the complete XML DTD without the root.
/// </summary>
/// <returns>The DTD as a string</returns>
public string GetContentTypesDtd()
{
var dtd = new StringBuilder();
if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
dtd.AppendLine("<!ELEMENT node ANY> <!ATTLIST node id ID #REQUIRED> <!ELEMENT data ANY>");
}
else
{
try
{
var strictSchemaBuilder = new StringBuilder();
var contentTypes = GetAllContentTypes();
foreach (ContentType contentType in contentTypes)
{
string safeAlias = contentType.Alias.ToUmbracoAlias();
if (safeAlias != null)
{
strictSchemaBuilder.AppendLine(String.Format("<!ELEMENT {0} ANY>", safeAlias));
strictSchemaBuilder.AppendLine(String.Format("<!ATTLIST {0} id ID #REQUIRED>", safeAlias));
}
}
// Only commit the strong schema to the container if we didn't generate an error building it
dtd.Append(strictSchemaBuilder);
}
catch (Exception exception)
{
LogHelper.Error<ContentTypeService>("Error while trying to build DTD for Xml schema; is Umbraco installed correctly and the connection string configured?", exception);
}
}
return dtd.ToString();
}
#region Event Handlers
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletingContentType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IContentType>> DeletedContentType;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletingMediaType;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IContentTypeService, DeleteEventArgs<IMediaType>> DeletedMediaType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavingContentType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IContentType>> SavedContentType;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavingMediaType;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IContentTypeService, SaveEventArgs<IMediaType>> SavedMediaType;
#endregion
}
}
| |
#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.Reflection;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Utilities.LinqBridge;
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Maps a JSON property to a .NET member or constructor parameter.
/// </summary>
public class JsonProperty
{
internal Required? _required;
internal bool _hasExplicitDefaultValue;
private object _defaultValue;
private bool _hasGeneratedDefaultValue;
private string _propertyName;
internal bool _skipPropertyNameEscape;
private Type _propertyType;
// use to cache contract during deserialization
internal JsonContract PropertyContract { get; set; }
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
_skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags);
}
}
/// <summary>
/// Gets or sets the type that declared this property.
/// </summary>
/// <value>The type that declared this property.</value>
public Type DeclaringType { get; set; }
/// <summary>
/// Gets or sets the order of serialization and deserialization of a member.
/// </summary>
/// <value>The numeric order of serialization or deserialization.</value>
public int? Order { get; set; }
/// <summary>
/// Gets or sets the name of the underlying member or parameter.
/// </summary>
/// <value>The name of the underlying member or parameter.</value>
public string UnderlyingName { get; set; }
/// <summary>
/// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.
/// </summary>
/// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value>
public IValueProvider ValueProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="IAttributeProvider"/> for this property.
/// </summary>
/// <value>The <see cref="IAttributeProvider"/> for this property.</value>
public IAttributeProvider AttributeProvider { get; set; }
/// <summary>
/// Gets or sets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type PropertyType
{
get { return _propertyType; }
set
{
if (_propertyType != value)
{
_propertyType = value;
_hasGeneratedDefaultValue = false;
}
}
}
/// <summary>
/// Gets or sets the <see cref="JsonConverter" /> for the property.
/// If set this converter takes presidence over the contract converter for the property type.
/// </summary>
/// <value>The converter.</value>
public JsonConverter Converter { get; set; }
/// <summary>
/// Gets or sets the member converter.
/// </summary>
/// <value>The member converter.</value>
public JsonConverter MemberConverter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is ignored.
/// </summary>
/// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value>
public bool Ignored { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is readable.
/// </summary>
/// <value><c>true</c> if readable; otherwise, <c>false</c>.</value>
public bool Readable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is writable.
/// </summary>
/// <value><c>true</c> if writable; otherwise, <c>false</c>.</value>
public bool Writable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> has a member attribute.
/// </summary>
/// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value>
public bool HasMemberAttribute { get; set; }
/// <summary>
/// Gets the default value.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue
{
get
{
if (!_hasExplicitDefaultValue)
return null;
return _defaultValue;
}
set
{
_hasExplicitDefaultValue = true;
_defaultValue = value;
}
}
internal object GetResolvedDefaultValue()
{
if (_propertyType == null)
return null;
if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue)
{
_defaultValue = ReflectionUtils.GetDefaultValue(PropertyType);
_hasGeneratedDefaultValue = true;
}
return _defaultValue;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is required.
/// </summary>
/// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value>
public Required Required
{
get { return _required ?? Required.Default; }
set { _required = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this property preserves object references.
/// </summary>
/// <value>
/// <c>true</c> if this instance is reference; otherwise, <c>false</c>.
/// </value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the property null value handling.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling? NullValueHandling { get; set; }
/// <summary>
/// Gets or sets the property default value handling.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling? DefaultValueHandling { get; set; }
/// <summary>
/// Gets or sets the property reference loop handling.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling? ReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets the property object creation handling.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling? ObjectCreationHandling { get; set; }
/// <summary>
/// Gets or sets or sets the type name handling.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling? TypeNameHandling { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialize.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialize.</value>
public Predicate<object> ShouldSerialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object> GetIsSpecified { get; set; }
/// <summary>
/// Gets or sets an action used to set whether the property has been deserialized.
/// </summary>
/// <value>An action used to set whether the property has been deserialized.</value>
public Action<object, object> SetIsSpecified { get; set; }
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return PropertyName;
}
/// <summary>
/// Gets or sets the converter used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items converter.</value>
public JsonConverter ItemConverter { get; set; }
/// <summary>
/// Gets or sets whether this property's collection items are serialized as a reference.
/// </summary>
/// <value>Whether this property's collection items are serialized as a reference.</value>
public bool? ItemIsReference { get; set; }
/// <summary>
/// Gets or sets the the type name handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items type name handling.</value>
public TypeNameHandling? ItemTypeNameHandling { get; set; }
/// <summary>
/// Gets or sets the the reference loop handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items reference loop handling.</value>
public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; }
internal void WritePropertyName(JsonWriter writer)
{
if (_skipPropertyNameEscape)
writer.WritePropertyName(PropertyName, false);
else
writer.WritePropertyName(PropertyName);
}
}
}
| |
//! \file ArcFPK.cs
//! \date Fri Sep 16 04:23:31 2016
//! \brief MoonhirGames resources archive.
//
// Copyright (C) 2016 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using GameRes.Utility;
namespace GameRes.Formats.MoonhirGames
{
internal class FpkEntry : Entry
{
public bool IsEncrypted;
}
internal class FpkArchive : ArcFile
{
public readonly uint Key;
public FpkArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, uint key)
: base (arc, impl, dir)
{
Key = key;
}
}
[Serializable]
public class Fpk0100Scheme : ResourceScheme
{
public uint[] KnownKeys;
}
[Export(typeof(ArchiveFormat))]
public class FpkOpener : ArchiveFormat
{
public override string Tag { get { return "FPK/MOONHIR"; } }
public override string Description { get { return "MoonhirGames engine resource archive"; } }
public override uint Signature { get { return 0x4B5046; } } // 'FPK'
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public static uint[] KnownKeys = { 0 };
public override ResourceScheme Scheme
{
get { return new Fpk0100Scheme { KnownKeys = KnownKeys }; }
set { KnownKeys = ((Fpk0100Scheme)value).KnownKeys; }
}
public override ArcFile TryOpen (ArcView file)
{
if (!file.View.AsciiEqual (4, "0100"))
return null;
int count = file.View.ReadInt32 (0xC);
if (!IsSaneCount (count))
return null;
uint index_offset = file.View.ReadUInt32 (8);
var arc_name = Path.GetFileName (file.Name);
var fbx_type = arc_name.StartsWith ("scr", StringComparison.OrdinalIgnoreCase) ? "" : "image";
var dir = new List<Entry> (count);
bool has_encrypted = false;
for (int i = 0; i < count; ++i)
{
var name = file.View.ReadString (index_offset+12, 12);
var entry = Create<FpkEntry> (name);
entry.IsEncrypted = 0 != file.View.ReadUInt32 (index_offset);
entry.Offset = file.View.ReadUInt32 (index_offset+4);
entry.Size = file.View.ReadUInt32 (index_offset+8);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
if (name.HasExtension (".fbx"))
entry.Type = fbx_type;
has_encrypted = has_encrypted || entry.IsEncrypted;
dir.Add (entry);
index_offset += 0x18;
}
if (!has_encrypted)
return new ArcFile (file, this, dir);
var enc_entry = dir.Cast<FpkEntry>().FirstOrDefault (e => e.IsEncrypted && e.Size > 8);
if (null == enc_entry)
return new ArcFile (file, this, dir);
var key = FindKey (file, enc_entry);
if (null == key)
{
Trace.WriteLine (string.Format ("{0}: unknown encryption key", file.Name), "[FPK]");
return new ArcFile (file, this, dir);
}
return new FpkArchive (file, this, dir, key.Value);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var farc = arc as FpkArchive;
var fent = entry as FpkEntry;
Stream input;
byte[] header;
if (null == farc || null == fent || !fent.IsEncrypted)
{
if (fent != null && fent.IsEncrypted)
throw new UnknownEncryptionScheme();
input = arc.File.CreateStream (entry.Offset, entry.Size);
header = new byte[0x10];
input.Read (header, 0, 0x10);
input.Position = 0;
}
else
{
var data = arc.File.View.ReadBytes (entry.Offset, entry.Size);
Decrypt (data, 0, data.Length, farc.Key);
int length = LittleEndian.ToInt32 (data, data.Length-8);
input = new BinMemoryStream (data, 0, length, entry.Name);
header = data;
}
if (!Binary.AsciiEqual (header, "FBX\x01"))
return input;
using (input)
{
int packed_size = LittleEndian.ToInt32 (header, 8);
int unpacked_size = LittleEndian.ToInt32 (header, 0xC);
input.Position = header[7];
var unpacked = UnpackFbx (input, packed_size, unpacked_size);
return new BinMemoryStream (unpacked, entry.Name);
}
}
uint? FindKey (ArcView file, Entry entry)
{
if (entry.Size < 8)
return null;
var offset = entry.Offset + entry.Size - 8;
uint t1 = file.View.ReadUInt32 (offset+4);
uint t0 = file.View.ReadUInt32 (offset);
// l = (a - x - m + 7) ^ ((x - ((b - x - m + 4) ^ x)) >> 7) ^ ((x * 2 + m - 4) << 7);
foreach (uint key in KnownKeys)
{
uint k1 = key + entry.Size - 4;
uint k2 = ((key - ((t1 - k1) ^ key)) >> 7) ^ ((k1 + key) << 7);
uint test_length = ((((t0 - (k1 - 3)) ^ k2) + 3) & ~3u) + 8;
if (entry.Size == test_length)
return key;
}
return null;
}
unsafe void Decrypt (byte[] data, int index, int length, uint key)
{
if (length < 8)
return;
fixed (byte* data8 = &data[index])
{
uint* data32 = (uint*)data8;
uint* dptr = data32 + length / 4 - 1;
uint k1 = key + (uint)length - 4;
uint k2 = key;
while (dptr >= data32)
{
*dptr = (*dptr - k1) ^ k2;
k2 = ((k2 - *dptr) >> 7) ^ ((k1 + k2) << 7);
k1 -= 3;
--dptr;
}
}
}
byte[] UnpackFbx (Stream input, int packed_size, int unpacked_size)
{
var output = new byte[unpacked_size];
int dst = 0;
int ctl = 1;
while (dst < output.Length)
{
if (1 == ctl)
{
ctl = input.ReadByte();
if (-1 == ctl)
break;
ctl |= 0x100;
}
int count, offset;
switch (ctl & 3)
{
case 0:
output[dst++] = (byte)input.ReadByte();
break;
case 1:
count = input.ReadByte();
if (-1 == count)
return output;
count = Math.Min (count + 2, output.Length - dst);
input.Read (output, dst, count);
dst += count;
break;
case 2:
offset = input.ReadByte() << 8;
offset |= input.ReadByte();
if (-1 == offset)
return output;
count = Math.Min ((offset & 0x1F) + 4, output.Length - dst);
offset >>= 5;
Binary.CopyOverlapped (output, dst - offset - 1, dst, count);
dst += count;
break;
case 3:
int exctl = input.ReadByte();
if (-1 == exctl)
return output;
count = exctl & 0x3F;
switch (exctl >> 6)
{
case 0:
count = count << 8 | input.ReadByte();
if (-1 == count)
return output;
count = Math.Min (count + 0x102, output.Length - dst);
input.Read (output, dst, count);
dst += count;
break;
case 1:
offset = input.ReadByte() << 8;
offset |= input.ReadByte();
count = count << 5 | offset & 0x1F;
count = Math.Min (count + 0x24, output.Length - dst);
offset >>= 5;
Binary.CopyOverlapped (output, dst - offset - 1, dst, count);
dst += count;
break;
case 3:
input.Seek (count, SeekOrigin.Current);
ctl = 1 << 2;
break;
default:
break;
}
break;
}
ctl >>= 2;
}
return output;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace CalcIP
{
public static class CalcIPUtils
{
public static ImmutableDictionary<byte, int> CidrBytes { get; }
public static ImmutableDictionary<byte, int> BytePopCount { get; }
static CalcIPUtils()
{
var cidrBuilder = ImmutableDictionary.CreateBuilder<byte, int>();
cidrBuilder.Add(0x80, 1);
cidrBuilder.Add(0xC0, 2);
cidrBuilder.Add(0xE0, 3);
cidrBuilder.Add(0xF0, 4);
cidrBuilder.Add(0xF8, 5);
cidrBuilder.Add(0xFC, 6);
cidrBuilder.Add(0xFE, 7);
CidrBytes = cidrBuilder.ToImmutable();
var popCountBuilder = ImmutableDictionary.CreateBuilder<byte, int>();
for (int b = 0x00; b < 0x100; ++b)
{
byte popCount = 0;
for (int bit = 0; bit < 8; ++bit)
{
if ((b & (1 << bit)) != 0)
{
++popCount;
}
}
popCountBuilder.Add((byte)b, popCount);
}
BytePopCount = popCountBuilder.ToImmutable();
}
public static byte[] SubnetMaskBytesFromCidrPrefix(int byteCount, int cidrPrefix)
{
if (byteCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(byteCount), byteCount,
nameof(byteCount) + " must be at least 0");
}
if (cidrPrefix < 0 || cidrPrefix > 8*byteCount)
{
throw new ArgumentOutOfRangeException(nameof(cidrPrefix), cidrPrefix,
nameof(cidrPrefix) + " must be at least 0 and at most " + (8*byteCount));
}
byte[] subnetMaskBytes = new byte[byteCount];
for (int i = 0; i < subnetMaskBytes.Length; ++i)
{
switch (cidrPrefix)
{
case 0:
subnetMaskBytes[i] = 0x00;
break;
case 1:
subnetMaskBytes[i] = 0x80;
break;
case 2:
subnetMaskBytes[i] = 0xC0;
break;
case 3:
subnetMaskBytes[i] = 0xE0;
break;
case 4:
subnetMaskBytes[i] = 0xF0;
break;
case 5:
subnetMaskBytes[i] = 0xF8;
break;
case 6:
subnetMaskBytes[i] = 0xFC;
break;
case 7:
subnetMaskBytes[i] = 0xFE;
break;
default:
subnetMaskBytes[i] = 0xFF;
break;
}
if (cidrPrefix < 9)
{
break;
}
else
{
cidrPrefix -= 8;
}
}
return subnetMaskBytes;
}
public static int? CidrPrefixFromSubnetMaskBytes(byte[] subnetMaskBytes)
{
bool nonFullByteSeen = false;
int prefixLength = 0;
foreach (byte b in subnetMaskBytes)
{
if (b == 0xFF)
{
if (nonFullByteSeen)
{
// something like FF 00 FF FF or FF 80 FF FF
return null;
}
// OK
prefixLength += 8;
}
else if (b == 0x00)
{
// disallow FF 00 FF FF but allow FF 00 00 00
nonFullByteSeen = true;
}
else
{
if (nonFullByteSeen)
{
// disalllow FF F0 FF FF
return null;
}
// is this a CIDR-y byte?
int byteLength;
if (!CidrBytes.TryGetValue(b, out byteLength))
{
// nope
// disallow FF FF 0C
return null;
}
// disallow FF F0 FF FF
nonFullByteSeen = true;
// OK otherwise
prefixLength += byteLength;
}
}
return prefixLength;
}
public static string ByteToBinary(byte b)
{
var ret = new char[8];
for (int i = 0; i < ret.Length; ++i)
{
ret[i] = ((b & (1 << (ret.Length-i-1))) != 0)
? '1'
: '0';
}
return new string(ret);
}
public static string UInt16ToBinary(ushort b)
{
var ret = new char[16];
for (int i = 0; i < ret.Length; ++i)
{
ret[i] = ((b & (1 << (ret.Length-i-1))) != 0)
? '1'
: '0';
}
return new string(ret);
}
public static string PadRightTo(string s, int count, char padChar = ' ')
{
if (s.Length >= count)
{
return s;
}
int diff = count - s.Length;
var padding = new string(padChar, diff);
return s + padding;
}
public static T MaxAny<T>(T one, T other)
where T : IComparable<T>
{
return (one.CompareTo(other) >= 0) ? one : other;
}
public static T MinAny<T>(T one, T other)
where T : IComparable<T>
{
return (one.CompareTo(other) <= 0) ? one : other;
}
public static TAddress UnravelAddress<TAddress>(TAddress address, TAddress subnetMask)
where TAddress : struct, IIPAddress<TAddress>
{
if (CalcIPUtils.CidrPrefixFromSubnetMaskBytes(subnetMask.Bytes).HasValue)
{
// nothing to unravel :)
return address;
}
// given an address ABCDEFGH with subnet mask 11001001, turn it into ABEHCDFG (i.e. with subnet mask 11110000)
byte[] addressBytes = address.Bytes;
byte[] maskBytes = subnetMask.Bytes;
var netBits = new List<bool>(addressBytes.Length);
var hostBits = new List<bool>(addressBytes.Length);
// find the bits
for (int i = 0; i < addressBytes.Length; ++i)
{
for (int bit = 7; bit >= 0; --bit)
{
bool addressBit = ((addressBytes[i] & (1 << bit)) != 0);
bool isNet = ((maskBytes[i] & (1 << bit)) != 0);
if (isNet)
{
netBits.Add(addressBit);
}
else
{
hostBits.Add(addressBit);
}
}
}
var unraveledBits = new List<bool>(netBits.Count + hostBits.Count);
unraveledBits.AddRange(netBits);
unraveledBits.AddRange(hostBits);
var retBytes = new byte[addressBytes.Length];
for (int i = 0; i < retBytes.Length; ++i)
{
byte b = 0;
for (int bit = 0; bit < 8; ++bit)
{
if (unraveledBits[8*i+bit])
{
b |= (byte)(1 << (7-bit));
}
}
retBytes[i] = b;
}
return address.MaybeFromBytes(retBytes).Value;
}
public static TAddress WeaveAddress<TAddress>(TAddress address, TAddress subnetMask)
where TAddress : struct, IIPAddress<TAddress>
{
if (CalcIPUtils.CidrPrefixFromSubnetMaskBytes(subnetMask.Bytes).HasValue)
{
// nothing to weave :)
return address;
}
// given an address ABCDEFGH with subnet mask 11001001, convert from subnet mask 11110000 turning it into ABEFCGHD
byte[] addressBytes = address.Bytes;
byte[] maskBytes = subnetMask.Bytes;
int cidrPrefix = subnetMask.Bytes.Sum(b => CalcIPUtils.BytePopCount[b]);
var netBits = new List<bool>(addressBytes.Length);
var hostBits = new List<bool>(addressBytes.Length);
var maskBits = new List<bool>(maskBytes.Length);
// find the bits
for (int i = 0; i < addressBytes.Length; ++i)
{
for (int bit = 0; bit < 8; ++bit)
{
int totalBitIndex = 8*i + bit;
bool addressBit = ((addressBytes[i] & (1 << (7-bit))) != 0);
bool isNet = (totalBitIndex < cidrPrefix);
if (isNet)
{
netBits.Add(addressBit);
}
else
{
hostBits.Add(addressBit);
}
bool maskBit = ((maskBytes[i] & (1 << (7-bit))) != 0);
maskBits.Add(maskBit);
}
}
var retBytes = new byte[addressBytes.Length];
int netIndex = 0;
int hostIndex = 0;
for (int i = 0; i < retBytes.Length; ++i)
{
byte b = 0;
for (int bit = 0; bit < 8; ++bit)
{
bool shouldSetBit;
if (maskBits[8*i+bit])
{
shouldSetBit = netBits[netIndex];
++netIndex;
}
else
{
shouldSetBit = hostBits[hostIndex];
++hostIndex;
}
if (shouldSetBit)
{
b |= (byte)(1 << (7-bit));
}
}
retBytes[i] = b;
}
return address.MaybeFromBytes(retBytes).Value;
}
}
}
| |
// 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 Microsoft.Azure.Management.ServiceBus
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SubscriptionsOperations.
/// </summary>
public static partial class SubscriptionsOperationsExtensions
{
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
public static IPage<SBSubscription> ListByTopic(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName)
{
return operations.ListByTopicAsync(resourceGroupName, namespaceName, topicName).GetAwaiter().GetResult();
}
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SBSubscription>> ListByTopicAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByTopicWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a topic subscription.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639385.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a subscription resource.
/// </param>
public static SBSubscription CreateOrUpdate(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, SBSubscription parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, topicName, subscriptionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a topic subscription.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639385.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a subscription resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SBSubscription> CreateOrUpdateAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, SBSubscription parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a subscription from the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639381.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
public static void Delete(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName)
{
operations.DeleteAsync(resourceGroupName, namespaceName, topicName, subscriptionName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a subscription from the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639381.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, subscriptionName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns a subscription description for the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639402.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
public static SBSubscription Get(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName)
{
return operations.GetAsync(resourceGroupName, namespaceName, topicName, subscriptionName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a subscription description for the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639402.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SBSubscription> GetAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, subscriptionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SBSubscription> ListByTopicNext(this ISubscriptionsOperations operations, string nextPageLink)
{
return operations.ListByTopicNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SBSubscription>> ListByTopicNextAsync(this ISubscriptionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByTopicNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// MetadataWriter.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil.Metadata {
using System;
using System.Collections;
using System.IO;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Binary;
internal sealed class MetadataWriter : BaseMetadataVisitor {
AssemblyDefinition m_assembly;
MetadataRoot m_root;
TargetRuntime m_runtime;
ImageWriter m_imgWriter;
MetadataTableWriter m_tableWriter;
MemoryBinaryWriter m_binaryWriter;
IDictionary m_stringCache;
MemoryBinaryWriter m_stringWriter;
IDictionary m_guidCache;
MemoryBinaryWriter m_guidWriter;
IDictionary m_usCache;
MemoryBinaryWriter m_usWriter;
IDictionary m_blobCache;
MemoryBinaryWriter m_blobWriter;
MemoryBinaryWriter m_tWriter;
MemoryBinaryWriter m_cilWriter;
MemoryBinaryWriter m_fieldDataWriter;
MemoryBinaryWriter m_resWriter;
uint m_mdStart, m_mdSize;
uint m_resStart, m_resSize;
uint m_snsStart, m_snsSize;
uint m_debugHeaderStart;
uint m_imporTableStart;
uint m_entryPointToken;
RVA m_cursor = new RVA (0x2050);
public MemoryBinaryWriter CilWriter {
get { return m_cilWriter; }
}
public uint DebugHeaderPosition {
get { return m_debugHeaderStart; }
}
public uint ImportTablePosition {
get { return m_imporTableStart; }
}
public uint EntryPointToken {
get { return m_entryPointToken; }
set { m_entryPointToken = value; }
}
public MetadataWriter (AssemblyDefinition asm, MetadataRoot root,
AssemblyKind kind, TargetRuntime rt, BinaryWriter writer)
{
m_assembly = asm;
m_root = root;
m_runtime = rt;
m_imgWriter = new ImageWriter (this, kind, writer);
m_binaryWriter = m_imgWriter.GetTextWriter ();
m_stringCache = new Hashtable ();
m_stringWriter = new MemoryBinaryWriter (Encoding.UTF8);
m_stringWriter.Write ((byte) 0);
m_guidCache = new Hashtable ();
m_guidWriter = new MemoryBinaryWriter ();
m_usCache = new Hashtable ();
m_usWriter = new MemoryBinaryWriter (Encoding.Unicode);
m_usWriter.Write ((byte) 0);
m_blobCache = new Hashtable ();
m_blobWriter = new MemoryBinaryWriter ();
m_blobWriter.Write ((byte) 0);
m_tWriter = new MemoryBinaryWriter ();
m_tableWriter = new MetadataTableWriter (this, m_tWriter);
m_cilWriter = new MemoryBinaryWriter ();
m_fieldDataWriter = new MemoryBinaryWriter ();
m_resWriter = new MemoryBinaryWriter ();
}
public MetadataRoot GetMetadataRoot ()
{
return m_root;
}
public ImageWriter GetImageWriter ()
{
return m_imgWriter;
}
public MemoryBinaryWriter GetWriter ()
{
return m_binaryWriter;
}
public MetadataTableWriter GetTableVisitor ()
{
return m_tableWriter;
}
public void AddData (int length)
{
m_cursor += new RVA ((uint) length);
}
public RVA GetDataCursor ()
{
return m_cursor;
}
public uint AddString (string str)
{
if (str == null || str.Length == 0)
return 0;
if (m_stringCache.Contains (str))
return (uint) m_stringCache [str];
uint pointer = (uint) m_stringWriter.BaseStream.Position;
m_stringCache [str] = pointer;
m_stringWriter.Write (Encoding.UTF8.GetBytes (str));
m_stringWriter.Write ('\0');
return pointer;
}
public uint AddBlob (byte [] data)
{
if (data == null || data.Length == 0)
return 0;
// using CompactFramework compatible version of
// Convert.ToBase64String
string key = Convert.ToBase64String (data, 0, data.Length);
if (m_blobCache.Contains (key))
return (uint) m_blobCache [key];
uint pointer = (uint) m_blobWriter.BaseStream.Position;
m_blobCache [key] = pointer;
Utilities.WriteCompressedInteger (m_blobWriter, data.Length);
m_blobWriter.Write (data);
return pointer;
}
public uint AddGuid (Guid g)
{
if (m_guidCache.Contains (g))
return (uint) m_guidCache [g];
uint pointer = (uint) m_guidWriter.BaseStream.Position;
m_guidCache [g] = pointer;
m_guidWriter.Write (g.ToByteArray ());
return pointer + 1;
}
public uint AddUserString (string str)
{
if (str == null)
return 0;
if (m_usCache.Contains (str))
return (uint) m_usCache [str];
uint pointer = (uint) m_usWriter.BaseStream.Position;
m_usCache [str] = pointer;
byte [] us = Encoding.Unicode.GetBytes (str);
Utilities.WriteCompressedInteger (m_usWriter, us.Length + 1);
m_usWriter.Write (us);
m_usWriter.Write ((byte) (RequiresSpecialHandling (us) ? 1 : 0));
return pointer;
}
static bool RequiresSpecialHandling (byte [] chars)
{
for (int i = 0; i < chars.Length; i++) {
byte c = chars [i];
if ((i % 2) == 1)
if (c != 0)
return true;
if (InRange (0x01, 0x08, c) ||
InRange (0x0e, 0x1f, c) ||
c == 0x27 ||
c == 0x2d ||
c == 0x7f) {
return true;
}
}
return false;
}
static bool InRange (int left, int right, int value)
{
return left <= value && value <= right;
}
void CreateStream (string name)
{
MetadataStream stream = new MetadataStream ();
stream.Header.Name = name;
stream.Heap = MetadataHeap.HeapFactory (stream);
m_root.Streams.Add (stream);
}
void SetHeapSize (MetadataHeap heap, MemoryBinaryWriter data, byte flag)
{
if (data.BaseStream.Length > 65536) {
m_root.Streams.TablesHeap.HeapSizes |= flag;
heap.IndexSize = 4;
} else
heap.IndexSize = 2;
}
public uint AddResource (byte [] data)
{
uint offset = (uint) m_resWriter.BaseStream.Position;
m_resWriter.Write (data.Length);
m_resWriter.Write (data);
m_resWriter.QuadAlign ();
return offset;
}
public void AddFieldInitData (byte [] data)
{
m_fieldDataWriter.Write (data);
m_fieldDataWriter.QuadAlign ();
}
uint GetStrongNameSignatureSize ()
{
if (m_assembly.Name.PublicKey != null) {
// in fx 2.0 the key may be from 384 to 16384 bits
// so we must calculate the signature size based on
// the size of the public key (minus the 32 byte header)
int size = m_assembly.Name.PublicKey.Length;
if (size > 32)
return (uint) (size - 32);
// note: size == 16 for the ECMA "key" which is replaced
// by the runtime with a 1024 bits key (128 bytes)
}
return 128; // default strongname signature size
}
public override void VisitMetadataRoot (MetadataRoot root)
{
WriteMemStream (m_cilWriter);
WriteMemStream (m_fieldDataWriter);
m_resStart = (uint) m_binaryWriter.BaseStream.Position;
WriteMemStream (m_resWriter);
m_resSize = (uint) (m_binaryWriter.BaseStream.Position - m_resStart);
// for now, we only reserve the place for the strong name signature
if ((m_assembly.Name.Flags & AssemblyFlags.PublicKey) > 0) {
m_snsStart = (uint) m_binaryWriter.BaseStream.Position;
m_snsSize = GetStrongNameSignatureSize ();
m_binaryWriter.Write (new byte [m_snsSize]);
m_binaryWriter.QuadAlign ();
}
// save place for debug header
if (m_imgWriter.GetImage ().DebugHeader != null) {
m_debugHeaderStart = (uint) m_binaryWriter.BaseStream.Position;
m_binaryWriter.Write (new byte [m_imgWriter.GetImage ().DebugHeader.GetSize ()]);
m_binaryWriter.QuadAlign ();
}
m_mdStart = (uint) m_binaryWriter.BaseStream.Position;
if (m_stringWriter.BaseStream.Length > 1) {
CreateStream (MetadataStream.Strings);
SetHeapSize (root.Streams.StringsHeap, m_stringWriter, 0x01);
m_stringWriter.QuadAlign ();
}
if (m_guidWriter.BaseStream.Length > 0) {
CreateStream (MetadataStream.GUID);
SetHeapSize (root.Streams.GuidHeap, m_guidWriter, 0x02);
}
if (m_blobWriter.BaseStream.Length > 1) {
CreateStream (MetadataStream.Blob);
SetHeapSize (root.Streams.BlobHeap, m_blobWriter, 0x04);
m_blobWriter.QuadAlign ();
}
if (m_usWriter.BaseStream.Length > 2) {
CreateStream (MetadataStream.UserStrings);
m_usWriter.QuadAlign ();
}
m_root.Header.MajorVersion = 1;
m_root.Header.MinorVersion = 1;
switch (m_runtime) {
case TargetRuntime.NET_1_0 :
m_root.Header.Version = "v1.0.3705";
break;
case TargetRuntime.NET_1_1 :
m_root.Header.Version = "v1.1.4322";
break;
case TargetRuntime.NET_2_0 :
m_root.Header.Version = "v2.0.50727";
break;
}
m_root.Streams.TablesHeap.Tables.Accept (m_tableWriter);
if (m_tWriter.BaseStream.Length == 0)
m_root.Streams.Remove (m_root.Streams.TablesHeap.GetStream ());
}
public override void VisitMetadataRootHeader (MetadataRoot.MetadataRootHeader header)
{
m_binaryWriter.Write (header.Signature);
m_binaryWriter.Write (header.MajorVersion);
m_binaryWriter.Write (header.MinorVersion);
m_binaryWriter.Write (header.Reserved);
m_binaryWriter.Write (header.Version.Length + 3 & (~3));
m_binaryWriter.Write (Encoding.ASCII.GetBytes (header.Version));
m_binaryWriter.QuadAlign ();
m_binaryWriter.Write (header.Flags);
m_binaryWriter.Write ((ushort) m_root.Streams.Count);
}
public override void VisitMetadataStreamCollection (MetadataStreamCollection streams)
{
foreach (MetadataStream stream in streams) {
MetadataStream.MetadataStreamHeader header = stream.Header;
header.Offset = (uint) (m_binaryWriter.BaseStream.Position);
m_binaryWriter.Write (header.Offset);
MemoryBinaryWriter container;
string name = header.Name;
uint size = 0;
switch (header.Name) {
case MetadataStream.Tables :
container = m_tWriter;
size += 24; // header
break;
case MetadataStream.Strings :
name += "\0\0\0\0";
container = m_stringWriter;
break;
case MetadataStream.GUID :
container = m_guidWriter;
break;
case MetadataStream.Blob :
container = m_blobWriter;
break;
case MetadataStream.UserStrings :
container = m_usWriter;
break;
default :
throw new MetadataFormatException ("Unknown stream kind");
}
size += (uint) (container.BaseStream.Length + 3 & (~3));
m_binaryWriter.Write (size);
m_binaryWriter.Write (Encoding.ASCII.GetBytes (name));
m_binaryWriter.QuadAlign ();
}
}
void WriteMemStream (MemoryBinaryWriter writer)
{
m_binaryWriter.Write (writer);
m_binaryWriter.QuadAlign ();
}
void PatchStreamHeaderOffset (MetadataHeap heap)
{
long pos = m_binaryWriter.BaseStream.Position;
m_binaryWriter.BaseStream.Position = heap.GetStream ().Header.Offset;
m_binaryWriter.Write ((uint) (pos - m_mdStart));
m_binaryWriter.BaseStream.Position = pos;
}
public override void VisitGuidHeap (GuidHeap heap)
{
PatchStreamHeaderOffset (heap);
WriteMemStream (m_guidWriter);
}
public override void VisitStringsHeap (StringsHeap heap)
{
PatchStreamHeaderOffset (heap);
WriteMemStream (m_stringWriter);
}
public override void VisitTablesHeap (TablesHeap heap)
{
PatchStreamHeaderOffset (heap);
m_binaryWriter.Write (heap.Reserved);
switch (m_runtime) {
case TargetRuntime.NET_1_0 :
case TargetRuntime.NET_1_1 :
heap.MajorVersion = 1;
heap.MinorVersion = 0;
break;
case TargetRuntime.NET_2_0 :
heap.MajorVersion = 2;
heap.MinorVersion = 0;
break;
}
m_binaryWriter.Write (heap.MajorVersion);
m_binaryWriter.Write (heap.MinorVersion);
m_binaryWriter.Write (heap.HeapSizes);
m_binaryWriter.Write (heap.Reserved2);
m_binaryWriter.Write (heap.Valid);
m_binaryWriter.Write (heap.Sorted);
WriteMemStream (m_tWriter);
}
public override void VisitBlobHeap (BlobHeap heap)
{
PatchStreamHeaderOffset (heap);
WriteMemStream (m_blobWriter);
}
public override void VisitUserStringsHeap (UserStringsHeap heap)
{
PatchStreamHeaderOffset (heap);
WriteMemStream (m_usWriter);
}
void PatchHeader ()
{
Image img = m_imgWriter.GetImage ();
img.CLIHeader.EntryPointToken = m_entryPointToken;
if (m_mdSize > 0)
img.CLIHeader.Metadata = new DataDirectory (
img.TextSection.VirtualAddress + m_mdStart, m_imporTableStart - m_mdStart);
if (m_resSize > 0)
img.CLIHeader.Resources = new DataDirectory (
img.TextSection.VirtualAddress + m_resStart, m_resSize);
if (m_snsStart > 0)
img.CLIHeader.StrongNameSignature = new DataDirectory (
img.TextSection.VirtualAddress + m_snsStart, m_snsSize);
if (m_debugHeaderStart > 0)
img.PEOptionalHeader.DataDirectories.Debug = new DataDirectory (
img.TextSection.VirtualAddress + m_debugHeaderStart, 0x1c);
}
public override void TerminateMetadataRoot (MetadataRoot root)
{
m_mdSize = (uint) (m_binaryWriter.BaseStream.Position - m_mdStart);
m_imporTableStart = (uint) m_binaryWriter.BaseStream.Position;
m_binaryWriter.Write (new byte [0x60]); // imports
m_imgWriter.Initialize ();
PatchHeader ();
root.GetImage ().Accept (m_imgWriter);
}
}
}
| |
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="Security.IPIntelligencePolicyBinding", Namespace="urn:iControl")]
public partial class SecurityIPIntelligencePolicy : iControlInterface {
public SecurityIPIntelligencePolicy() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_blacklist_category
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void add_blacklist_category(
string [] policies,
string [] [] categories
) {
this.Invoke("add_blacklist_category", new object [] {
policies,
categories});
}
public System.IAsyncResult Beginadd_blacklist_category(string [] policies,string [] [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_blacklist_category", new object[] {
policies,
categories}, callback, asyncState);
}
public void Endadd_blacklist_category(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_feed_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void add_feed_list(
string [] policies,
string [] [] lists
) {
this.Invoke("add_feed_list", new object [] {
policies,
lists});
}
public System.IAsyncResult Beginadd_feed_list(string [] policies,string [] [] lists, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_feed_list", new object[] {
policies,
lists}, callback, asyncState);
}
public void Endadd_feed_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void create(
string [] policies
) {
this.Invoke("create", new object [] {
policies});
}
public System.IAsyncResult Begincreate(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
policies}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_policies
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void delete_all_policies(
) {
this.Invoke("delete_all_policies", new object [0]);
}
public System.IAsyncResult Begindelete_all_policies(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_policies", new object[0], callback, asyncState);
}
public void Enddelete_all_policies(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_policy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void delete_policy(
string [] policies
) {
this.Invoke("delete_policy", new object [] {
policies});
}
public System.IAsyncResult Begindelete_policy(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_policy", new object[] {
policies}, callback, asyncState);
}
public void Enddelete_policy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_blacklist_category
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_blacklist_category(
string [] policies
) {
object [] results = this.Invoke("get_blacklist_category", new object [] {
policies});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_blacklist_category(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_blacklist_category", new object[] {
policies}, callback, asyncState);
}
public string [] [] Endget_blacklist_category(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_blacklist_category_action_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] [] get_blacklist_category_action_type(
string [] policies,
string [] [] categories
) {
object [] results = this.Invoke("get_blacklist_category_action_type", new object [] {
policies,
categories});
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] [])(results[0]));
}
public System.IAsyncResult Beginget_blacklist_category_action_type(string [] policies,string [] [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_blacklist_category_action_type", new object[] {
policies,
categories}, callback, asyncState);
}
public SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] [] Endget_blacklist_category_action_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_blacklist_category_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_blacklist_category_description(
string [] policies,
string [] [] categories
) {
object [] results = this.Invoke("get_blacklist_category_description", new object [] {
policies,
categories});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_blacklist_category_description(string [] policies,string [] [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_blacklist_category_description", new object[] {
policies,
categories}, callback, asyncState);
}
public string [] [] Endget_blacklist_category_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_blacklist_category_log_blacklist_hit_only_setting
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] get_blacklist_category_log_blacklist_hit_only_setting(
string [] policies,
string [] [] categories
) {
object [] results = this.Invoke("get_blacklist_category_log_blacklist_hit_only_setting", new object [] {
policies,
categories});
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [])(results[0]));
}
public System.IAsyncResult Beginget_blacklist_category_log_blacklist_hit_only_setting(string [] policies,string [] [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_blacklist_category_log_blacklist_hit_only_setting", new object[] {
policies,
categories}, callback, asyncState);
}
public SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] Endget_blacklist_category_log_blacklist_hit_only_setting(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_blacklist_category_log_blacklist_whitelist_hit_setting
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] get_blacklist_category_log_blacklist_whitelist_hit_setting(
string [] policies,
string [] [] categories
) {
object [] results = this.Invoke("get_blacklist_category_log_blacklist_whitelist_hit_setting", new object [] {
policies,
categories});
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [])(results[0]));
}
public System.IAsyncResult Beginget_blacklist_category_log_blacklist_whitelist_hit_setting(string [] policies,string [] [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_blacklist_category_log_blacklist_whitelist_hit_setting", new object[] {
policies,
categories}, callback, asyncState);
}
public SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] Endget_blacklist_category_log_blacklist_whitelist_hit_setting(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_blacklist_category_match_direction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SecurityIPIntelligencePolicyIPIntelligencePolicyMatchDirection [] [] get_blacklist_category_match_direction(
string [] policies,
string [] [] categories
) {
object [] results = this.Invoke("get_blacklist_category_match_direction", new object [] {
policies,
categories});
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyMatchDirection [] [])(results[0]));
}
public System.IAsyncResult Beginget_blacklist_category_match_direction(string [] policies,string [] [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_blacklist_category_match_direction", new object[] {
policies,
categories}, callback, asyncState);
}
public SecurityIPIntelligencePolicyIPIntelligencePolicyMatchDirection [] [] Endget_blacklist_category_match_direction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyMatchDirection [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_default_action_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] get_default_action_type(
string [] policies
) {
object [] results = this.Invoke("get_default_action_type", new object [] {
policies});
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [])(results[0]));
}
public System.IAsyncResult Beginget_default_action_type(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_action_type", new object[] {
policies}, callback, asyncState);
}
public SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] Endget_default_action_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] policies
) {
object [] results = this.Invoke("get_description", new object [] {
policies});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
policies}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_feed_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_feed_list(
string [] policies
) {
object [] results = this.Invoke("get_feed_list", new object [] {
policies});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_feed_list(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_feed_list", new object[] {
policies}, callback, asyncState);
}
public string [] [] Endget_feed_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[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_log_blacklist_hit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_log_blacklist_hit_state(
string [] policies
) {
object [] results = this.Invoke("get_log_blacklist_hit_state", new object [] {
policies});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_log_blacklist_hit_state(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_log_blacklist_hit_state", new object[] {
policies}, callback, asyncState);
}
public CommonEnabledState [] Endget_log_blacklist_hit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_log_blacklist_whitelist_both_hit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_log_blacklist_whitelist_both_hit_state(
string [] policies
) {
object [] results = this.Invoke("get_log_blacklist_whitelist_both_hit_state", new object [] {
policies});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_log_blacklist_whitelist_both_hit_state(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_log_blacklist_whitelist_both_hit_state", new object[] {
policies}, callback, asyncState);
}
public CommonEnabledState [] Endget_log_blacklist_whitelist_both_hit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
[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_blacklist_categories
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void remove_all_blacklist_categories(
string [] policies
) {
this.Invoke("remove_all_blacklist_categories", new object [] {
policies});
}
public System.IAsyncResult Beginremove_all_blacklist_categories(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_blacklist_categories", new object[] {
policies}, callback, asyncState);
}
public void Endremove_all_blacklist_categories(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_feed_lists
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void remove_all_feed_lists(
string [] policies
) {
this.Invoke("remove_all_feed_lists", new object [] {
policies});
}
public System.IAsyncResult Beginremove_all_feed_lists(string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_feed_lists", new object[] {
policies}, callback, asyncState);
}
public void Endremove_all_feed_lists(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_blacklist_category
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void remove_blacklist_category(
string [] policies,
string [] [] categories
) {
this.Invoke("remove_blacklist_category", new object [] {
policies,
categories});
}
public System.IAsyncResult Beginremove_blacklist_category(string [] policies,string [] [] categories, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_blacklist_category", new object[] {
policies,
categories}, callback, asyncState);
}
public void Endremove_blacklist_category(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_feed_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void remove_feed_list(
string [] policies,
string [] [] lists
) {
this.Invoke("remove_feed_list", new object [] {
policies,
lists});
}
public System.IAsyncResult Beginremove_feed_list(string [] policies,string [] [] lists, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_feed_list", new object[] {
policies,
lists}, callback, asyncState);
}
public void Endremove_feed_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_blacklist_category_action_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_blacklist_category_action_type(
string [] policies,
string [] [] categories,
SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] [] types
) {
this.Invoke("set_blacklist_category_action_type", new object [] {
policies,
categories,
types});
}
public System.IAsyncResult Beginset_blacklist_category_action_type(string [] policies,string [] [] categories,SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] [] types, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_blacklist_category_action_type", new object[] {
policies,
categories,
types}, callback, asyncState);
}
public void Endset_blacklist_category_action_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_blacklist_category_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_blacklist_category_description(
string [] policies,
string [] [] categories,
string [] [] descriptions
) {
this.Invoke("set_blacklist_category_description", new object [] {
policies,
categories,
descriptions});
}
public System.IAsyncResult Beginset_blacklist_category_description(string [] policies,string [] [] categories,string [] [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_blacklist_category_description", new object[] {
policies,
categories,
descriptions}, callback, asyncState);
}
public void Endset_blacklist_category_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_blacklist_category_log_blacklist_hit_only_setting
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_blacklist_category_log_blacklist_hit_only_setting(
string [] policies,
string [] [] categories,
SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] hits
) {
this.Invoke("set_blacklist_category_log_blacklist_hit_only_setting", new object [] {
policies,
categories,
hits});
}
public System.IAsyncResult Beginset_blacklist_category_log_blacklist_hit_only_setting(string [] policies,string [] [] categories,SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] hits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_blacklist_category_log_blacklist_hit_only_setting", new object[] {
policies,
categories,
hits}, callback, asyncState);
}
public void Endset_blacklist_category_log_blacklist_hit_only_setting(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_blacklist_category_log_blacklist_whitelist_hit_setting
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_blacklist_category_log_blacklist_whitelist_hit_setting(
string [] policies,
string [] [] categories,
SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] hits
) {
this.Invoke("set_blacklist_category_log_blacklist_whitelist_hit_setting", new object [] {
policies,
categories,
hits});
}
public System.IAsyncResult Beginset_blacklist_category_log_blacklist_whitelist_hit_setting(string [] policies,string [] [] categories,SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType [] [] hits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_blacklist_category_log_blacklist_whitelist_hit_setting", new object[] {
policies,
categories,
hits}, callback, asyncState);
}
public void Endset_blacklist_category_log_blacklist_whitelist_hit_setting(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_blacklist_category_match_direction
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_blacklist_category_match_direction(
string [] policies,
string [] [] categories,
SecurityIPIntelligencePolicyIPIntelligencePolicyMatchDirection [] [] directions
) {
this.Invoke("set_blacklist_category_match_direction", new object [] {
policies,
categories,
directions});
}
public System.IAsyncResult Beginset_blacklist_category_match_direction(string [] policies,string [] [] categories,SecurityIPIntelligencePolicyIPIntelligencePolicyMatchDirection [] [] directions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_blacklist_category_match_direction", new object[] {
policies,
categories,
directions}, callback, asyncState);
}
public void Endset_blacklist_category_match_direction(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_action_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_default_action_type(
string [] policies,
SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] types
) {
this.Invoke("set_default_action_type", new object [] {
policies,
types});
}
public System.IAsyncResult Beginset_default_action_type(string [] policies,SecurityIPIntelligencePolicyIPIntelligencePolicyActionType [] types, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_action_type", new object[] {
policies,
types}, callback, asyncState);
}
public void Endset_default_action_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_description(
string [] policies,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
policies,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] policies,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
policies,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_log_blacklist_hit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_log_blacklist_hit_state(
string [] policies,
CommonEnabledState [] states
) {
this.Invoke("set_log_blacklist_hit_state", new object [] {
policies,
states});
}
public System.IAsyncResult Beginset_log_blacklist_hit_state(string [] policies,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_log_blacklist_hit_state", new object[] {
policies,
states}, callback, asyncState);
}
public void Endset_log_blacklist_hit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_log_blacklist_whitelist_both_hit_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/IPIntelligencePolicy",
RequestNamespace="urn:iControl:Security/IPIntelligencePolicy", ResponseNamespace="urn:iControl:Security/IPIntelligencePolicy")]
public void set_log_blacklist_whitelist_both_hit_state(
string [] policies,
CommonEnabledState [] states
) {
this.Invoke("set_log_blacklist_whitelist_both_hit_state", new object [] {
policies,
states});
}
public System.IAsyncResult Beginset_log_blacklist_whitelist_both_hit_state(string [] policies,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_log_blacklist_whitelist_both_hit_state", new object[] {
policies,
states}, callback, asyncState);
}
public void Endset_log_blacklist_whitelist_both_hit_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.IPIntelligencePolicy.IPIntelligencePolicyActionType", Namespace = "urn:iControl")]
public enum SecurityIPIntelligencePolicyIPIntelligencePolicyActionType
{
IP_INTELLIGENCE_POLICY_ACTION_TYPE_UNKNOWN,
IP_INTELLIGENCE_POLICY_ACTION_TYPE_USE_PARENT,
IP_INTELLIGENCE_POLICY_ACTION_TYPE_ALLOW,
IP_INTELLIGENCE_POLICY_ACTION_TYPE_DROP,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.IPIntelligencePolicy.IPIntelligencePolicyBlacklistCategoryLogType", Namespace = "urn:iControl")]
public enum SecurityIPIntelligencePolicyIPIntelligencePolicyBlacklistCategoryLogType
{
IP_INTELLIGENCE_POLICY_BLACKLIST_CATEGORY_LOG_TYPE_UNKNOWN,
IP_INTELLIGENCE_POLICY_BLACKLIST_CATEGORY_LOG_TYPE_USE_PARENT,
IP_INTELLIGENCE_POLICY_BLACKLIST_CATEGORY_LOG_TYPE_YES,
IP_INTELLIGENCE_POLICY_BLACKLIST_CATEGORY_LOG_TYPE_NO,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.IPIntelligencePolicy.IPIntelligencePolicyMatchDirection", Namespace = "urn:iControl")]
public enum SecurityIPIntelligencePolicyIPIntelligencePolicyMatchDirection
{
IP_INTELLIGENCE_POLICY_MATCH_DIRECTION_UNKNOWN,
IP_INTELLIGENCE_POLICY_MATCH_DIRECTION_SOURCE,
IP_INTELLIGENCE_POLICY_MATCH_DIRECTION_DESTINATION,
IP_INTELLIGENCE_POLICY_MATCH_DIRECTION_SOURCE_AND_DESTINATION,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
namespace System
{
// CONTRACT with Runtime
// The UIntPtr type is one of the primitives understood by the compilers and runtime
// Data Contract: Single field of type void *
[Serializable]
[CLSCompliant(false)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
{
unsafe private void* _value;
[Intrinsic]
public static readonly UIntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(uint value)
{
_value = (void*)value;
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((uint)value);
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe UIntPtr(void* value)
{
_value = value;
}
private unsafe UIntPtr(SerializationInfo info, StreamingContext context)
{
ulong l = info.GetUInt64("value");
if (Size == 4 && l > uint.MaxValue)
throw new ArgumentException(SR.Serialization_InvalidPtrValue);
_value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
info.AddValue("value", (ulong)_value);
}
[Intrinsic]
[NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
[Intrinsic]
[NonVersionable]
public unsafe uint ToUInt32()
{
#if BIT64
return checked((uint)_value);
#else
return (uint)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe ulong ToUInt64()
{
return (ulong)_value;
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(uint value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static explicit operator UIntPtr(ulong value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator UIntPtr(void* value)
{
return new UIntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator void* (UIntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator uint(UIntPtr value)
{
#if BIT64
return checked((uint)value._value);
#else
return (uint)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator ulong(UIntPtr value)
{
return (ulong)value._value;
}
unsafe bool IEquatable<UIntPtr>.Equals(UIntPtr value)
{
return _value == value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator ==(UIntPtr value1, UIntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator !=(UIntPtr value1, UIntPtr value2)
{
return value1._value != value2._value;
}
public static unsafe int Size
{
[Intrinsic]
[NonVersionable]
get
{
#if BIT64
return 8;
#else
return 4;
#endif
}
}
public unsafe override String ToString()
{
#if BIT64
return ((ulong)_value).ToString(FormatProvider.InvariantCulture);
#else
return ((uint)_value).ToString(FormatProvider.InvariantCulture);
#endif
}
public unsafe override bool Equals(Object obj)
{
if (obj is UIntPtr)
{
return (_value == ((UIntPtr)obj)._value);
}
return false;
}
public unsafe override int GetHashCode()
{
#if BIT64
ulong l = (ulong)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
[NonVersionable]
public static UIntPtr Add(UIntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator +(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[NonVersionable]
public static UIntPtr Subtract(UIntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public static UIntPtr operator -(UIntPtr pointer, int offset)
{
#if BIT64
return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Gallio.Common.Collections;
using Gallio.Framework.Assertions;
using Gallio.Common.Reflection;
using Gallio.Common.Reflection.Impl;
using MbUnit.Framework;
using System.Runtime.CompilerServices;
using Action=Gallio.Common.Action;
namespace Gallio.Tests.Common.Reflection
{
/// <summary>
/// Assertions for testing the reflection wrappers.
/// </summary>
public class WrapperAssert
{
private const BindingFlags All = BindingFlags.NonPublic | AllPublic;
private const BindingFlags AllPublic = BindingFlags.Public
| BindingFlags.Instance | BindingFlags.Static
| BindingFlags.FlattenHierarchy;
private TypeAttributes TypeAttributesMask
{
get
{
return TypeAttributes.ClassSemanticsMask | TypeAttributes.VisibilityMask
| TypeAttributes.Abstract | TypeAttributes.Sealed
| (supportsSpecialName ? TypeAttributes.SpecialName : 0);
}
}
private const GenericParameterAttributes GenericParameterAttributesMask =
GenericParameterAttributes.SpecialConstraintMask | GenericParameterAttributes.VarianceMask;
private MethodAttributes MethodAttributesMask
{
get
{
return MethodAttributes.MemberAccessMask | MethodAttributes.VtableLayoutMask
| MethodAttributes.Abstract | MethodAttributes.Final
| MethodAttributes.PrivateScope
| MethodAttributes.Static | MethodAttributes.Virtual
| (supportsSpecialName ? MethodAttributes.SpecialName : 0);
}
}
private const ParameterAttributes ParameterAttributesMask =
ParameterAttributes.HasDefault | ParameterAttributes.Optional
| ParameterAttributes.In | ParameterAttributes.Out | ParameterAttributes.Retval;
private FieldAttributes FieldAttributesMask
{
get
{
return FieldAttributes.FieldAccessMask | FieldAttributes.HasDefault | FieldAttributes.InitOnly
| FieldAttributes.Literal | FieldAttributes.Static
| (supportsSpecialName ? FieldAttributes.SpecialName : 0);
}
}
private PropertyAttributes PropertyAttributesMask
{
get
{
return PropertyAttributes.HasDefault
| (supportsSpecialName ? PropertyAttributes.SpecialName : 0);
}
}
private EventAttributes EventAttributesMask
{
get
{
return supportsSpecialName ? EventAttributes.SpecialName : 0;
}
}
private readonly MultiMap<object, object> equivalenceCache;
private bool supportsSpecialFeatures = true;
private bool supportsSpecialName = true;
private bool supportsCallingConventions = true;
private bool supportsReturnAttributes = true;
private bool supportsGenericParameterAttributes = true;
private bool supportsEventFields = true;
private bool supportsFinalizers = true;
private bool supportsStaticConstructors = true;
private bool supportsFullAssemblyName = true;
private bool supportsNestedGenericTypes = true;
public WrapperAssert()
{
equivalenceCache = new MultiMap<object, object>();
}
/// <summary>
/// Specifies whether the reflection API supports all of the weird quirky runtime
/// tricks the CLR plays with reflection like creating new methods out of
/// thin air.
/// </summary>
public bool SupportsSpecialFeatures
{
set { supportsSpecialFeatures = value; }
}
/// <summary>
/// Specifies whether the reflection API supports the SpecialName property for members.
/// </summary>
public bool SupportsSpecialName
{
set { supportsSpecialName = value; }
}
/// <summary>
/// Specifies whether the reflection API supports the CallingConventions property for methods.
/// </summary>
public bool SupportsCallingConventions
{
set { supportsCallingConventions = value; }
}
/// <summary>
/// Specifies whether the reflection API supports attributes on method return values.
/// </summary>
public bool SupportsReturnAttributes
{
set { supportsReturnAttributes = value; }
}
/// <summary>
/// Specifies whether the reflection API supports attributes on generic parameters.
/// </summary>
public bool SupportsGenericParameterAttributes
{
set { supportsGenericParameterAttributes = value; }
}
/// <summary>
/// Specifies whether the reflection API supports representing events as fields.
/// </summary>
public bool SupportsEventFields
{
set { supportsEventFields = value; }
}
/// <summary>
/// Specifies whether the reflection API supports finalizer methods.
/// </summary>
public bool SupportsFinalizers
{
set { supportsFinalizers = value; }
}
/// <summary>
/// Specifies whether the reflection API supports static constructors.
/// </summary>
public bool SupportsStaticConstructors
{
set { supportsStaticConstructors = value; }
}
/// <summary>
/// Specifies whether the reflection API supports full assembly name information.
/// </summary>
public bool SupportsFullAssemblyName
{
set { supportsFullAssemblyName = value; }
}
/// <summary>
/// Specifies whether the reflection API supports nested generic types.
/// This is to workaround R# 3.1 specific issues involving a generic type
/// that contains another generic type nested within.
/// </summary>
public bool SupportsNestedGenericTypes
{
set { supportsNestedGenericTypes = value; }
}
public void AreEquivalent(string namespaceName, INamespaceInfo info)
{
if (namespaceName == null)
{
Assert.IsNull(info);
return;
}
MemoizeEquivalence(namespaceName, info, delegate
{
Assert.AreEqual(CodeElementKind.Namespace, info.Kind);
Assert.AreEqual(CodeReference.CreateFromNamespace(namespaceName), info.CodeReference);
Assert.AreEqual(namespaceName, info.Name);
Assert.IsFalse(info.GetAttributeInfos(null, false).GetEnumerator().MoveNext());
Assert.IsFalse(info.GetAttributes(null, false).GetEnumerator().MoveNext());
Assert.IsFalse(info.HasAttribute(null, false));
Assert.AreEqual(CodeLocation.Unknown, info.GetCodeLocation());
Assert.IsNull(info.GetXmlDocumentation());
});
}
public void AreEquivalent(Assembly target, IAssemblyInfo info, bool recursive)
{
MemoizeEquivalence(target, info, delegate
{
Assert.AreEqual(CodeElementKind.Assembly, info.Kind);
string targetDisplayName = target.GetName().Name;
Assert.AreEqual(targetDisplayName, info.Name);
if (info.Name != info.FullName)
{
Assert.AreEqual(target.FullName,
info.ToString());
Assert.AreEqual(target.FullName,
info.FullName);
Assert.AreEqual(target.GetName().FullName,
info.GetName().FullName);
}
else
{
// We might not always be able to get the full name in the reflection wrapper.
// A partial name will suffice.
Assert.AreEqual(targetDisplayName, info.ToString());
Assert.AreEqual(targetDisplayName, info.FullName);
Assert.AreEqual(targetDisplayName, info.GetName().Name);
}
AreEqualUpToAssemblyDisplayName(CodeReference.CreateFromAssembly(target), info.CodeReference);
Assert.AreEqual(Path.GetFileName(AssemblyUtils.GetAssemblyLocalPath(target)), Path.GetFileName(info.Path), StringComparison.InvariantCultureIgnoreCase);
CodeLocation infoLocation = info.GetCodeLocation();
Assert.AreEqual(Path.GetFileName(AssemblyUtils.GetAssemblyLocalPath(target)), Path.GetFileName(infoLocation.Path), StringComparison.InvariantCultureIgnoreCase);
Assert.AreEqual(0, infoLocation.Line);
Assert.AreEqual(0, infoLocation.Column);
Assert.IsNull(info.GetXmlDocumentation());
Assert.AreElementsEqualIgnoringOrder(
target.GetReferencedAssemblies(),
info.GetReferencedAssemblies(),
delegate(AssemblyName expected, AssemblyName actual) {
return expected.FullName == actual.FullName;
});
IList<ITypeInfo> privateTypes = info.GetTypes();
IList<ITypeInfo> publicTypes = info.GetExportedTypes();
foreach (Type type in target.GetTypes())
{
if (type.IsPublic)
{
if (! IsUnsupportedType(type))
{
ITypeInfo foundType = info.GetType(type.FullName);
AreEqualWhenResolved(type, foundType);
Assert.IsTrue(publicTypes.Contains(foundType), "Should appear in public types: {0}", type);
}
}
}
foreach (ITypeInfo type in privateTypes)
{
if (type.IsPublic || type.IsNestedPublic)
Assert.IsTrue(publicTypes.Contains(type), "Should appear in public types: {0}", type);
else
Assert.IsFalse(publicTypes.Contains(type), "Should not appear in public types: {0}", type);
AreEqualWhenResolved(Type.GetType(type.AssemblyQualifiedName), type);
}
foreach (ITypeInfo type in publicTypes)
{
Assert.IsTrue(type.IsPublic || type.IsNestedPublic);
Assert.IsTrue(privateTypes.Contains(type), "Should appear in private types: {0}", type);
}
Assert.AreEqual(target, info.Resolve(true));
AreAttributeProvidersEquivalent(target, info);
});
if (recursive)
{
foreach (Type type in target.GetExportedTypes())
{
if (!IsUnsupportedType(type))
{
AreEquivalent(type, info.GetType(type.FullName), true);
}
}
}
}
public void AreEquivalent(Attribute target, IAttributeInfo info, bool recursive)
{
AreEqualWhenResolved(target.GetType(), info.Type);
Assert.AreEqual(target.GetType(), info.Resolve(false).GetType());
foreach (FieldInfo field in target.GetType().GetFields())
Assert.AreEqual(field.GetValue(target), info.GetFieldValue(field.Name).Resolve(false));
foreach (PropertyInfo property in target.GetType().GetProperties())
if (property.CanRead && property.CanWrite)
Assert.AreEqual(property.GetValue(target, null), info.GetPropertyValue(property.Name).Resolve(false));
if (recursive)
{
AreEquivalent(target.GetType(), info.Type, true);
}
}
public void AreEquivalent(ConstructorInfo target, IConstructorInfo info, bool recursive)
{
Assert.AreEqual(CodeElementKind.Constructor, info.Kind);
AreFunctionsEquivalent(target, info, recursive);
AreEqual(target, info.Resolve(true));
}
public void AreEquivalent(MethodInfo target, IMethodInfo info, bool recursive)
{
Assert.AreEqual(CodeElementKind.Method, info.Kind);
AreFunctionsEquivalent(target, info, recursive);
AreEqual(target, info.Resolve(true));
Assert.AreEqual(target.ContainsGenericParameters, info.ContainsGenericParameters);
Assert.AreEqual(target.IsGenericMethod, info.IsGenericMethod);
Assert.AreEqual(target.IsGenericMethodDefinition, info.IsGenericMethodDefinition);
AreElementsEqualWhenResolved(target.GetGenericArguments(), info.GenericArguments);
AreEqualWhenResolved(target.IsGenericMethod ? target.GetGenericMethodDefinition() : null, info.GenericMethodDefinition);
AreEqualWhenResolved(target.ReturnType, info.ReturnType);
AreEqualWhenResolved(target.ReturnParameter, info.ReturnParameter);
if (recursive)
{
AreEquivalent(target.GetGenericArguments(), info.GenericArguments, false);
AreEquivalent(target.ReturnType, info.ReturnType, false);
}
}
public void AreEquivalent(EventInfo target, IEventInfo info, bool recursive)
{
Assert.AreEqual(CodeElementKind.Event, info.Kind);
AreMembersEquivalent(target, info, recursive);
AreEqual(target, info.Resolve(true));
Assert.AreEqual(target.Attributes & EventAttributesMask, info.EventAttributes & EventAttributesMask);
AreEqualWhenResolved(target.GetAddMethod(true), info.AddMethod);
AreEqualWhenResolved(target.GetRemoveMethod(true), info.RemoveMethod);
AreEqualWhenResolved(target.GetRaiseMethod(true), info.RaiseMethod);
AreEqualWhenResolved(target.EventHandlerType, info.EventHandlerType);
if (recursive)
{
AreEquivalent(target.EventHandlerType, info.EventHandlerType, false);
}
}
public void AreEquivalent(FieldInfo target, IFieldInfo info, bool recursive)
{
Assert.AreEqual(CodeElementKind.Field, info.Kind);
AreMembersEquivalent(target, info, recursive);
AreEqual(target, info.Resolve(true));
AreEqualWhenResolved(target.FieldType, info.ValueType);
Assert.AreEqual(0, info.Position);
Assert.AreEqual(target.Attributes & FieldAttributesMask, info.FieldAttributes & FieldAttributesMask);
Assert.AreEqual(target.IsLiteral, info.IsLiteral);
Assert.AreEqual(target.IsInitOnly, info.IsInitOnly);
Assert.AreEqual(target.IsStatic, info.IsStatic);
Assert.AreEqual(target.IsAssembly, info.IsAssembly);
Assert.AreEqual(target.IsFamily, info.IsFamily);
Assert.AreEqual(target.IsFamilyAndAssembly, info.IsFamilyAndAssembly);
Assert.AreEqual(target.IsFamilyOrAssembly, info.IsFamilyOrAssembly);
Assert.AreEqual(target.IsPrivate, info.IsPrivate);
Assert.AreEqual(target.IsPublic, info.IsPublic);
if (recursive)
{
AreEquivalent(target.FieldType, info.ValueType, false);
}
}
public void AreEquivalent(PropertyInfo target, IPropertyInfo info, bool recursive)
{
Assert.AreEqual(CodeElementKind.Property, info.Kind);
AreMembersEquivalent(target, info, recursive);
AreEqual(target, info.Resolve(true));
AreEqualWhenResolved(target.PropertyType, info.ValueType);
Assert.AreEqual(0, info.Position);
Assert.AreEqual(target.Attributes & PropertyAttributesMask, info.PropertyAttributes & PropertyAttributesMask);
Assert.AreEqual(target.CanRead, info.CanRead);
Assert.AreEqual(target.CanWrite, info.CanWrite);
AreEqualWhenResolved(target.GetGetMethod(true), info.GetMethod);
AreEqualWhenResolved(target.GetSetMethod(true), info.SetMethod);
AreElementsEqualWhenResolved(target.GetIndexParameters(), info.IndexParameters);
if (recursive)
{
AreEquivalent(target.PropertyType, info.ValueType, false);
AreEquivalent(target.GetIndexParameters(), info.IndexParameters, true);
}
}
public void AreEquivalent(Type target, ITypeInfo info, bool recursive)
{
if (target.IsGenericParameter)
{
AreEquivalent(target, (IGenericParameterInfo)info, recursive);
return;
}
Assert.AreEqual(CodeElementKind.Type, info.Kind);
AreTypesEquivalent(target, info, recursive);
Assert.AreEqual(target, info.Resolve(true));
if (recursive)
{
if (target.HasElementType)
AreEquivalent(target.GetElementType(), info.ElementType, false);
if (target.BaseType != null)
AreEquivalent(target.BaseType, info.BaseType, false);
AreEquivalent(target.GetGenericArguments(), info.GenericArguments, false);
}
}
public void AreEquivalent(Type target, IGenericParameterInfo info, bool recursive)
{
Assert.AreEqual(CodeElementKind.GenericParameter, info.Kind);
AreTypesEquivalent(target, info, recursive);
Assert.AreEqual(target, info.Resolve(true));
AreEqualWhenResolved(typeof(Type), info.ValueType);
Assert.IsTrue(info.ContainsGenericParameters);
Assert.AreEqual(target.GenericParameterPosition, info.Position);
Assert.AreEqual(target.GenericParameterAttributes & GenericParameterAttributesMask, info.GenericParameterAttributes & GenericParameterAttributesMask);
Assert.IsNull(info.FullName);
Assert.IsNull(info.AssemblyQualifiedName);
}
public void AreEquivalent(ParameterInfo target, IParameterInfo info, bool recursive)
{
Assert.AreEqual(CodeElementKind.Parameter, info.Kind);
AreEqual(target, info.Resolve(true));
AreEqualUpToAssemblyDisplayName(CodeReference.CreateFromParameter(target), info.CodeReference);
Assert.AreEqual(target.Name, info.Name);
Assert.IsNull(info.GetXmlDocumentation());
AreEqualWhenResolved(target.ParameterType, info.ValueType);
Assert.AreEqual(target.Position, info.Position);
Assert.AreEqual(target.Attributes & ParameterAttributesMask, info.ParameterAttributes & ParameterAttributesMask);
AreEqualWhenResolved(target.Member, info.Member);
AreAttributeProvidersEquivalent(target, info);
if (recursive)
{
AreEquivalent(target.ParameterType, info.ValueType, false);
}
}
private void AreFunctionsEquivalent(MethodBase target, IFunctionInfo info, bool recursive)
{
AreMembersEquivalent(target, info, recursive);
MemoizeEquivalence(target, info, delegate
{
AreEqual(target, info.Resolve(true));
Assert.AreEqual(target.IsAbstract, info.IsAbstract);
Assert.AreEqual(target.IsFinal, info.IsFinal);
Assert.AreEqual(target.IsStatic, info.IsStatic);
Assert.AreEqual(target.IsVirtual, info.IsVirtual);
Assert.AreEqual(target.IsAssembly, info.IsAssembly);
Assert.AreEqual(target.IsFamily, info.IsFamily);
Assert.AreEqual(target.IsFamilyAndAssembly, info.IsFamilyAndAssembly);
Assert.AreEqual(target.IsFamilyOrAssembly, info.IsFamilyOrAssembly);
Assert.AreEqual(target.IsPrivate, info.IsPrivate);
Assert.AreEqual(target.IsPublic, info.IsPublic);
Assert.AreEqual(target.IsHideBySig, info.IsHideBySig);
Assert.AreEqual(target.Attributes & MethodAttributesMask, info.MethodAttributes & MethodAttributesMask);
if (supportsCallingConventions)
Assert.AreEqual(target.CallingConvention, info.CallingConvention);
AreElementsEqualWhenResolved(target.GetParameters(), info.Parameters);
// The source location may not be exactly the same with some wrappers.
// What's important is that it is in the same file at least when it is available at all.
CodeLocation targetLocation = DebugSymbolUtils.GetSourceLocation(target);
if (targetLocation == CodeLocation.Unknown)
targetLocation = DebugSymbolUtils.GetSourceLocation(target.DeclaringType);
CodeLocation infoLocation = info.GetCodeLocation();
if (targetLocation != CodeLocation.Unknown && infoLocation != CodeLocation.Unknown)
Assert.AreEqual(targetLocation.Path, infoLocation.Path, StringComparison.InvariantCultureIgnoreCase);
});
if (recursive)
{
AreEquivalent(target.GetParameters(), info.Parameters, true);
}
}
private void AreTypesEquivalent(Type target, ITypeInfo info, bool recursive)
{
AreMembersEquivalent(target, info, recursive);
MemoizeEquivalence(target, info, delegate
{
Assert.AreEqual(target, info.Resolve(true));
Assert.AreEqual(target.Attributes & TypeAttributesMask, info.TypeAttributes & TypeAttributesMask, target.ToString());
Assert.AreEqual(target.Assembly, info.Assembly.Resolve(true), target.ToString());
Assert.AreEqual(target.Namespace ?? "", info.Namespace.Name, target.ToString());
Assert.AreEqual(target.Namespace ?? "", info.NamespaceName, target.ToString());
AreEqualWhenResolved(target.BaseType, info.BaseType);
if (supportsFullAssemblyName)
Assert.AreEqual(target.AssemblyQualifiedName,
info.AssemblyQualifiedName, target.ToString());
else
Assert.StartsWith(target.AssemblyQualifiedName,
info.AssemblyQualifiedName, target.ToString());
Assert.AreEqual(target.FullName,
info.FullName, target.ToString());
AreEqualWhenResolved(target.HasElementType ? target.GetElementType() : null, info.ElementType);
Assert.AreEqual(target.IsAbstract, info.IsAbstract);
Assert.AreEqual(target.IsSealed, info.IsSealed);
Assert.AreEqual(target.IsClass, info.IsClass);
Assert.AreEqual(target.IsEnum, info.IsEnum);
Assert.AreEqual(target.IsInterface, info.IsInterface);
Assert.AreEqual(target.IsValueType, info.IsValueType);
Assert.AreEqual(target.IsNested, info.IsNested);
Assert.AreEqual(target.IsNestedAssembly, info.IsNestedAssembly);
Assert.AreEqual(target.IsNestedFamANDAssem, info.IsNestedFamilyAndAssembly);
Assert.AreEqual(target.IsNestedFamily, info.IsNestedFamily);
Assert.AreEqual(target.IsNestedFamORAssem, info.IsNestedFamilyOrAssembly);
Assert.AreEqual(target.IsNestedPrivate, info.IsNestedPrivate);
Assert.AreEqual(target.IsNestedPublic, info.IsNestedPublic);
Assert.AreEqual(target.IsPublic, info.IsPublic);
Assert.AreEqual(target.IsNotPublic, info.IsNotPublic);
Assert.AreEqual(target.IsArray, info.IsArray);
Assert.AreEqual(target.IsPointer, info.IsPointer);
Assert.AreEqual(target.IsByRef, info.IsByRef);
Assert.AreEqual(target.IsGenericParameter, info.IsGenericParameter);
Assert.AreEqual(Type.GetTypeCode(target), info.TypeCode);
Assert.AreEqual(target.ContainsGenericParameters, info.ContainsGenericParameters);
Assert.AreEqual(target.IsGenericType, info.IsGenericType);
Assert.AreEqual(target.IsGenericTypeDefinition, info.IsGenericTypeDefinition);
AreElementsEqualWhenResolved(target.GetGenericArguments(), info.GenericArguments);
AreEqualWhenResolved(target.IsGenericType ? target.GetGenericTypeDefinition() : null, info.GenericTypeDefinition);
if (target.IsArray)
Assert.AreEqual(target.GetArrayRank(), info.ArrayRank);
else
Assert.Throws<InvalidOperationException>(delegate { GC.KeepAlive(info.ArrayRank); });
if (info.IsArray || info.IsByRef || info.IsPointer || info.IsGenericParameter)
return; // Stop here for special types.
AreElementsEqualWhenResolved(target.GetInterfaces(), info.Interfaces);
BindingFlags constructorFlags = supportsStaticConstructors ? All : BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
AreElementsEqualWhenResolved(target.GetConstructors(constructorFlags), info.GetConstructors(constructorFlags));
AreElementsEqualWhenResolved(target.GetEvents(All), info.GetEvents(All));
AreElementsEqualWhenResolved(target.GetFields(All), info.GetFields(All));
AreElementsEqualWhenResolved(target.GetMethods(All), info.GetMethods(All));
AreElementsEqualWhenResolved(target.GetProperties(All), info.GetProperties(All));
foreach (MethodInfo method in target.GetMethods(AllPublic))
{
if (! supportsSpecialFeatures && IsSpecialMember(method))
continue;
try
{
MethodInfo methodByName = target.GetMethod(method.Name, AllPublic);
Assert.IsNotNull(methodByName);
// In the case of hidden methods, GetMethod might return a different method than we
// expected because the method was hidden but not overridden. In this case, we need
// to perform the comparison on the basis of the named method we obtained rather
// than the one we were originally looking for.
Assert.DoesNotThrow(delegate
{
AreEqualWhenResolved(methodByName, info.GetMethod(methodByName.Name, AllPublic));
});
}
catch (AmbiguousMatchException)
{
// WORKAROUND: The .Net framework contains a BUG associated with hidden generic methods.
// As it compares the method signatures, of the methods, it does not take into
// account the fact that the hidden method's parameter types may not compare
// for equality with those of the hiding method.
//
// For example:
// public class A { public void Method<T>(T t); }
// public class B : A { new public void Method<T>(T t); }
//
// The runtime will not realize that B's Method hides A's because it tries to compare
// parameter types to ascertain it. The generic parameter T of the hiding method will not
// compare for equality with that of the hidden method.
//
// Consequently .Net will throw a spurious AmbiguousMatchException.
//
// Simulating this bug is more trouble than it's worth, so we will ignore it.
if (method.IsGenericMethod)
continue;
Assert.Throws<AmbiguousMatchException>(delegate
{
Assert.IsNotNull(info.GetMethod(method.Name, AllPublic));
});
}
}
foreach (PropertyInfo property in target.GetProperties(AllPublic))
{
if (!supportsSpecialFeatures && IsSpecialMember(property))
continue;
try
{
PropertyInfo propertyByName = target.GetProperty(property.Name, AllPublic);
Assert.IsNotNull(propertyByName);
Assert.DoesNotThrow(delegate
{
AreEqualWhenResolved(propertyByName, info.GetProperty(propertyByName.Name, AllPublic));
});
}
catch (AmbiguousMatchException)
{
Assert.Throws<AmbiguousMatchException>(delegate
{
Assert.IsNotNull(info.GetProperty(property.Name, AllPublic));
});
}
}
foreach (FieldInfo field in target.GetFields(AllPublic))
{
if (!supportsSpecialFeatures && IsSpecialMember(field))
continue;
try
{
FieldInfo fieldByName = target.GetField(field.Name, AllPublic);
Assert.IsNotNull(fieldByName);
Assert.DoesNotThrow(delegate
{
AreEqualWhenResolved(fieldByName, info.GetField(fieldByName.Name, AllPublic));
});
}
catch (AmbiguousMatchException)
{
Assert.Throws<AmbiguousMatchException>(delegate
{
Assert.IsNotNull(info.GetField(field.Name, AllPublic));
});
}
}
foreach (EventInfo @event in target.GetEvents(AllPublic))
{
if (!supportsSpecialFeatures && IsSpecialMember(@event))
continue;
try
{
EventInfo eventByName = target.GetEvent(@event.Name, AllPublic);
Assert.IsNotNull(eventByName);
Assert.DoesNotThrow(delegate
{
AreEqualWhenResolved(eventByName, info.GetEvent(eventByName.Name, AllPublic));
});
}
catch (AmbiguousMatchException)
{
Assert.Throws<AmbiguousMatchException>(delegate
{
Assert.IsNotNull(info.GetEvent(@event.Name, AllPublic));
});
}
}
foreach (Type nestedType in target.GetNestedTypes(AllPublic))
{
try
{
Type nestedTypeByName = target.GetNestedType(nestedType.Name, AllPublic);
Assert.IsNotNull(nestedTypeByName);
Assert.DoesNotThrow(delegate
{
AreEqualWhenResolved(nestedTypeByName, info.GetNestedType(nestedTypeByName.Name, AllPublic));
});
}
catch (AmbiguousMatchException)
{
Assert.Throws<AmbiguousMatchException>(delegate
{
Assert.IsNotNull(info.GetNestedType(nestedType.Name, AllPublic));
});
}
}
});
if (recursive)
{
if (target.IsGenericType)
{
Type[] genericArguments = target.GetGenericArguments();
IList<ITypeInfo> genericArgumentInfos = info.GenericArguments;
for (int i = 0; i < genericArguments.Length; i++)
AreEquivalent(genericArguments[i], genericArgumentInfos[i], false);
}
foreach (FieldInfo field in target.GetFields(All))
{
if (!supportsSpecialFeatures && IsSpecialMember(field))
continue;
IFieldInfo fieldInfo = GetMemberThatIsEqualWhenResolved(field, info.GetFields(All));
AreEquivalent(field, fieldInfo, true);
}
foreach (EventInfo @event in target.GetEvents(All))
{
if (!supportsSpecialFeatures && IsSpecialMember(@event))
continue;
IEventInfo eventInfo = GetMemberThatIsEqualWhenResolved(@event, info.GetEvents(All));
AreEquivalent(@event, eventInfo, true);
}
foreach (PropertyInfo property in target.GetProperties(All))
{
if (!supportsSpecialFeatures && IsSpecialMember(property))
continue;
IPropertyInfo propertyInfo = GetMemberThatIsEqualWhenResolved(property, info.GetProperties(All));
AreEquivalent(property, propertyInfo, true);
}
foreach (ConstructorInfo constructor in target.GetConstructors(All))
{
if (!supportsSpecialFeatures && IsSpecialMember(constructor))
continue;
IConstructorInfo constructorInfo = GetMemberThatIsEqualWhenResolved(constructor, info.GetConstructors(All));
AreEquivalent(constructor, constructorInfo, true);
}
foreach (MethodInfo method in target.GetMethods(All))
{
if (!supportsSpecialFeatures && IsSpecialMember(method))
continue;
IMethodInfo methodInfo = GetMemberThatIsEqualWhenResolved(method, info.GetMethods(All));
AreEquivalent(method, methodInfo, true);
}
foreach (Type nestedType in target.GetNestedTypes(All))
{
ITypeInfo nestedTypeInfo = GetMemberThatIsEqualWhenResolved(nestedType, info.GetNestedTypes(All));
AreEquivalent(nestedType, nestedTypeInfo, true);
}
}
}
private void AreMembersEquivalent(MemberInfo target, IMemberInfo info, bool recursive)
{
AreEqual(target, info.Resolve(true));
Assert.AreEqual(target.ToString(), info.ToString());
Assert.AreEqual(target.Name, info.Name);
AreEqualUpToAssemblyDisplayName(CodeReference.CreateFromMember(target), info.CodeReference);
AreEqualWhenResolved(target.DeclaringType, info.DeclaringType);
AreEqualWhenResolved(target.ReflectedType, info.ReflectedType);
string xmlDocumentation = info.GetXmlDocumentation();
if (xmlDocumentation != null)
Assert.AreEqual(XmlDocumentationUtils.GetXmlDocumentation(target), xmlDocumentation);
AreAttributeProvidersEquivalent(target, info);
}
private void AreEquivalent(ParameterInfo[] parameters, IList<IParameterInfo> parameterInfos, bool recursive)
{
for (int i = 0; i < parameters.Length; i++)
AreEquivalent(parameters[i], parameterInfos[i], recursive);
}
private void AreEquivalent(Type[] types, IList<ITypeInfo> typeInfos, bool recursive)
{
for (int i = 0; i < types.Length; i++)
AreEquivalent(types[i], typeInfos[i], recursive);
}
private static T GetMemberThatIsEqualWhenResolved<T>(MemberInfo member, IEnumerable<T> memberInfos)
where T : IMemberInfo
{
foreach (T memberInfo in memberInfos)
{
MemberInfo resolvedMember = memberInfo.Resolve(true);
if (member.DeclaringType == resolvedMember.DeclaringType
&& member.MetadataToken == resolvedMember.MetadataToken)
return memberInfo;
}
throw new AssertionException(String.Format("Did not find matching member: {0}", member));
}
private void AreEqual(MemberInfo expected, MemberInfo actual)
{
Assert.AreEqual(expected.DeclaringType, actual.DeclaringType);
Assert.AreEqual(expected.MetadataToken, actual.MetadataToken);
}
private void AreEqual(ParameterInfo expected, ParameterInfo actual)
{
Assert.AreEqual(expected.Member.DeclaringType, actual.Member.DeclaringType);
Assert.AreEqual(expected.MetadataToken, actual.MetadataToken);
}
private void AreEqualWhenResolved(Type expected, ITypeInfo wrapper)
{
if (expected != null)
{
Assert.AreEqual(expected, wrapper != null ? wrapper.Resolve(true) : null);
}
else
Assert.IsNull(wrapper);
}
private void AreEqualWhenResolved<TMember, TWrapper>(TMember expected, TWrapper wrapper)
where TMember : MemberInfo
where TWrapper : IMemberInfo
{
if (expected != null)
AreEqual(expected, wrapper != null ? wrapper.Resolve(true) : null);
else
Assert.IsNull(wrapper);
}
private void AreEqualWhenResolved(ParameterInfo expected, IParameterInfo wrapper)
{
if (expected != null)
AreEqual(expected, wrapper != null ? wrapper.Resolve(true) : null);
else
Assert.IsNull(wrapper);
}
private void AreElementsEqualWhenResolved<TWrapper>(IEnumerable<Type> expectedTypes, IEnumerable<TWrapper> actualTypes)
where TWrapper : ITypeInfo
{
Dictionary<string, Type> keyedExpectedTypes = new Dictionary<string, Type>();
foreach (Type expectedType in expectedTypes)
keyedExpectedTypes.Add(expectedType.FullName ?? expectedType.Name, expectedType);
Dictionary<string, ITypeInfo> keyedActualTypes = new Dictionary<string, ITypeInfo>();
foreach (ITypeInfo actualType in actualTypes)
keyedActualTypes.Add(actualType.FullName ?? actualType.Name, actualType);
Assert.Over.KeyedPairs(keyedExpectedTypes, keyedActualTypes, AreEqualWhenResolved);
}
private void AreElementsEqualWhenResolved<TMember, TWrapper>(IEnumerable<TMember> expectedMembers, IEnumerable<TWrapper> actualMembers)
where TMember : MemberInfo
where TWrapper : IMemberInfo
{
Dictionary<string, TMember> keyedExpectedMembers = new Dictionary<string, TMember>();
foreach (TMember expectedMember in expectedMembers)
{
if (!supportsSpecialFeatures && IsSpecialMember(expectedMember))
continue;
string key = expectedMember.DeclaringType + " -> " + expectedMember;
keyedExpectedMembers.Add(key, expectedMember);
}
Dictionary<string, TWrapper> keyedActualMembers = new Dictionary<string, TWrapper>();
foreach (TWrapper actualMember in actualMembers)
{
if (!supportsSpecialFeatures && IsSpecialMember(actualMember.Resolve(false)))
continue;
string key = actualMember.DeclaringType + " -> " + actualMember;
if (keyedActualMembers.ContainsKey(key))
Assert.Fail("Found duplicate member: {0}", key);
keyedActualMembers.Add(key, actualMember);
}
Assert.Over.KeyedPairs(keyedExpectedMembers, keyedActualMembers, AreEqualWhenResolved);
}
private void AreElementsEqualWhenResolved(IEnumerable<ParameterInfo> expected, IEnumerable<IParameterInfo> actual)
{
Assert.Over.Pairs(expected, actual, AreEqualWhenResolved);
}
private void AreAttributeProvidersEquivalent<TTarget, TWrapper>(TTarget expectedTarget, TWrapper actualWrapper)
where TTarget : ICustomAttributeProvider
where TWrapper : ICodeElementInfo
{
// There are some weird cases with attributes of object.
// For example, the runtime reutrns ComVisibleAttributer and ClassInterfaceAttribute
// when the "inherit" flag is false, but not if the flag is true!
if (! supportsSpecialFeatures && expectedTarget is Type && expectedTarget.Equals(typeof(object)))
return;
if (!supportsReturnAttributes)
{
MethodInfo targetMethod = expectedTarget as MethodInfo;
if (targetMethod != null && MightHaveOrInheritReturnParameter(targetMethod))
return;
}
if (!supportsGenericParameterAttributes)
{
Type targetType = expectedTarget as Type;
if (targetType != null && targetType.IsGenericParameter)
return;
}
IList<object> nonInheritedAttribs;
IList<object> inheritedAttribs;
try
{
nonInheritedAttribs = expectedTarget.GetCustomAttributes(false);
inheritedAttribs = expectedTarget.GetCustomAttributes(true);
}
catch (ArgumentException)
{
// The sample assembly might have some attributes with deliberately invalid arguments.
// If we trip over then, we can just ignore them. It would be better to check that
// the same exception were thrown but that's a little tedious and in any case we
// have pretty good guarantees that it will given everything else works.
return;
}
ITypeInfo attributeType = Reflector.Wrap(typeof(Attribute));
AreAttributesOfSameTypesExcludingSpecialAttributes(nonInheritedAttribs,
actualWrapper.GetAttributes(null, false));
AreAttributesOfSameTypesExcludingSpecialAttributes(inheritedAttribs,
actualWrapper.GetAttributes(null, true));
AreAttributesOfSameTypesExcludingSpecialAttributes(nonInheritedAttribs,
actualWrapper.GetAttributes(attributeType, false));
AreAttributesOfSameTypesExcludingSpecialAttributes(inheritedAttribs,
actualWrapper.GetAttributes(attributeType, true));
AreAttributesOfSameTypesExcludingSpecialAttributes(nonInheritedAttribs,
actualWrapper.GetAttributeInfos(null, false));
AreAttributesOfSameTypesExcludingSpecialAttributes(inheritedAttribs,
actualWrapper.GetAttributeInfos(null, true));
AreAttributesOfSameTypesExcludingSpecialAttributes(nonInheritedAttribs,
actualWrapper.GetAttributeInfos(attributeType, false));
AreAttributesOfSameTypesExcludingSpecialAttributes(inheritedAttribs,
actualWrapper.GetAttributeInfos(attributeType, true));
foreach (object nonInheritedAttrib in nonInheritedAttribs)
{
if (supportsSpecialFeatures || !IsSpecialAttribute(nonInheritedAttrib))
Assert.IsTrue(AttributeUtils.HasAttribute(actualWrapper, nonInheritedAttrib.GetType(), false),
"Should contain non-inherited attributes of same type.");
}
foreach (object inheritedAttrib in inheritedAttribs)
{
if (supportsSpecialFeatures || !IsSpecialAttribute(inheritedAttrib))
Assert.IsTrue(AttributeUtils.HasAttribute(actualWrapper, inheritedAttrib.GetType(), true),
"Should contain inherited attributes of same type.");
}
}
private void AreAttributesOfSameTypesExcludingSpecialAttributes(IEnumerable<object> expected,
IEnumerable<object> actual)
{
Dictionary<Type, int> expectedCounts = new Dictionary<Type, int>();
Dictionary<Type, int> actualCounts = new Dictionary<Type, int>();
foreach (object expectedAttrib in expected)
if (supportsSpecialFeatures || !IsSpecialAttribute(expectedAttrib))
IncrementCount(expectedCounts, expectedAttrib.GetType());
foreach (object actualAttrib in actual)
if (supportsSpecialFeatures || !IsSpecialAttribute(actualAttrib))
IncrementCount(actualCounts, actualAttrib.GetType());
Assert.Over.KeyedPairs(expectedCounts, actualCounts, delegate(Type type, int expectedCount, int actualCount)
{
Assert.AreEqual(expectedCount, actualCount, "Number of {0} attributes should be equal.", type);
});
}
private void AreAttributesOfSameTypesExcludingSpecialAttributes(IEnumerable<object> expected,
IEnumerable<IAttributeInfo> actual)
{
List<object> actualResolvedObjects = new List<object>();
foreach (IAttributeInfo attrib in actual)
actualResolvedObjects.Add(attrib.Resolve(false));
AreAttributesOfSameTypesExcludingSpecialAttributes(expected, actualResolvedObjects);
}
private static void IncrementCount(IDictionary<Type, int> counts, Type type)
{
int count;
counts.TryGetValue(type, out count);
counts[type] = count + 1;
}
public bool IsUnsupportedType(Type type)
{
if (!supportsNestedGenericTypes && IsNestedGenericType(type))
return true;
return false;
}
private bool IsNestedGenericType(Type type)
{
int genericTypeCount = 0;
while (type != null)
{
if (type.IsGenericType)
genericTypeCount += 1;
type = type.DeclaringType;
}
return genericTypeCount > 1;
}
private bool IsSpecialAttribute(object attrib)
{
return attrib is ComVisibleAttribute
|| attrib is ClassInterfaceAttribute
|| attrib is DefaultMemberAttribute
|| attrib is SerializableAttribute
|| attrib is DebuggableAttribute
|| attrib is CompilationRelaxationsAttribute
|| attrib is RuntimeCompatibilityAttribute
|| attrib is AssemblyCultureAttribute
|| attrib is AssemblyVersionAttribute
|| attrib is SecurityAttribute
|| attrib is StructLayoutAttribute
|| attrib is MethodImplAttribute;
}
private bool IsSpecialMember(FieldInfo field)
{
if (! supportsEventFields && field.FieldType.IsSubclassOf(typeof(Delegate))) // imprecise hack
return true;
return IsSpecialMember(field, field.IsPublic);
}
private bool IsSpecialMember(PropertyInfo property)
{
return IsSpecialMember(property,
property.GetGetMethod() != null
|| property.GetSetMethod() != null);
}
private bool IsSpecialMember(EventInfo @event)
{
return IsSpecialMember(@event,
@event.GetAddMethod() != null
|| @event.GetRemoveMethod() != null
|| @event.GetRaiseMethod() != null);
}
private bool IsSpecialMember(MethodBase function)
{
if (!supportsCallingConventions && (function.CallingConvention & CallingConventions.VarArgs) != 0)
return true;
if (!supportsFinalizers && function.Name == "Finalize")
return true;
if (function.IsConstructor && function.DeclaringType.IsSubclassOf(typeof(Delegate)))
return true;
return IsSpecialMember(function, function.IsPublic);
}
private bool IsSpecialMember(MemberInfo member)
{
if (member is FieldInfo)
return IsSpecialMember((FieldInfo)member);
if (member is PropertyInfo)
return IsSpecialMember((PropertyInfo)member);
if (member is EventInfo)
return IsSpecialMember((EventInfo)member);
if (member is MethodBase)
return IsSpecialMember((MethodBase)member);
throw new NotSupportedException("Unsupported member.");
}
private bool IsSpecialMember(MemberInfo member, bool isPublic)
{
if (! isPublic && member.DeclaringType.Namespace.StartsWith("System"))
return true;
return member.Name.Contains("<");
}
private static bool MightHaveOrInheritReturnParameter(MethodInfo method)
{
if (HasReturnParameter(method))
return true;
// Check possibly overridden methods.
for (Type baseType = method.DeclaringType.BaseType; baseType != null; baseType = baseType.BaseType)
{
foreach (MethodInfo inheritedMethod in baseType.GetMethods(All | BindingFlags.DeclaredOnly))
{
if (method.Name == inheritedMethod.Name && HasReturnParameter(inheritedMethod))
return true;
}
}
return false;
}
private static bool HasReturnParameter(MethodInfo method)
{
return method.ReturnParameter.GetCustomAttributes(true).Length != 0;
}
private static void AreEqualUpToAssemblyDisplayName(CodeReference expected, CodeReference actual)
{
Assert.AreEqual(
new CodeReference(new AssemblyName(expected.AssemblyName).Name,
expected.NamespaceName, expected.TypeName, expected.MemberName, expected.ParameterName),
new CodeReference(new AssemblyName(actual.AssemblyName).Name,
actual.NamespaceName, actual.TypeName, actual.MemberName, actual.ParameterName));
}
/// <summary>
/// We memoize results from comparing for equivalence of certain members to help
/// the exhaustive recursive reflection tests run in a more reasonable period of time.
/// This implementation assumes that the Equals methods are implemented correctly.
/// If you're uncertain of this, you should disable memoization.
/// </summary>
private void MemoizeEquivalence(object target, object wrapper, Action action)
{
if (!equivalenceCache.Contains(target, wrapper))
{
action();
equivalenceCache.Add(target, wrapper);
}
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Common;
namespace Randoop
{
/// <summary>
/// Creates C# source code for a Plan.
///
/// WARNING: THIS CODE IS TRICKY! The main reason it's tricky
/// is because the plan data structure is itself tricky, and
/// that complexity spills over into this code.
///
/// The trickiest part is coming up with variable names for
/// the values that the plan creates and propagating that
/// information as the plan is visited.
/// </summary>
public class CodeGenerator
{
private CodeGenerator()
{
// Empty body.
}
/// <summary>
/// Returns C# source code for the given plan.
/// The code is returns as a list of strings, one
/// per line (each line contains a statement).
/// </summary>
public static ReadOnlyCollection<string> AsCSharpCode(Plan p)
{
if (p == null) throw new ArgumentNullException();
CSharpGenVisitor v = new CSharpGenVisitor();
v.Visit(p);
return v.Code;
}
public class OutPortId
{
private readonly List<int> list;
private readonly int i;
public OutPortId(Collection<int> list, int i)
{
if (list == null) throw new ArgumentNullException();
this.list = new List<int>(list);
this.i = i;
}
public override bool Equals(object obj)
{
OutPortId other = obj as OutPortId;
bool retval = true;
if (other == null)
{
retval = false;
}
else if (this.i != other.i)
{
retval = false;
}
else if (this.list.Count != other.list.Count)
{
retval = false;
}
else
{
for (int c = 0; c < this.list.Count; c++)
if (this.list[c] != other.list[c])
{
retval = false;
break;
}
}
string s1 = this.ToString();
string s2 = other.ToString();
if (retval == true && this.GetHashCode() != other.GetHashCode())
throw new Exception();
if (retval == false && s1.Equals(s2))
throw new Exception();
if (retval == true && !s1.Equals(s2))
throw new Exception();
return retval;
}
public override int GetHashCode()
{
int hash = 7;
foreach (int e in list)
hash = 31 * hash + e;
hash = 31 * hash + i;
return hash;
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
b.Append("[");
foreach (int le in list)
b.Append(" " + le);
b.Append(" ]");
b.Append("." + i);
return b.ToString();
}
}
public class NameMap
{
private Dictionary<OutPortId, string> names = new Dictionary<OutPortId, string>();
// For sanity checking (not for functionality).
private Dictionary<string, string> namesghost = new Dictionary<string, string>();
// For sanity checking (not for functionality).
private List<string> keys = new List<string>();
public string Get(OutPortId id)
{
return names[id];
}
public void set(OutPortId id, string s)
{
bool alreadyThere = keys.Contains(id.ToString());
int keySize = names.Keys.Count;
if (names.ContainsKey(id) && !namesghost.ContainsKey(id.ToString()))
throw new Exception();
names[id] = s;
namesghost[id.ToString()] = s;
if (names.Keys.Count != namesghost.Keys.Count)
throw new Exception();
if (alreadyThere && keySize < names.Keys.Count)
throw new Exception();
keys.Add(id.ToString());
}
}
public class NameManager
{
private int nameCounter = 0;
public NameMap foobar = new NameMap();
public void ProcessPlan(Plan p, Collection<int> path)
{
// Create new name for p's result.
string freshvar = "v" + nameCounter++;
if (p.transformer is MethodCall)
{
MapOutputPortsMethod(p, path, freshvar);
}
else if ((p.transformer is ConstructorCallTransformer))
{
MapOutputPortsConstructor(p, path, freshvar);
}
else if (p.transformer is ArrayOrArrayListBuilderTransformer)
{
MapOutputPortsArray(p, path, freshvar);
}
else if (p.transformer is DummyTransformer)
{
MapOutputPortsDummy(p, path, freshvar);
}
else if (p.transformer is PrimitiveValueTransformer)
{
MapOutputPortsPrimitive(p, path, freshvar);
}
else //TODO: do this
{
Util.Assert(p.transformer is FieldSettingTransformer);
MapOutputPortsFieldSetter(p, path, freshvar);
}
}
private void MapOutputPortsDummy(Plan p, Collection<int> path, string freshvar)
{
OutPortId newObjPort = new OutPortId(path, 0);
foobar.set(newObjPort, freshvar);
}
private void MapOutputPortsPrimitive(Plan p, Collection<int> path, string freshvar)
{
// Map primitive.
OutPortId newObjPort = new OutPortId(path, 0);
foobar.set(newObjPort, freshvar);
}
private void MapOutputPortsFieldSetter(Plan p, Collection<int> path, string freshvar)
{
// Map receiver.
Plan.ParameterChooser c = p.parameterChoosers[0];
OutPortId pOutputPort = new OutPortId(path, 0);
path.Add(c.planIndex);
OutPortId recPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
foobar.set(pOutputPort, foobar.Get(recPort));
}
private void MapOutputPortsArray(Plan p, Collection<int> path, string freshvar)
{
// Map new array object.
OutPortId newObjPort = new OutPortId(path, 0);
foobar.set(newObjPort, freshvar);
// Map parameters.
for (int i = 0; i < p.parameterChoosers.Length; i++)
{
Plan.ParameterChooser c = p.parameterChoosers[i];
OutPortId pOutputPort = new OutPortId(path, i + 1);
path.Add(c.planIndex);
OutPortId paramPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
foobar.set(pOutputPort, foobar.Get(paramPort));
}
}
private void MapOutputPortsConstructor(Plan p, Collection<int> path, string freshvar)
{
// Map new object.
OutPortId newObjPort = new OutPortId(path, 0);
foobar.set(newObjPort, freshvar);
// Map mutated parameters.
for (int i = 0; i < p.parameterChoosers.Length; i++)
{
Plan.ParameterChooser c = p.parameterChoosers[i];
OutPortId pOutputPort = new OutPortId(path, i + 1);
path.Add(c.planIndex);
OutPortId paramPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
foobar.set(pOutputPort, foobar.Get(paramPort));
}
}
private void MapOutputPortsMethod(Plan p, Collection<int> path, string freshvar)
{
// Map receiver.
Plan.ParameterChooser c = p.parameterChoosers[0];
OutPortId pOutputPort = new OutPortId(path, 0);
path.Add(c.planIndex);
OutPortId recPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
foobar.set(pOutputPort, foobar.Get(recPort));
// Map return value.
MethodCall mct = p.transformer as MethodCall;
if (!mct.method.ReturnType.Equals(typeof(void)))
{
OutPortId newObjPort = new OutPortId(path, 1);
foobar.set(newObjPort, freshvar);
}
// Map mutated parameters.
// Start from 1 because already handled receiver.
for (int i = 1; i < p.parameterChoosers.Length; i++)
{
c = p.parameterChoosers[i];
pOutputPort = new OutPortId(path, i + 1); // Add 1 because of retval.
path.Add(c.planIndex);
OutPortId paramPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
foobar.set(pOutputPort, foobar.Get(paramPort));
}
}
}
// TODO give it a more specific name.
public class PlanVisitor
{
protected NameManager nameManager;
public void Visit(Plan p)
{
nameManager = new NameManager();
Visit(p, new Collection<int>());
}
protected virtual void Visit(Plan p, Collection<int> path)
{
for (int i = 0; i < p.parentPlans.Length; i++)
{
Plan p2 = p.parentPlans[i];
path.Add(i);
Visit(p2, path);
path.RemoveAt(path.Count - 1);
}
nameManager.ProcessPlan(p, path);
}
}
public class DebuggingStringVisitor : PlanVisitor
{
protected override void Visit(Plan p, Collection<int> path)
{
base.Visit(p, path);
}
}
private class CSharpGenVisitor : PlanVisitor
{
public ReadOnlyCollection<string> Code
{
get
{
return new ReadOnlyCollection<string>(b);
}
}
Collection<string> b = new Collection<string>();
protected override void Visit(Plan p, Collection<int> path)
{
base.Visit(p, path);
if (p.transformer is MethodCall)
{
HandleMethod(p, path);
}
else if ((p.transformer is ConstructorCallTransformer))
{
HandleConstructor(p, path);
}
else if (p.transformer is ArrayOrArrayListBuilderTransformer)
{
HandleArray(p, path);
}
else if (p.transformer is DummyTransformer)
{
HandleDummy(p, path);
}
else if (p.transformer is PrimitiveValueTransformer)
{
HandlePrimitive(p, path);
}
else //TODO: do this
{
Util.Assert(p.transformer is FieldSettingTransformer);
HandleField(p, path);
}
}
private void HandleField(Plan p, Collection<int> path)
{
Collection<string> args = new Collection<string>();
for (int i = 0; i < p.parameterChoosers.Length; i++)
{
Plan.ParameterChooser c = p.parameterChoosers[i];
path.Add(c.planIndex);
OutPortId paramPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
args.Add(nameManager.foobar.Get(paramPort));
}
b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(args), "dummy"));
}
private void HandlePrimitive(Plan p, Collection<int> path)
{
OutPortId newPort = new OutPortId(path, 0);
string newName = nameManager.foobar.Get(newPort);
b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(new List<string>()), newName));
}
private void HandleDummy(Plan p, Collection<int> path)
{
// Dummy transformer has no associated code.
}
private void HandleConstructor(Plan p, Collection<int> path)
{
OutPortId newObjPort = new OutPortId(path, 0);
string newObjName = nameManager.foobar.Get(newObjPort);
Collection<string> args = new Collection<string>();
for (int i = 0; i < p.parameterChoosers.Length; i++)
{
Plan.ParameterChooser c = p.parameterChoosers[i];
path.Add(c.planIndex);
OutPortId paramPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
args.Add(nameManager.foobar.Get(paramPort));
}
b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(args), nameManager.foobar.Get(newObjPort)));
}
private void HandleMethod(Plan p, Collection<int> path)
{
MethodCall mct = p.transformer as MethodCall;
string freshvar = null;
if (!mct.method.ReturnType.Equals(typeof(void)))
{
OutPortId newObjPort = new OutPortId(path, 1);
freshvar = nameManager.foobar.Get(newObjPort);
}
Collection<string> arguments = new Collection<string>();
for (int i = 0; i < p.parameterChoosers.Length; i++)
{
if (i == 0 && mct.method.IsStatic)
{
arguments.Add(null);
continue;
}
Plan.ParameterChooser c = p.parameterChoosers[i];
path.Add(c.planIndex);
OutPortId paramPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
arguments.Add(nameManager.foobar.Get(paramPort));
}
b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(arguments), freshvar));
}
private void HandleArray(Plan p, Collection<int> path)
{
OutPortId newObjPort = new OutPortId(path, 0);
string newObjName = nameManager.foobar.Get(newObjPort);
Collection<string> args = new Collection<string>();
for (int i = 0; i < p.parameterChoosers.Length; i++)
{
Plan.ParameterChooser c = p.parameterChoosers[i];
path.Add(c.planIndex);
OutPortId paramPort = new OutPortId(path, c.resultIndex);
path.RemoveAt(path.Count - 1);
args.Add(nameManager.foobar.Get(paramPort));
}
b.Add(p.transformer.ToCSharpCode(new ReadOnlyCollection<string>(args), nameManager.foobar.Get(newObjPort)));
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising 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.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
using System.ComponentModel.Design;
namespace Controls
{
/// <summary>
/// Summary description for RoundedCornerPanel.
/// </summary>
///
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public class RoundedCornerPanel : System.Windows.Forms.ScrollableControl
{
private int cornerRadius = 10;
private SolidBrush backBrush;
private Color panelColor = Color.White;
private Pen borderPen;
private GraphicsPath path;
private bool displayShadow = false;
private bool fadeShadow = true;
private int shadowOffset = 5;
private Color shadowColor = Color.Gray;
private System.ComponentModel.Container components = null;
public RoundedCornerPanel()
{
this.SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
InitializeComponent();
this.DoubleBuffered = true;
backBrush = new SolidBrush(panelColor);
borderPen = new Pen(this.ForeColor, 1.0f);
path = new GraphicsPath();
CreateGraphicsPath();
}
private void CreateGraphicsPath()
{
int cornerDiameter = cornerRadius * 2;
path.Reset();
int halfBorderWidth = (int)(borderPen.Width / 2);
if (displayShadow)
{
path.AddArc(halfBorderWidth, halfBorderWidth, cornerDiameter, cornerDiameter, 180, 90);
path.AddArc(this.Width - cornerDiameter - halfBorderWidth - shadowOffset - 1, halfBorderWidth, cornerDiameter, cornerDiameter, 270, 90);
path.AddArc(this.Width - cornerDiameter - halfBorderWidth - shadowOffset - 1, this.Height - cornerDiameter - halfBorderWidth - shadowOffset - 1, cornerDiameter, cornerDiameter, 0, 90);
path.AddArc(halfBorderWidth, this.Height - cornerDiameter - halfBorderWidth - shadowOffset - 1, cornerDiameter, cornerDiameter, 90, 90);
}
else
{
path.AddArc(halfBorderWidth, halfBorderWidth, cornerDiameter, cornerDiameter, 180, 90);
path.AddArc(this.Width - cornerDiameter - halfBorderWidth - 1, halfBorderWidth, cornerDiameter, cornerDiameter, 270, 90);
path.AddArc(this.Width - cornerDiameter - halfBorderWidth - 1, this.Height - cornerDiameter - halfBorderWidth - 1, cornerDiameter, cornerDiameter, 0, 90);
path.AddArc(halfBorderWidth, this.Height - cornerDiameter - halfBorderWidth - 1, cornerDiameter, cornerDiameter, 90, 90);
}
path.CloseFigure();
}
/*private void Redraw()
{
this.Draw(null);
}*/
protected override void OnForeColorChanged(EventArgs e)
{
borderPen.Color = this.ForeColor;
this.Invalidate();
base.OnForeColorChanged(e);
}
public float BorderSize
{
get
{
return borderPen.Width;
}
set
{
borderPen.Width = value;
CreateGraphicsPath();
this.Invalidate();
}
}
protected override void OnBackColorChanged(EventArgs e)
{
base.OnBackColorChanged (e);
this.Invalidate();
}
public Color ShadowColor
{
get
{
return shadowColor;
}
set
{
shadowColor = value;
this.Invalidate();
}
}
/*public bool FadeShadow
{
get
{
return fadeShadow;
}
set
{
fadeShadow = value;
this.Invalidate();
}
}*/
public bool DisplayShadow
{
get
{
return displayShadow;
}
set
{
this.displayShadow = value;
CreateGraphicsPath();
this.Invalidate();
}
}
public int ShadowOffset
{
get
{
return shadowOffset;
}
set
{
shadowOffset = value;
CreateGraphicsPath();
this.Invalidate();
}
}
public Color PanelColor
{
get
{
return panelColor;
}
set
{
panelColor = value;
backBrush.Color = value;
this.Invalidate();
}
}
public int CornerRadius
{
get
{
return cornerRadius;
}
set
{
cornerRadius = value;
CreateGraphicsPath();
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
//e.Graphics.Clear(this.BackColor);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
// Draw the shadow
if (displayShadow)
{
using (SolidBrush shadowBrush = new SolidBrush(shadowColor))
{
/*if (fadeShadow)
{
for (int index = shadowOffset; index >= 0; index--)
{
}
}
else
{*/
e.Graphics.TranslateTransform(shadowOffset, shadowOffset);
e.Graphics.FillPath(shadowBrush, path);
e.Graphics.ResetTransform();
//}
}
}
e.Graphics.FillPath(backBrush, path);
e.Graphics.DrawPath(borderPen, path);
}
/*protected override void OnPaintBackground(PaintEventArgs pevent)
{
base.OnPaintBackground (pevent);
}*/
/// <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 Component 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()
{
//
// RoundedCornerPanel
//
this.Name = "RoundedCornerPanel";
this.Size = new System.Drawing.Size(144, 88);
this.Resize += new System.EventHandler(this.RoundedCornerPanel_Resize);
}
#endregion
private void RoundedCornerPanel_Resize(object sender, System.EventArgs e)
{
CreateGraphicsPath();
this.Invalidate();
}
}
}
| |
namespace Projections
{
partial class EllipticPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component 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.m_toolTip = new System.Windows.Forms.ToolTip(this.components);
this.label4 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.m_k2TextBox = new System.Windows.Forms.TextBox();
this.m_alpha2TextBox = new System.Windows.Forms.TextBox();
this.m_kp2TextBox = new System.Windows.Forms.TextBox();
this.m_alphap2TextBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.m_constructorComboBox = new System.Windows.Forms.ComboBox();
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.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.m_KtextBox = new System.Windows.Forms.TextBox();
this.m_EtextBox = new System.Windows.Forms.TextBox();
this.m_DtextBox = new System.Windows.Forms.TextBox();
this.m_KEtextBox = new System.Windows.Forms.TextBox();
this.m_PItextBox = new System.Windows.Forms.TextBox();
this.m_GtextBox = new System.Windows.Forms.TextBox();
this.m_HtextBox = new System.Windows.Forms.TextBox();
this.label13 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.label17 = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.label19 = new System.Windows.Forms.Label();
this.m_phiTextBox = new System.Windows.Forms.TextBox();
this.m_EphiTextBox = new System.Windows.Forms.TextBox();
this.m_DphiTextBox = new System.Windows.Forms.TextBox();
this.m_FphiTextBox = new System.Windows.Forms.TextBox();
this.m_PiphiTextBox = new System.Windows.Forms.TextBox();
this.m_GphiTextBox = new System.Windows.Forms.TextBox();
this.m_HphiTextBox = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(9, 11);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(19, 13);
this.label4.TabIndex = 0;
this.label4.Text = "k2";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 37);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(39, 13);
this.label1.TabIndex = 1;
this.label1.Text = "alpha2";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(9, 63);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(25, 13);
this.label2.TabIndex = 2;
this.label2.Text = "kp2";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(9, 89);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(45, 13);
this.label3.TabIndex = 3;
this.label3.Text = "alphap2";
//
// m_k2TextBox
//
this.m_k2TextBox.Location = new System.Drawing.Point(76, 7);
this.m_k2TextBox.Name = "m_k2TextBox";
this.m_k2TextBox.Size = new System.Drawing.Size(100, 20);
this.m_k2TextBox.TabIndex = 4;
//
// m_alpha2TextBox
//
this.m_alpha2TextBox.Location = new System.Drawing.Point(76, 33);
this.m_alpha2TextBox.Name = "m_alpha2TextBox";
this.m_alpha2TextBox.Size = new System.Drawing.Size(100, 20);
this.m_alpha2TextBox.TabIndex = 5;
//
// m_kp2TextBox
//
this.m_kp2TextBox.Location = new System.Drawing.Point(76, 59);
this.m_kp2TextBox.Name = "m_kp2TextBox";
this.m_kp2TextBox.Size = new System.Drawing.Size(100, 20);
this.m_kp2TextBox.TabIndex = 6;
//
// m_alphap2TextBox
//
this.m_alphap2TextBox.Location = new System.Drawing.Point(76, 85);
this.m_alphap2TextBox.Name = "m_alphap2TextBox";
this.m_alphap2TextBox.Size = new System.Drawing.Size(100, 20);
this.m_alphap2TextBox.TabIndex = 7;
//
// button1
//
this.button1.Location = new System.Drawing.Point(47, 141);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 8;
this.button1.Text = "Set";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.OnSet);
//
// m_constructorComboBox
//
this.m_constructorComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.m_constructorComboBox.FormattingEnabled = true;
this.m_constructorComboBox.Items.AddRange(new object[] {
"Constructor #1",
"Constructor #2"});
this.m_constructorComboBox.Location = new System.Drawing.Point(76, 113);
this.m_constructorComboBox.Name = "m_constructorComboBox";
this.m_constructorComboBox.Size = new System.Drawing.Size(100, 21);
this.m_constructorComboBox.TabIndex = 9;
this.m_toolTip.SetToolTip(this.m_constructorComboBox, "Selects the constructor");
this.m_constructorComboBox.SelectedIndexChanged += new System.EventHandler(this.OnConstructor);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(9, 117);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(61, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Constructor";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(186, 11);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(14, 13);
this.label6.TabIndex = 11;
this.label6.Text = "K";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(186, 37);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(14, 13);
this.label7.TabIndex = 12;
this.label7.Text = "E";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(186, 63);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(15, 13);
this.label8.TabIndex = 13;
this.label8.Text = "D";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(186, 89);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(21, 13);
this.label9.TabIndex = 14;
this.label9.Text = "KE";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(186, 113);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(16, 13);
this.label10.TabIndex = 15;
this.label10.Text = "Pi";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(186, 141);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(15, 13);
this.label11.TabIndex = 16;
this.label11.Text = "G";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(186, 168);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(15, 13);
this.label12.TabIndex = 17;
this.label12.Text = "H";
//
// m_KtextBox
//
this.m_KtextBox.Location = new System.Drawing.Point(218, 7);
this.m_KtextBox.Name = "m_KtextBox";
this.m_KtextBox.ReadOnly = true;
this.m_KtextBox.Size = new System.Drawing.Size(100, 20);
this.m_KtextBox.TabIndex = 18;
//
// m_EtextBox
//
this.m_EtextBox.Location = new System.Drawing.Point(218, 33);
this.m_EtextBox.Name = "m_EtextBox";
this.m_EtextBox.ReadOnly = true;
this.m_EtextBox.Size = new System.Drawing.Size(100, 20);
this.m_EtextBox.TabIndex = 19;
//
// m_DtextBox
//
this.m_DtextBox.Location = new System.Drawing.Point(218, 59);
this.m_DtextBox.Name = "m_DtextBox";
this.m_DtextBox.ReadOnly = true;
this.m_DtextBox.Size = new System.Drawing.Size(100, 20);
this.m_DtextBox.TabIndex = 20;
//
// m_KEtextBox
//
this.m_KEtextBox.Location = new System.Drawing.Point(218, 85);
this.m_KEtextBox.Name = "m_KEtextBox";
this.m_KEtextBox.ReadOnly = true;
this.m_KEtextBox.Size = new System.Drawing.Size(100, 20);
this.m_KEtextBox.TabIndex = 21;
//
// m_PItextBox
//
this.m_PItextBox.Location = new System.Drawing.Point(218, 111);
this.m_PItextBox.Name = "m_PItextBox";
this.m_PItextBox.ReadOnly = true;
this.m_PItextBox.Size = new System.Drawing.Size(100, 20);
this.m_PItextBox.TabIndex = 22;
//
// m_GtextBox
//
this.m_GtextBox.Location = new System.Drawing.Point(218, 137);
this.m_GtextBox.Name = "m_GtextBox";
this.m_GtextBox.ReadOnly = true;
this.m_GtextBox.Size = new System.Drawing.Size(100, 20);
this.m_GtextBox.TabIndex = 23;
//
// m_HtextBox
//
this.m_HtextBox.Location = new System.Drawing.Point(218, 163);
this.m_HtextBox.Name = "m_HtextBox";
this.m_HtextBox.ReadOnly = true;
this.m_HtextBox.Size = new System.Drawing.Size(100, 20);
this.m_HtextBox.TabIndex = 24;
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(329, 11);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(21, 13);
this.label13.TabIndex = 25;
this.label13.Text = "phi";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(329, 37);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(34, 13);
this.label14.TabIndex = 26;
this.label14.Text = "E(phi)";
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(329, 89);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(33, 13);
this.label15.TabIndex = 27;
this.label15.Text = "F(phi)";
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(329, 63);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(35, 13);
this.label16.TabIndex = 28;
this.label16.Text = "D(phi)";
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(329, 115);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(36, 13);
this.label17.TabIndex = 29;
this.label17.Text = "Pi(phi)";
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(329, 141);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(35, 13);
this.label18.TabIndex = 30;
this.label18.Text = "G(phi)";
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(329, 167);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(35, 13);
this.label19.TabIndex = 31;
this.label19.Text = "H(phi)";
//
// m_phiTextBox
//
this.m_phiTextBox.Location = new System.Drawing.Point(371, 7);
this.m_phiTextBox.Name = "m_phiTextBox";
this.m_phiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_phiTextBox.TabIndex = 32;
//
// m_EphiTextBox
//
this.m_EphiTextBox.Location = new System.Drawing.Point(371, 33);
this.m_EphiTextBox.Name = "m_EphiTextBox";
this.m_EphiTextBox.ReadOnly = true;
this.m_EphiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_EphiTextBox.TabIndex = 33;
//
// m_DphiTextBox
//
this.m_DphiTextBox.Location = new System.Drawing.Point(372, 59);
this.m_DphiTextBox.Name = "m_DphiTextBox";
this.m_DphiTextBox.ReadOnly = true;
this.m_DphiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_DphiTextBox.TabIndex = 34;
//
// m_FphiTextBox
//
this.m_FphiTextBox.Location = new System.Drawing.Point(371, 85);
this.m_FphiTextBox.Name = "m_FphiTextBox";
this.m_FphiTextBox.ReadOnly = true;
this.m_FphiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_FphiTextBox.TabIndex = 35;
//
// m_PiphiTextBox
//
this.m_PiphiTextBox.Location = new System.Drawing.Point(371, 111);
this.m_PiphiTextBox.Name = "m_PiphiTextBox";
this.m_PiphiTextBox.ReadOnly = true;
this.m_PiphiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_PiphiTextBox.TabIndex = 36;
//
// m_GphiTextBox
//
this.m_GphiTextBox.Location = new System.Drawing.Point(371, 137);
this.m_GphiTextBox.Name = "m_GphiTextBox";
this.m_GphiTextBox.ReadOnly = true;
this.m_GphiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_GphiTextBox.TabIndex = 37;
//
// m_HphiTextBox
//
this.m_HphiTextBox.Location = new System.Drawing.Point(371, 163);
this.m_HphiTextBox.Name = "m_HphiTextBox";
this.m_HphiTextBox.ReadOnly = true;
this.m_HphiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_HphiTextBox.TabIndex = 38;
//
// button2
//
this.button2.Location = new System.Drawing.Point(332, 190);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(139, 23);
this.button2.TabIndex = 39;
this.button2.Text = "Calculate phi functions";
this.m_toolTip.SetToolTip(this.button2, "Calculate all functions that use phi as an input");
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.OnComputePhi);
//
// button3
//
this.button3.Location = new System.Drawing.Point(47, 168);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 40;
this.button3.Text = "Validate";
this.m_toolTip.SetToolTip(this.button3, "Verifies Elliptic Function interfaces");
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.OnValidate);
//
// EllipticPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.m_HphiTextBox);
this.Controls.Add(this.m_GphiTextBox);
this.Controls.Add(this.m_PiphiTextBox);
this.Controls.Add(this.m_FphiTextBox);
this.Controls.Add(this.m_DphiTextBox);
this.Controls.Add(this.m_EphiTextBox);
this.Controls.Add(this.m_phiTextBox);
this.Controls.Add(this.label19);
this.Controls.Add(this.label18);
this.Controls.Add(this.label17);
this.Controls.Add(this.label16);
this.Controls.Add(this.label15);
this.Controls.Add(this.label14);
this.Controls.Add(this.label13);
this.Controls.Add(this.m_HtextBox);
this.Controls.Add(this.m_GtextBox);
this.Controls.Add(this.m_PItextBox);
this.Controls.Add(this.m_KEtextBox);
this.Controls.Add(this.m_DtextBox);
this.Controls.Add(this.m_EtextBox);
this.Controls.Add(this.m_KtextBox);
this.Controls.Add(this.label12);
this.Controls.Add(this.label11);
this.Controls.Add(this.label10);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.m_constructorComboBox);
this.Controls.Add(this.button1);
this.Controls.Add(this.m_alphap2TextBox);
this.Controls.Add(this.m_kp2TextBox);
this.Controls.Add(this.m_alpha2TextBox);
this.Controls.Add(this.m_k2TextBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.label4);
this.Name = "EllipticPanel";
this.Size = new System.Drawing.Size(764, 377);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolTip m_toolTip;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox m_k2TextBox;
private System.Windows.Forms.TextBox m_alpha2TextBox;
private System.Windows.Forms.TextBox m_kp2TextBox;
private System.Windows.Forms.TextBox m_alphap2TextBox;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ComboBox m_constructorComboBox;
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.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox m_KtextBox;
private System.Windows.Forms.TextBox m_EtextBox;
private System.Windows.Forms.TextBox m_DtextBox;
private System.Windows.Forms.TextBox m_KEtextBox;
private System.Windows.Forms.TextBox m_PItextBox;
private System.Windows.Forms.TextBox m_GtextBox;
private System.Windows.Forms.TextBox m_HtextBox;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.TextBox m_phiTextBox;
private System.Windows.Forms.TextBox m_EphiTextBox;
private System.Windows.Forms.TextBox m_DphiTextBox;
private System.Windows.Forms.TextBox m_FphiTextBox;
private System.Windows.Forms.TextBox m_PiphiTextBox;
private System.Windows.Forms.TextBox m_GphiTextBox;
private System.Windows.Forms.TextBox m_HphiTextBox;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
}
}
| |
using System.Diagnostics;
using System;
namespace System.Data.SQLite
{
public partial class Sqlite3
{
/***** This file contains automatically generated code ******
**
** The code in this file has been automatically generated by
**
** sqlite/tool/mkkeywordhash.c
**
** The code in this file implements a function that determines whether
** or not a given identifier is really an SQL keyword. The same thing
** might be implemented more directly using a hand-written hash table.
** But by using this automatically generated code, the size of the code
** is substantially reduced. This is important for embedded applications
** on platforms with limited memory.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
/* Hash score: 175 */
/* zText[] encodes 811 bytes of keywords in 541 bytes */
/* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
/* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
/* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
/* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
/* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
/* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
/* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
/* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
/* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
/* INITIALLY */
static string zText = new string(new char[540] {
'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G',
#if !SQLITE_OMIT_TRIGGER
'E',
#else
'\0',
#endif
'R',
#if !SQLITE_OMIT_FOREIGN_KEY
'E',
#else
'\0',
#endif
'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
});
static byte[] aHash = { //aHash[127]
72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
};
static byte[] aNext = { //aNext[121]
0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
35, 64, 0, 0,
};
static byte[] aLen = { //aLen[121]
7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
6, 4, 9, 3,
};
static int[] aOffset = { //aOffset[121]
0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
521, 527, 531, 536,
};
static byte[] aCode = { //aCode[121
TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
TK_ALL,
};
static int keywordCode(string z, int iOffset, int n)
{
int h, i;
if (n < 2)
return TK_ID;
h = ((sqlite3UpperToLower[z[iOffset + 0]]) * 4 ^//(charMap(z[iOffset+0]) * 4) ^
(sqlite3UpperToLower[z[iOffset + n - 1]] * 3) ^ //(charMap(z[iOffset+n - 1]) * 3) ^
n) % 127;
for (i = (aHash[h]) - 1; i >= 0; i = (aNext[i]) - 1)
{
if (aLen[i] == n && String.Compare(zText, aOffset[i], z, iOffset, n, StringComparison.InvariantCultureIgnoreCase) == 0)
{
testcase(i == 0); /* REINDEX */
testcase(i == 1); /* INDEXED */
testcase(i == 2); /* INDEX */
testcase(i == 3); /* DESC */
testcase(i == 4); /* ESCAPE */
testcase(i == 5); /* EACH */
testcase(i == 6); /* CHECK */
testcase(i == 7); /* KEY */
testcase(i == 8); /* BEFORE */
testcase(i == 9); /* FOREIGN */
testcase(i == 10); /* FOR */
testcase(i == 11); /* IGNORE */
testcase(i == 12); /* REGEXP */
testcase(i == 13); /* EXPLAIN */
testcase(i == 14); /* INSTEAD */
testcase(i == 15); /* ADD */
testcase(i == 16); /* DATABASE */
testcase(i == 17); /* AS */
testcase(i == 18); /* SELECT */
testcase(i == 19); /* TABLE */
testcase(i == 20); /* LEFT */
testcase(i == 21); /* THEN */
testcase(i == 22); /* END */
testcase(i == 23); /* DEFERRABLE */
testcase(i == 24); /* ELSE */
testcase(i == 25); /* EXCEPT */
testcase(i == 26); /* TRANSACTION */
testcase(i == 27); /* ACTION */
testcase(i == 28); /* ON */
testcase(i == 29); /* NATURAL */
testcase(i == 30); /* ALTER */
testcase(i == 31); /* RAISE */
testcase(i == 32); /* EXCLUSIVE */
testcase(i == 33); /* EXISTS */
testcase(i == 34); /* SAVEPOINT */
testcase(i == 35); /* INTERSECT */
testcase(i == 36); /* TRIGGER */
testcase(i == 37); /* REFERENCES */
testcase(i == 38); /* CONSTRAINT */
testcase(i == 39); /* INTO */
testcase(i == 40); /* OFFSET */
testcase(i == 41); /* OF */
testcase(i == 42); /* SET */
testcase(i == 43); /* TEMPORARY */
testcase(i == 44); /* TEMP */
testcase(i == 45); /* OR */
testcase(i == 46); /* UNIQUE */
testcase(i == 47); /* QUERY */
testcase(i == 48); /* ATTACH */
testcase(i == 49); /* HAVING */
testcase(i == 50); /* GROUP */
testcase(i == 51); /* UPDATE */
testcase(i == 52); /* BEGIN */
testcase(i == 53); /* INNER */
testcase(i == 54); /* RELEASE */
testcase(i == 55); /* BETWEEN */
testcase(i == 56); /* NOTNULL */
testcase(i == 57); /* NOT */
testcase(i == 58); /* NO */
testcase(i == 59); /* NULL */
testcase(i == 60); /* LIKE */
testcase(i == 61); /* CASCADE */
testcase(i == 62); /* ASC */
testcase(i == 63); /* DELETE */
testcase(i == 64); /* CASE */
testcase(i == 65); /* COLLATE */
testcase(i == 66); /* CREATE */
testcase(i == 67); /* CURRENT_DATE */
testcase(i == 68); /* DETACH */
testcase(i == 69); /* IMMEDIATE */
testcase(i == 70); /* JOIN */
testcase(i == 71); /* INSERT */
testcase(i == 72); /* MATCH */
testcase(i == 73); /* PLAN */
testcase(i == 74); /* ANALYZE */
testcase(i == 75); /* PRAGMA */
testcase(i == 76); /* ABORT */
testcase(i == 77); /* VALUES */
testcase(i == 78); /* VIRTUAL */
testcase(i == 79); /* LIMIT */
testcase(i == 80); /* WHEN */
testcase(i == 81); /* WHERE */
testcase(i == 82); /* RENAME */
testcase(i == 83); /* AFTER */
testcase(i == 84); /* REPLACE */
testcase(i == 85); /* AND */
testcase(i == 86); /* DEFAULT */
testcase(i == 87); /* AUTOINCREMENT */
testcase(i == 88); /* TO */
testcase(i == 89); /* IN */
testcase(i == 90); /* CAST */
testcase(i == 91); /* COLUMN */
testcase(i == 92); /* COMMIT */
testcase(i == 93); /* CONFLICT */
testcase(i == 94); /* CROSS */
testcase(i == 95); /* CURRENT_TIMESTAMP */
testcase(i == 96); /* CURRENT_TIME */
testcase(i == 97); /* PRIMARY */
testcase(i == 98); /* DEFERRED */
testcase(i == 99); /* DISTINCT */
testcase(i == 100); /* IS */
testcase(i == 101); /* DROP */
testcase(i == 102); /* FAIL */
testcase(i == 103); /* FROM */
testcase(i == 104); /* FULL */
testcase(i == 105); /* GLOB */
testcase(i == 106); /* BY */
testcase(i == 107); /* IF */
testcase(i == 108); /* ISNULL */
testcase(i == 109); /* ORDER */
testcase(i == 110); /* RESTRICT */
testcase(i == 111); /* OUTER */
testcase(i == 112); /* RIGHT */
testcase(i == 113); /* ROLLBACK */
testcase(i == 114); /* ROW */
testcase(i == 115); /* UNION */
testcase(i == 116); /* USING */
testcase(i == 117); /* VACUUM */
testcase(i == 118); /* VIEW */
testcase(i == 119); /* INITIALLY */
testcase(i == 120); /* ALL */
return aCode[i];
}
}
return TK_ID;
}
static int sqlite3KeywordCode(string z, int n)
{
return keywordCode(z, 0, n);
}
public const int SQLITE_N_KEYWORD = 121;//#define SQLITE_N_KEYWORD 121
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
public partial class Socket
{
partial void ValidateForMultiConnect(bool isMultiEndpoint)
{
// ValidateForMultiConnect is called before any {Begin}Connect{Async} call,
// regardless of whether it's targeting an endpoint with multiple addresses.
// If it is targeting such an endpoint, then any exposure of the socket's handle
// or configuration of the socket we haven't tracked would prevent us from
// replicating the socket's file descriptor appropriately. Similarly, if it's
// only targeting a single address, but it already experienced a failure in a
// previous connect call, then this is logically part of a multi endpoint connect,
// and the same logic applies. Either way, in such a situation we throw.
if (_handle.ExposedHandleOrUntrackedConfiguration && (isMultiEndpoint || _handle.LastConnectFailed))
{
ThrowMultiConnectNotSupported();
}
// If the socket was already used for a failed connect attempt, replace it
// with a fresh one, copying over all of the state we've tracked.
ReplaceHandleIfNecessaryAfterFailedConnect();
Debug.Assert(!_handle.LastConnectFailed);
}
internal void ReplaceHandleIfNecessaryAfterFailedConnect()
{
if (!_handle.LastConnectFailed)
{
return;
}
SocketError errorCode = ReplaceHandle();
if (errorCode != SocketError.Success)
{
throw new SocketException((int) errorCode);
}
_handle.LastConnectFailed = false;
}
internal SocketError ReplaceHandle()
{
// Copy out values from key options. The copied values should be kept in sync with the
// handling in SafeCloseSocket.TrackOption. Note that we copy these values out first, before
// we change _handle, so that we can use the helpers on Socket which internally access _handle.
// Then once _handle is switched to the new one, we can call the setters to propagate the retrieved
// values back out to the new underlying socket.
bool broadcast = false, dontFragment = false, noDelay = false;
int receiveSize = -1, receiveTimeout = -1, sendSize = -1, sendTimeout = -1;
short ttl = -1;
LingerOption linger = null;
if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) dontFragment = DontFragment;
if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) broadcast = EnableBroadcast;
if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) linger = LingerState;
if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) noDelay = NoDelay;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) receiveSize = ReceiveBufferSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) receiveTimeout = ReceiveTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendBufferSize)) sendSize = SendBufferSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendTimeout)) sendTimeout = SendTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.Ttl)) ttl = Ttl;
// Then replace the handle with a new one
SafeCloseSocket oldHandle = _handle;
SocketError errorCode = SocketPal.CreateSocket(_addressFamily, _socketType, _protocolType, out _handle);
oldHandle.TransferTrackedState(_handle);
oldHandle.Dispose();
if (errorCode != SocketError.Success)
{
return errorCode;
}
// And put back the copied settings. For DualMode, we use the value stored in the _handle
// rather than querying the socket itself, as on Unix stacks binding a dual-mode socket to
// an IPv6 address may cause the IPv6Only setting to revert to true.
if (_handle.IsTrackedOption(TrackedSocketOptions.DualMode)) DualMode = _handle.DualMode;
if (_handle.IsTrackedOption(TrackedSocketOptions.DontFragment)) DontFragment = dontFragment;
if (_handle.IsTrackedOption(TrackedSocketOptions.EnableBroadcast)) EnableBroadcast = broadcast;
if (_handle.IsTrackedOption(TrackedSocketOptions.LingerState)) LingerState = linger;
if (_handle.IsTrackedOption(TrackedSocketOptions.NoDelay)) NoDelay = noDelay;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveBufferSize)) ReceiveBufferSize = receiveSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.ReceiveTimeout)) ReceiveTimeout = receiveTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendBufferSize)) SendBufferSize = sendSize;
if (_handle.IsTrackedOption(TrackedSocketOptions.SendTimeout)) SendTimeout = sendTimeout;
if (_handle.IsTrackedOption(TrackedSocketOptions.Ttl)) Ttl = ttl;
return SocketError.Success;
}
private static void ThrowMultiConnectNotSupported()
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported);
}
private Socket GetOrCreateAcceptSocket(Socket acceptSocket, bool unused, string propertyName, out SafeCloseSocket handle)
{
// AcceptSocket is not supported on Unix.
if (acceptSocket != null)
{
throw new PlatformNotSupportedException();
}
handle = null;
return null;
}
private static void CheckTransmitFileOptions(TransmitFileOptions flags)
{
// Note, UseDefaultWorkerThread is the default and is == 0.
// Unfortunately there is no TransmitFileOptions.None.
if (flags != TransmitFileOptions.UseDefaultWorkerThread)
{
throw new PlatformNotSupportedException(SR.net_sockets_transmitfileoptions_notsupported);
}
}
private void SendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
CheckTransmitFileOptions(flags);
// Open the file, if any
// Open it before we send the preBuffer so that any exception happens first
FileStream fileStream = OpenFile(fileName);
SocketError errorCode = SocketError.Success;
using (fileStream)
{
// Send the preBuffer, if any
// This will throw on error
if (preBuffer != null && preBuffer.Length > 0)
{
Send(preBuffer);
}
// Send the file, if any
if (fileStream != null)
{
// This can throw ObjectDisposedException.
errorCode = SocketPal.SendFile(_handle, fileStream);
}
}
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
// Send the postBuffer, if any
// This will throw on error
if (postBuffer != null && postBuffer.Length > 0)
{
Send(postBuffer);
}
}
private async Task SendFileInternalAsync(FileStream fileStream, byte[] preBuffer, byte[] postBuffer)
{
SocketError errorCode = SocketError.Success;
using (fileStream)
{
// Send the preBuffer, if any
// This will throw on error
if (preBuffer != null && preBuffer.Length > 0)
{
// Using "this." makes the extension method kick in
await this.SendAsync(new ArraySegment<byte>(preBuffer), SocketFlags.None).ConfigureAwait(false);
}
// Send the file, if any
if (fileStream != null)
{
var tcs = new TaskCompletionSource<SocketError>();
errorCode = SocketPal.SendFileAsync(_handle, fileStream, (_, socketError) => tcs.SetResult(socketError));
if (errorCode == SocketError.IOPending)
{
errorCode = await tcs.Task.ConfigureAwait(false);
}
}
}
if (errorCode != SocketError.Success)
{
UpdateStatusAfterSocketErrorAndThrowException(errorCode);
}
// Send the postBuffer, if any
// This will throw on error
if (postBuffer != null && postBuffer.Length > 0)
{
// Using "this." makes the extension method kick in
await this.SendAsync(new ArraySegment<byte>(postBuffer), SocketFlags.None).ConfigureAwait(false);
}
}
private IAsyncResult BeginSendFileInternal(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
{
CheckTransmitFileOptions(flags);
// Open the file, if any
// Open it before we send the preBuffer so that any exception happens first
FileStream fileStream = OpenFile(fileName);
return TaskToApm.Begin(SendFileInternalAsync(fileStream, preBuffer, postBuffer), callback, state);
}
private void EndSendFileInternal(IAsyncResult asyncResult)
{
TaskToApm.End(asyncResult);
}
}
}
| |
namespace Volante.Impl
{
using System;
using System.Collections;
using System.Collections.Generic;
class TtreePage<K, V> : Persistent where V : class,IPersistent
{
const int maxItems = (Page.pageSize - ObjectHeader.Sizeof - 4 * 5) / 4;
const int minItems = maxItems - 2; // minimal number of items in internal node
TtreePage<K, V> left;
TtreePage<K, V> right;
int balance;
int nItems;
V[] item;
public override bool RecursiveLoading()
{
return false;
}
TtreePage() { }
internal TtreePage(V mbr)
{
nItems = 1;
item = new V[maxItems];
item[0] = mbr;
}
V loadItem(int i)
{
V mbr = item[i];
mbr.Load();
return mbr;
}
internal bool find(PersistentComparator<K, V> comparator, K minValue, BoundaryKind minBoundary, K maxValue, BoundaryKind maxBoundary, List<V> selection)
{
int l, r, m, n;
Load();
n = nItems;
if (minBoundary != BoundaryKind.None)
{
if (-comparator.CompareMemberWithKey(loadItem(0), minValue) >= (int)minBoundary)
{
if (-comparator.CompareMemberWithKey(loadItem(n - 1), minValue) >= (int)minBoundary)
{
if (right != null)
return right.find(comparator, minValue, minBoundary, maxValue, maxBoundary, selection);
return true;
}
for (l = 0, r = n; l < r; )
{
m = (l + r) >> 1;
if (-comparator.CompareMemberWithKey(loadItem(m), minValue) >= (int)minBoundary)
l = m + 1;
else
r = m;
}
while (r < n)
{
if (maxBoundary != BoundaryKind.None
&& comparator.CompareMemberWithKey(loadItem(r), maxValue) >= (int)maxBoundary)
return false;
selection.Add(loadItem(r));
r += 1;
}
if (right != null)
{
return right.find(comparator, minValue, minBoundary, maxValue, maxBoundary, selection);
}
return true;
}
}
if (left != null)
{
if (!left.find(comparator, minValue, minBoundary, maxValue, maxBoundary, selection))
return false;
}
for (l = 0; l < n; l++)
{
if (maxBoundary != BoundaryKind.None
&& comparator.CompareMemberWithKey(loadItem(l), maxValue) >= (int)maxBoundary)
{
return false;
}
selection.Add(loadItem(l));
}
if (right != null)
return right.find(comparator, minValue, minBoundary, maxValue, maxBoundary, selection);
return true;
}
internal bool contains(PersistentComparator<K, V> comparator, V mbr)
{
int l, r, m, n;
Load();
n = nItems;
if (comparator.CompareMembers(loadItem(0), mbr) < 0)
{
if (comparator.CompareMembers(loadItem(n - 1), mbr) < 0)
{
if (right != null)
return right.contains(comparator, mbr);
return false;
}
for (l = 0, r = n; l < r; )
{
m = (l + r) >> 1;
if (comparator.CompareMembers(loadItem(m), mbr) < 0)
l = m + 1;
else
r = m;
}
while (r < n)
{
if (mbr == loadItem(r))
return true;
if (comparator.CompareMembers(item[r], mbr) > 0)
return false;
r += 1;
}
if (right != null)
return right.contains(comparator, mbr);
return false;
}
if (left != null)
{
if (left.contains(comparator, mbr))
return true;
}
for (l = 0; l < n; l++)
{
if (mbr == loadItem(l))
return true;
if (comparator.CompareMembers(item[l], mbr) > 0)
return false;
}
if (right != null)
return right.contains(comparator, mbr);
return false;
}
internal const int OK = 0;
internal const int NOT_UNIQUE = 1;
internal const int NOT_FOUND = 2;
internal const int OVERFLOW = 3;
internal const int UNDERFLOW = 4;
internal int insert(PersistentComparator<K, V> comparator, V mbr, bool unique, ref TtreePage<K, V> pgRef)
{
TtreePage<K, V> pg, lp, rp;
V reinsertItem;
Load();
int n = nItems;
int diff = comparator.CompareMembers(mbr, loadItem(0));
if (diff <= 0)
{
if (unique && diff == 0)
return NOT_UNIQUE;
if ((left == null || diff == 0) && n != maxItems)
{
Modify();
//for (int i = n; i > 0; i--) item[i] = item[i-1];
Array.Copy(item, 0, item, 1, n);
item[0] = mbr;
nItems += 1;
return OK;
}
if (left == null)
{
Modify();
left = new TtreePage<K, V>(mbr);
}
else
{
pg = pgRef;
pgRef = left;
int result = left.insert(comparator, mbr, unique, ref pgRef);
if (result == NOT_UNIQUE)
return NOT_UNIQUE;
Modify();
left = pgRef;
pgRef = pg;
if (result == OK) return OK;
}
if (balance > 0)
{
balance = 0;
return OK;
}
else if (balance == 0)
{
balance = -1;
return OVERFLOW;
}
else
{
lp = this.left;
lp.Load();
lp.Modify();
if (lp.balance < 0)
{ // single LL turn
this.left = lp.right;
lp.right = this;
balance = 0;
lp.balance = 0;
pgRef = lp;
}
else
{ // double LR turn
rp = lp.right;
rp.Load();
rp.Modify();
lp.right = rp.left;
rp.left = lp;
this.left = rp.right;
rp.right = this;
balance = (rp.balance < 0) ? 1 : 0;
lp.balance = (rp.balance > 0) ? -1 : 0;
rp.balance = 0;
pgRef = rp;
}
return OK;
}
}
diff = comparator.CompareMembers(mbr, loadItem(n - 1));
if (diff >= 0)
{
if (unique && diff == 0)
return NOT_UNIQUE;
if ((right == null || diff == 0) && n != maxItems)
{
Modify();
item[n] = mbr;
nItems += 1;
return OK;
}
if (right == null)
{
Modify();
right = new TtreePage<K, V>(mbr);
}
else
{
pg = pgRef;
pgRef = right;
int result = right.insert(comparator, mbr, unique, ref pgRef);
if (result == NOT_UNIQUE)
return NOT_UNIQUE;
Modify();
right = pgRef;
pgRef = pg;
if (result == OK)
return OK;
}
if (balance < 0)
{
balance = 0;
return OK;
}
else if (balance == 0)
{
balance = 1;
return OVERFLOW;
}
else
{
rp = this.right;
rp.Load();
rp.Modify();
if (rp.balance > 0)
{ // single RR turn
this.right = rp.left;
rp.left = this;
balance = 0;
rp.balance = 0;
pgRef = rp;
}
else
{ // double RL turn
lp = rp.left;
lp.Load();
lp.Modify();
rp.left = lp.right;
lp.right = rp;
this.right = lp.left;
lp.left = this;
balance = (lp.balance > 0) ? -1 : 0;
rp.balance = (lp.balance < 0) ? 1 : 0;
lp.balance = 0;
pgRef = lp;
}
return OK;
}
}
int l = 1, r = n - 1;
while (l < r)
{
int i = (l + r) >> 1;
diff = comparator.CompareMembers(mbr, loadItem(i));
if (diff > 0)
{
l = i + 1;
}
else
{
r = i;
if (diff == 0)
{
if (unique)
return NOT_UNIQUE;
break;
}
}
}
// Insert before item[r]
Modify();
if (n != maxItems)
{
Array.Copy(item, r, item, r + 1, n - r);
//for (int i = n; i > r; i--) item[i] = item[i-1];
item[r] = mbr;
nItems += 1;
return OK;
}
else
{
if (balance >= 0)
{
reinsertItem = loadItem(0);
Array.Copy(item, 1, item, 0, r - 1);
//for (int i = 1; i < r; i++) item[i-1] = item[i];
item[r - 1] = mbr;
}
else
{
reinsertItem = loadItem(n - 1);
Array.Copy(item, r, item, r + 1, n - r - 1);
//for (int i = n-1; i > r; i--) item[i] = item[i-1];
item[r] = mbr;
}
return insert(comparator, reinsertItem, unique, ref pgRef);
}
}
internal int balanceLeftBranch(ref TtreePage<K, V> pgRef)
{
TtreePage<K, V> lp, rp;
if (balance < 0)
{
balance = 0;
return UNDERFLOW;
}
else if (balance == 0)
{
balance = 1;
return OK;
}
else
{
rp = this.right;
rp.Load();
rp.Modify();
if (rp.balance >= 0)
{ // single RR turn
this.right = rp.left;
rp.left = this;
if (rp.balance == 0)
{
this.balance = 1;
rp.balance = -1;
pgRef = rp;
return OK;
}
else
{
balance = 0;
rp.balance = 0;
pgRef = rp;
return UNDERFLOW;
}
}
else
{ // double RL turn
lp = rp.left;
lp.Load();
lp.Modify();
rp.left = lp.right;
lp.right = rp;
this.right = lp.left;
lp.left = this;
balance = lp.balance > 0 ? -1 : 0;
rp.balance = lp.balance < 0 ? 1 : 0;
lp.balance = 0;
pgRef = lp;
return UNDERFLOW;
}
}
}
internal int balanceRightBranch(ref TtreePage<K, V> pgRef)
{
TtreePage<K, V> lp, rp;
if (balance > 0)
{
balance = 0;
return UNDERFLOW;
}
else if (balance == 0)
{
balance = -1;
return OK;
}
else
{
lp = this.left;
lp.Load();
lp.Modify();
if (lp.balance <= 0)
{ // single LL turn
this.left = lp.right;
lp.right = this;
if (lp.balance == 0)
{
balance = -1;
lp.balance = 1;
pgRef = lp;
return OK;
}
else
{
balance = 0;
lp.balance = 0;
pgRef = lp;
return UNDERFLOW;
}
}
else
{ // double LR turn
rp = lp.right;
rp.Load();
rp.Modify();
lp.right = rp.left;
rp.left = lp;
this.left = rp.right;
rp.right = this;
balance = rp.balance < 0 ? 1 : 0;
lp.balance = rp.balance > 0 ? -1 : 0;
rp.balance = 0;
pgRef = rp;
return UNDERFLOW;
}
}
}
internal int remove(PersistentComparator<K, V> comparator, V mbr, ref TtreePage<K, V> pgRef)
{
TtreePage<K, V> pg, next, prev;
Load();
int n = nItems;
int diff = comparator.CompareMembers(mbr, loadItem(0));
if (diff <= 0)
{
if (left != null)
{
Modify();
pg = pgRef;
pgRef = left;
int h = left.remove(comparator, mbr, ref pgRef);
left = pgRef;
pgRef = pg;
if (h == UNDERFLOW)
return balanceLeftBranch(ref pgRef);
else if (h == OK)
return OK;
}
}
diff = comparator.CompareMembers(mbr, loadItem(n - 1));
if (diff <= 0)
{
for (int i = 0; i < n; i++)
{
if (item[i] == mbr)
{
if (n == 1)
{
if (right == null)
{
Deallocate();
pgRef = left;
return UNDERFLOW;
}
else if (left == null)
{
Deallocate();
pgRef = right;
return UNDERFLOW;
}
}
Modify();
if (n <= minItems)
{
if (left != null && balance <= 0)
{
prev = left;
prev.Load();
while (prev.right != null)
{
prev = prev.right;
prev.Load();
}
Array.Copy(item, 0, item, 1, i);
//while (--i >= 0)
//{
// item[i+1] = item[i];
//}
item[0] = prev.item[prev.nItems - 1];
pg = pgRef;
pgRef = left;
int h = left.remove(comparator, loadItem(0), ref pgRef);
left = pgRef;
pgRef = pg;
if (h == UNDERFLOW)
h = balanceLeftBranch(ref pgRef);
return h;
}
else if (right != null)
{
next = right;
next.Load();
while (next.left != null)
{
next = next.left;
next.Load();
}
Array.Copy(item, i + 1, item, i, n - i - 1);
//while (++i < n)
//{
// item[i-1] = item[i];
//}
item[n - 1] = next.item[0];
pg = pgRef;
pgRef = right;
int h = right.remove(comparator, loadItem(n - 1), ref pgRef);
right = pgRef;
pgRef = pg;
if (h == UNDERFLOW)
h = balanceRightBranch(ref pgRef);
return h;
}
}
Array.Copy(item, i + 1, item, i, n - i - 1);
//while (++i < n)
//{
// item[i-1] = item[i];
//}
item[n - 1] = null;
nItems -= 1;
return OK;
}
}
}
if (right != null)
{
Modify();
pg = pgRef;
pgRef = right;
int h = right.remove(comparator, mbr, ref pgRef);
right = pgRef;
pgRef = pg;
if (h == UNDERFLOW)
return balanceRightBranch(ref pgRef);
else
return h;
}
return NOT_FOUND;
}
internal int toArray(IPersistent[] arr, int index)
{
Load();
if (left != null)
index = left.toArray(arr, index);
for (int i = 0, n = nItems; i < n; i++)
{
arr[index++] = loadItem(i);
}
if (right != null)
index = right.toArray(arr, index);
return index;
}
internal void prune()
{
Load();
if (left != null)
left.prune();
if (right != null)
right.prune();
Deallocate();
}
}
}
| |
// 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.Immutable;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class DeclarationTests : ExpressionCompilerTestBase
{
[Fact]
public void Declarations()
{
var source =
@"class C
{
static object F;
static void M<T>(object x)
{
object y;
if (x == null)
{
object z;
}
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "int z = 1, F = 2;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0<T>").VerifyIL(
@"{
// Code size 85 (0x55)
.maxstack 4
.locals init (object V_0, //y
bool V_1,
object V_2,
System.Guid V_3)
IL_0000: ldtoken ""int""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""z""
IL_000f: ldloca.s V_3
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.3
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""z""
IL_0023: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)""
IL_0028: ldc.i4.1
IL_0029: stind.i4
IL_002a: ldtoken ""int""
IL_002f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0034: ldstr ""F""
IL_0039: ldloca.s V_3
IL_003b: initobj ""System.Guid""
IL_0041: ldloc.3
IL_0042: ldnull
IL_0043: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_0048: ldstr ""F""
IL_004d: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)""
IL_0052: ldc.i4.2
IL_0053: stind.i4
IL_0054: ret
}");
});
}
[Fact]
public void References()
{
var source =
@"class C
{
delegate void D();
internal object F;
static object G;
static void M<T>(object x)
{
object y;
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var aliases = ImmutableArray.Create(
VariableAlias("x", typeof(string)),
VariableAlias("y", typeof(int)),
VariableAlias("T", typeof(object)),
VariableAlias("D", "C"),
VariableAlias("F", typeof(int)));
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"(object)x ?? (object)y ?? (object)T ?? (object)F ?? ((C)D).F ?? C.G",
DkmEvaluationFlags.TreatAsExpression,
aliases,
out error,
testData);
Assert.Equal(testData.Methods.Count, 1);
testData.GetMethodData("<>x.<>m0<T>").VerifyIL(
@"{
// Code size 78 (0x4e)
.maxstack 2
.locals init (object V_0) //y
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_004d
IL_0004: pop
IL_0005: ldloc.0
IL_0006: dup
IL_0007: brtrue.s IL_004d
IL_0009: pop
IL_000a: ldstr ""T""
IL_000f: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0014: dup
IL_0015: brtrue.s IL_004d
IL_0017: pop
IL_0018: ldstr ""F""
IL_001d: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0022: unbox.any ""int""
IL_0027: box ""int""
IL_002c: dup
IL_002d: brtrue.s IL_004d
IL_002f: pop
IL_0030: ldstr ""D""
IL_0035: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_003a: castclass ""C""
IL_003f: ldfld ""object C.F""
IL_0044: dup
IL_0045: brtrue.s IL_004d
IL_0047: pop
IL_0048: ldsfld ""object C.G""
IL_004d: ret
}");
});
}
[Fact]
public void Address()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression(
"*(&c) = 'A'",
DkmEvaluationFlags.None,
ImmutableArray.Create(VariableAlias("c", typeof(char))),
out error,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 18 (0x12)
.maxstack 3
.locals init (char V_0)
IL_0000: ldstr ""c""
IL_0005: call ""char Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<char>(string)""
IL_000a: conv.u
IL_000b: ldc.i4.s 65
IL_000d: dup
IL_000e: stloc.0
IL_000f: stind.i2
IL_0010: ldloc.0
IL_0011: ret
}");
});
}
[Fact]
public void TreatAsExpression()
{
var source =
@"class C
{
static void M(object x)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
// Expression without ';' as statement.
var result = context.CompileExpression("3", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Null(error);
// Expression with ';' as statement.
result = context.CompileExpression("3;", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Null(error);
// Expression with format specifiers but without ';' as statement.
result = context.CompileExpression("string.Empty, nq", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Null(error);
AssertEx.SetEqual(result.FormatSpecifiers, new[] { "nq" });
// Expression with format specifiers with ';' as statement.
result = context.CompileExpression("string.Empty, nq;", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Equal(error, "error CS1073: Unexpected token ','");
Assert.Null(result);
// Assignment without ';' as statement.
result = context.CompileExpression("x = 2", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Null(error);
// Assignment with ';' as statement.
result = context.CompileExpression("x = 2;", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Null(error);
// Statement without ';' as statement.
result = context.CompileExpression("int o", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Equal(error, "error CS1525: Invalid expression term 'int'");
// Neither statement nor expression as statement.
result = context.CompileExpression("M(;", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Equal(error, "error CS1026: ) expected");
// Statement without ';' as expression.
result = context.CompileExpression("int o", DkmEvaluationFlags.TreatAsExpression, NoAliases, out error);
Assert.Equal(error, "error CS1525: Invalid expression term 'int'");
// Statement with ';' as expression.
result = context.CompileExpression("int o;", DkmEvaluationFlags.TreatAsExpression, NoAliases, out error);
Assert.Equal(error, "error CS1525: Invalid expression term 'int'");
// Neither statement nor expression as expression.
result = context.CompileExpression("M(;", DkmEvaluationFlags.TreatAsExpression, NoAliases, out error);
Assert.Equal(error, "error CS1026: ) expected");
});
}
[Fact]
public void BaseType()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"System.ValueType C = (int)$3;",
DkmEvaluationFlags.None,
ImmutableArray.Create(ObjectIdAlias(3, typeof(int))),
out error,
testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 62 (0x3e)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""System.ValueType""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""C""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""C""
IL_0023: call ""System.ValueType Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.ValueType>(string)""
IL_0028: ldstr ""$3""
IL_002d: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0032: unbox.any ""int""
IL_0037: box ""int""
IL_003c: stind.ref
IL_003d: ret
}");
});
}
[Fact]
public void Var()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "var x = 1;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 43 (0x2b)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""int""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""x""
IL_0023: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)""
IL_0028: ldc.i4.1
IL_0029: stind.i4
IL_002a: ret
}");
});
}
[WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")]
[Fact]
public void Dynamic()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "dynamic d = 1;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 58 (0x3a)
.maxstack 7
IL_0000: ldtoken ""object""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""d""
IL_000f: ldstr ""826d6ec1-dc4b-46af-be05-cd3f1a1fd4ac""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.1
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldc.i4.0
IL_0021: ldc.i4.1
IL_0022: stelem.i1
IL_0023: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_0028: ldstr ""d""
IL_002d: call ""dynamic Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<dynamic>(string)""
IL_0032: ldc.i4.1
IL_0033: box ""int""
IL_0038: stind.ref
IL_0039: ret
}");
});
}
[Fact]
public void BindingError_Initializer()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"object o = F();",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS0103: The name 'F' does not exist in the current context");
});
}
[Fact]
public void CannotInferType_NoInitializer()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"var y;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS0818: Implicitly-typed variables must be initialized");
});
}
[Fact]
public void CannotInferType_Null()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"var z = null;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS0815: Cannot assign <null> to an implicitly-typed variable");
});
}
[Fact]
public void InferredType_Void()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"var w = M();",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS0815: Cannot assign void to an implicitly-typed variable");
});
}
[Fact]
public void ReferenceInNextDeclaration()
{
var source =
@"class C
{
static void M<T>()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"T x = default(T), y = x;",
DkmEvaluationFlags.None,
NoAliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0<T>").VerifyIL(
@"{
// Code size 115 (0x73)
.maxstack 4
.locals init (System.Guid V_0,
T V_1)
IL_0000: ldtoken ""T""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""x""
IL_0023: call ""T Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<T>(string)""
IL_0028: ldloca.s V_1
IL_002a: initobj ""T""
IL_0030: ldloc.1
IL_0031: stobj ""T""
IL_0036: ldtoken ""T""
IL_003b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0040: ldstr ""y""
IL_0045: ldloca.s V_0
IL_0047: initobj ""System.Guid""
IL_004d: ldloc.0
IL_004e: ldnull
IL_004f: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_0054: ldstr ""y""
IL_0059: call ""T Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<T>(string)""
IL_005e: ldstr ""x""
IL_0063: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0068: unbox.any ""T""
IL_006d: stobj ""T""
IL_0072: ret
}");
});
}
[WorkItem(1094107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094107")]
[Fact]
public void ReferenceInSameDeclaration()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"object o = o ?? null;",
DkmEvaluationFlags.None,
NoAliases,
out error,
testData);
// The compiler reports "CS0165: Use of unassigned local variable 'o'"
// in flow analysis. But since flow analysis is skipped in the EE,
// compilation succeeds and references to the local in the initializer
// are treated as default(T). That matches the legacy EE.
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 57 (0x39)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""object""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""o""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""o""
IL_0023: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<object>(string)""
IL_0028: ldstr ""o""
IL_002d: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0032: dup
IL_0033: brtrue.s IL_0037
IL_0035: pop
IL_0036: ldnull
IL_0037: stind.ref
IL_0038: ret
}");
testData = new CompilationTestData();
context.CompileExpression(
"string s = s.Substring(0);",
DkmEvaluationFlags.None,
NoAliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 63 (0x3f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""string""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""s""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""s""
IL_0023: call ""string Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<string>(string)""
IL_0028: ldstr ""s""
IL_002d: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0032: castclass ""string""
IL_0037: ldc.i4.0
IL_0038: callvirt ""string string.Substring(int)""
IL_003d: stind.ref
IL_003e: ret
}");
});
}
[Fact]
public void ReferenceInPreviousDeclaration()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"object x = y, y;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS0841: Cannot use local variable 'y' before it is declared");
});
}
[WorkItem(1094104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094104")]
[Fact(Skip = "1094104")]
public void Conflict_Parameter()
{
var source =
@"class C
{
static void M(object x)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"var x = 4;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "...");
});
}
[WorkItem(1094104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094104")]
[Fact(Skip = "1094104")]
public void Conflict_Local()
{
var source =
@"class C
{
static void M()
{
object y;
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"object y = 5;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "...");
});
}
[WorkItem(1094104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094104")]
[Fact(Skip = "1094104")]
public void Conflict_OtherDeclaration()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
context.CompileExpression(
"object z = 6;",
DkmEvaluationFlags.None,
ImmutableArray.Create(VariableAlias("z", typeof(int))),
out error);
Assert.Equal(error, "...");
});
}
[Fact]
public void Arguments()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
// Local declaration arguments (error only).
string error;
context.CompileExpression(
"int a[3];",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS1525: Invalid expression term 'int'");
});
}
[Fact]
public void Keyword()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"object @class, @this = @class;",
DkmEvaluationFlags.None,
NoAliases,
out error,
testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 82 (0x52)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""object""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""class""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldtoken ""object""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: ldstr ""this""
IL_002d: ldloca.s V_0
IL_002f: initobj ""System.Guid""
IL_0035: ldloc.0
IL_0036: ldnull
IL_0037: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_003c: ldstr ""this""
IL_0041: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<object>(string)""
IL_0046: ldstr ""class""
IL_004b: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0050: stind.ref
IL_0051: ret
}");
});
}
[Fact]
public void Constant()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"const int x = 1;",
DkmEvaluationFlags.None,
NoAliases,
out error,
testData);
// Legacy EE reports "Invalid expression term 'const'".
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 43 (0x2b)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""int""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""x""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""x""
IL_0023: call ""int Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int>(string)""
IL_0028: ldc.i4.1
IL_0029: stind.i4
IL_002a: ret
}");
});
}
[Fact]
public void Generic()
{
var source =
@"class C
{
static void M<T>(T x)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"T y = x;",
DkmEvaluationFlags.None,
NoAliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0<T>").VerifyIL(
@"{
// Code size 47 (0x2f)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""T""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""y""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""y""
IL_0023: call ""T Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<T>(string)""
IL_0028: ldarg.0
IL_0029: stobj ""T""
IL_002e: ret
}");
});
}
/// <summary>
/// Should not allow names with '$' prefix.
/// </summary>
[WorkItem(1106819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1106819")]
[Fact]
public void NoPrefix()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
// $1
context.CompileExpression(
"var $1 = 1;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS1056: Unexpected character '$'");
// $exception
context.CompileExpression(
"var $exception = 2;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS1056: Unexpected character '$'");
// $ReturnValue
context.CompileExpression(
"var $ReturnValue = 3;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS1056: Unexpected character '$'");
// $x
context.CompileExpression(
"var $x = 4;",
DkmEvaluationFlags.None,
NoAliases,
out error);
Assert.Equal(error, "error CS1056: Unexpected character '$'");
});
}
/// <summary>
/// Local declarations inside a lambda should
/// not be considered pseudo-variables.
/// </summary>
[Fact]
public void Lambda()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"System.Action b = () => { object c = null; };",
DkmEvaluationFlags.None,
NoAliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 73 (0x49)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""System.Action""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""b""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""b""
IL_0023: call ""System.Action Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.Action>(string)""
IL_0028: ldsfld ""System.Action <>x.<>c.<>9__0_0""
IL_002d: dup
IL_002e: brtrue.s IL_0047
IL_0030: pop
IL_0031: ldsfld ""<>x.<>c <>x.<>c.<>9""
IL_0036: ldftn ""void <>x.<>c.<<>m0>b__0_0()""
IL_003c: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0041: dup
IL_0042: stsfld ""System.Action <>x.<>c.<>9__0_0""
IL_0047: stind.ref
IL_0048: ret
}");
});
}
[WorkItem(1094148, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094148")]
[Fact]
public void OtherStatements()
{
var source =
@"class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("while(false) ;", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Equal(error, "error CS8092: Expression or declaration statement expected.");
testData = new CompilationTestData();
context.CompileExpression("try { } catch (System.Exception) { }", DkmEvaluationFlags.None, NoAliases, out error);
Assert.Equal(error, "error CS8092: Expression or declaration statement expected.");
});
}
[WorkItem(3822, "https://github.com/dotnet/roslyn/issues/3822")]
[Fact]
public void GenericType_Identifier()
{
var source = @"
class C
{
static void M()
{
}
}
class Generic<T>
{
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName());
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "Generic<C> g = null;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 43 (0x2b)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Generic<C>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""g""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""g""
IL_0023: call ""Generic<C> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Generic<C>>(string)""
IL_0028: ldnull
IL_0029: stind.ref
IL_002a: ret
}");
});
}
[WorkItem(3822, "https://github.com/dotnet/roslyn/issues/3822")]
[Fact]
public void GenericType_Keyword()
{
var source = @"
class C
{
static void M()
{
}
}
class Generic<T>
{
}
";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "Generic<int> g = null;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 43 (0x2b)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""Generic<int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""g""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""g""
IL_0023: call ""Generic<int> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Generic<int>>(string)""
IL_0028: ldnull
IL_0029: stind.ref
IL_002a: ret
}");
});
}
[WorkItem(3822, "https://github.com/dotnet/roslyn/issues/3822")]
[Fact]
public void PointerType_Identifier()
{
var source = @"
class C
{
static void M()
{
}
}
struct S
{
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName());
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "S* s = null;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 44 (0x2c)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""S*""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""s""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""s""
IL_0023: call ""S* Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S*>(string)""
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stind.i
IL_002b: ret
}");
});
}
[WorkItem(3822, "https://github.com/dotnet/roslyn/issues/3822")]
[Fact]
public void PointerType_Keyword()
{
var source = @"
class C
{
static void M()
{
}
}
";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "int* p = null;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 44 (0x2c)
.maxstack 4
.locals init (System.Guid V_0)
IL_0000: ldtoken ""int*""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""p""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""p""
IL_0023: call ""int* Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int*>(string)""
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stind.i
IL_002b: ret
}");
});
}
[WorkItem(3822, "https://github.com/dotnet/roslyn/issues/3822")]
[Fact]
public void NullableType_Identifier()
{
var source = @"
class C
{
static void M()
{
}
}
struct S
{
}
";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "S? s = null;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 4
.locals init (System.Guid V_0,
S? V_1)
IL_0000: ldtoken ""S?""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""s""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""s""
IL_0023: call ""S? Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<S?>(string)""
IL_0028: ldloca.s V_1
IL_002a: initobj ""S?""
IL_0030: ldloc.1
IL_0031: stobj ""S?""
IL_0036: ret
}");
});
}
[WorkItem(3822, "https://github.com/dotnet/roslyn/issues/3822")]
[Fact]
public void NullableType_Keyword()
{
var source = @"
class C
{
static void M()
{
}
}
";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: GetUniqueName());
WithRuntimeInstance(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
DkmClrCompilationResultFlags flags;
CompilationTestData testData;
CompileDeclaration(context, "int? n = null;", out flags, out testData);
Assert.Equal(flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 4
.locals init (System.Guid V_0,
int? V_1)
IL_0000: ldtoken ""int?""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""n""
IL_000f: ldloca.s V_0
IL_0011: initobj ""System.Guid""
IL_0017: ldloc.0
IL_0018: ldnull
IL_0019: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_001e: ldstr ""n""
IL_0023: call ""int? Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<int?>(string)""
IL_0028: ldloca.s V_1
IL_002a: initobj ""int?""
IL_0030: ldloc.1
IL_0031: stobj ""int?""
IL_0036: ret
}");
});
}
private static void CompileDeclaration(EvaluationContext context, string declaration, out DkmClrCompilationResultFlags flags, out CompilationTestData testData)
{
testData = new CompilationTestData();
ResultProperties resultProperties;
string error;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
declaration,
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
flags = resultProperties.Flags;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
namespace Orleans.Messaging
{
internal enum SocketDirection
{
SiloToSilo,
ClientToGateway,
GatewayToClient
}
internal abstract class OutgoingMessageSender : AsynchQueueAgent<Message>
{
internal OutgoingMessageSender(string nameSuffix, IMessagingConfiguration config)
: base(nameSuffix, config)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void Process(Message msg)
{
if (Log.IsVerbose2) Log.Verbose2("Got a {0} message to send: {1}", msg.Direction, msg);
bool continueSend = PrepareMessageForSend(msg);
if (!continueSend) return;
Socket sock;
string error;
SiloAddress targetSilo;
continueSend = GetSendingSocket(msg, out sock, out targetSilo, out error);
if (!continueSend)
{
OnGetSendingSocketFailure(msg, error);
return;
}
List<ArraySegment<byte>> data;
int headerLength = 0;
try
{
data = msg.Serialize(out headerLength);
}
catch (Exception exc)
{
OnMessageSerializationFailure(msg, exc);
return;
}
int length = data.Sum(x => x.Count);
int bytesSent = 0;
bool exceptionSending = false;
bool countMismatchSending = false;
string sendErrorStr = null;
try
{
bytesSent = sock.Send(data);
if (bytesSent != length)
{
// The complete message wasn't sent, even though no error was reported; treat this as an error
countMismatchSending = true;
sendErrorStr = String.Format("Byte count mismatch on sending to {0}: sent {1}, expected {2}", targetSilo, bytesSent, length);
Log.Warn(ErrorCode.Messaging_CountMismatchSending, sendErrorStr);
}
}
catch (Exception exc)
{
exceptionSending = true;
if (!(exc is ObjectDisposedException))
{
sendErrorStr = String.Format("Exception sending message to {0}. Message: {1}. {2}", targetSilo, msg, exc);
Log.Warn(ErrorCode.Messaging_ExceptionSending, sendErrorStr, exc);
}
}
MessagingStatisticsGroup.OnMessageSend(msg.SendingSilo, targetSilo, msg.Direction, bytesSent, headerLength, GetSocketDirection());
bool sendError = exceptionSending || countMismatchSending;
if (sendError)
OnSendFailure(sock, targetSilo);
ProcessMessageAfterSend(msg, sendError, sendErrorStr);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void ProcessBatch(List<Message> msgs)
{
if (Log.IsVerbose2) Log.Verbose2("Got {0} messages to send.", msgs.Count);
for (int i = 0; i < msgs.Count; )
{
bool sendThisMessage = PrepareMessageForSend(msgs[i]);
if (sendThisMessage)
i++;
else
msgs.RemoveAt(i); // don't advance i
}
if (msgs.Count <= 0) return;
Socket sock;
string error;
SiloAddress targetSilo;
bool continueSend = GetSendingSocket(msgs[0], out sock, out targetSilo, out error);
if (!continueSend)
{
foreach (Message msg in msgs)
OnGetSendingSocketFailure(msg, error);
return;
}
List<ArraySegment<byte>> data;
int headerLength = 0;
continueSend = SerializeMessages(msgs, out data, out headerLength, OnMessageSerializationFailure);
if (!continueSend) return;
int length = data.Sum(x => x.Count);
int bytesSent = 0;
bool exceptionSending = false;
bool countMismatchSending = false;
string sendErrorStr = null;
try
{
bytesSent = sock.Send(data);
if (bytesSent != length)
{
// The complete message wasn't sent, even though no error was reported; treat this as an error
countMismatchSending = true;
sendErrorStr = String.Format("Byte count mismatch on sending to {0}: sent {1}, expected {2}", targetSilo, bytesSent, length);
Log.Warn(ErrorCode.Messaging_CountMismatchSending, sendErrorStr);
}
}
catch (Exception exc)
{
exceptionSending = true;
if (!(exc is ObjectDisposedException))
{
sendErrorStr = String.Format("Exception sending message to {0}. {1}", targetSilo, TraceLogger.PrintException(exc));
Log.Warn(ErrorCode.Messaging_ExceptionSending, sendErrorStr, exc);
}
}
MessagingStatisticsGroup.OnMessageBatchSend(msgs[0].SendingSilo, targetSilo, msgs[0].Direction, bytesSent, headerLength, GetSocketDirection(), msgs.Count);
bool sendError = exceptionSending || countMismatchSending;
if (sendError)
OnSendFailure(sock, targetSilo);
foreach (Message msg in msgs)
ProcessMessageAfterSend(msg, sendError, sendErrorStr);
}
public static bool SerializeMessages(List<Message> msgs, out List<ArraySegment<byte>> data, out int headerLengthOut, Action<Message, Exception> msgSerializationFailureHandler)
{
int numberOfValidMessages = 0;
var lengths = new List<ArraySegment<byte>>();
var bodies = new List<ArraySegment<byte>>();
data = null;
headerLengthOut = 0;
int totalHeadersLen = 0;
foreach(var message in msgs)
{
try
{
int headerLength;
int bodyLength;
List<ArraySegment<byte>> body = message.SerializeForBatching(out headerLength, out bodyLength);
var headerLen = new ArraySegment<byte>(BitConverter.GetBytes(headerLength));
var bodyLen = new ArraySegment<byte>(BitConverter.GetBytes(bodyLength));
bodies.AddRange(body);
lengths.Add(headerLen);
lengths.Add(bodyLen);
numberOfValidMessages++;
totalHeadersLen += headerLength;
}
catch (Exception exc)
{
if (msgSerializationFailureHandler!=null)
msgSerializationFailureHandler(message, exc);
else
throw;
}
}
// at least 1 message was successfully serialized
if (bodies.Count <= 0) return false;
data = new List<ArraySegment<byte>> {new ArraySegment<byte>(BitConverter.GetBytes(numberOfValidMessages))};
data.AddRange(lengths);
data.AddRange(bodies);
headerLengthOut = totalHeadersLen;
return true;
// no message serialized
}
protected abstract SocketDirection GetSocketDirection();
protected abstract bool PrepareMessageForSend(Message msg);
protected abstract bool GetSendingSocket(Message msg, out Socket socket, out SiloAddress targetSilo, out string error);
protected abstract void OnGetSendingSocketFailure(Message msg, string error);
protected abstract void OnMessageSerializationFailure(Message msg, Exception exc);
protected abstract void OnSendFailure(Socket socket, SiloAddress targetSilo);
protected abstract void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr);
protected abstract void FailMessage(Message msg, string reason);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HTLib2.Bioinfo
{
public partial class Tinker
{
public partial class Selftest
{
public static readonly string[] selftest_xyz = new string[]
{
" 186 GNOMES, ROCK MONSTERS AND CHILI SAUCE",
" 1 NH3 -11.020000 -12.540000 -24.210000 65 2 5 6 7",
" 2 CT1 -12.460000 -12.650000 -24.060000 24 1 3 8 9",
" 3 C -12.800000 -14.020000 -23.500000 20 2 4 25",
" 4 O -12.120000 -15.000000 -23.800000 74 3",
" 5 HC -10.790000 -11.640000 -24.580000 6 1",
" 6 HC -10.580000 -12.660000 -23.320000 6 1",
" 7 HC -10.700000 -13.250000 -24.840000 6 1",
" 8 HB -12.740000 -11.930000 -23.430000 5 2",
" 9 CT2 -13.150000 -12.430000 -25.410000 26 2 10 14 15",
" 10 CT2 -14.610000 -12.030000 -25.280000 26 9 11 16 17",
" 11 CT2 -15.320000 -12.030000 -26.620000 26 10 12 18 19",
" 12 CT2 -16.820000 -12.190000 -26.420000 58 11 13 20 21",
" 13 NH3 -17.100000 -13.270000 -25.420000 65 12 22 23 24",
" 14 HA -13.100000 -13.280000 -25.940000 1 9",
" 15 HA -12.670000 -11.710000 -25.910000 1 9",
" 16 HA -14.650000 -11.110000 -24.890000 1 10",
" 17 HA -15.070000 -12.680000 -24.670000 1 10",
" 18 HA -14.970000 -12.790000 -27.180000 1 11",
" 19 HA -15.140000 -11.160000 -27.090000 1 11",
" 20 HA -17.250000 -12.430000 -27.280000 17 12",
" 21 HA -17.200000 -11.330000 -26.080000 17 12",
" 22 HC -18.090000 -13.360000 -25.290000 6 13",
" 23 HC -16.730000 -14.140000 -25.750000 6 13",
" 24 HC -16.680000 -13.040000 -24.540000 6 13",
" 25 NH1 -13.830000 -14.080000 -22.660000 63 3 26 29",
" 26 CT1 -14.300000 -15.350000 -22.110000 23 25 27 30 31",
" 27 C -15.270000 -16.040000 -23.050000 20 26 28 44",
" 28 O -16.370000 -15.530000 -23.300000 74 27",
" 29 H -14.300000 -13.240000 -22.400000 3 25",
" 30 HB -13.470000 -15.910000 -22.010000 4 26",
" 31 CT2 -14.970000 -15.140000 -20.760000 26 26 32 35 36",
" 32 CT1 -14.080000 -14.610000 -19.640000 25 31 33 34 37",
" 33 CT3 -14.870000 -14.540000 -18.350000 27 32 38 39 40",
" 34 CT3 -12.870000 -15.500000 -19.480000 27 32 41 42 43",
" 35 HA -15.350000 -16.010000 -20.470000 1 31",
" 36 HA -15.720000 -14.480000 -20.890000 1 31",
" 37 HA -13.760000 -13.690000 -19.860000 1 32",
" 38 HA -14.290000 -14.200000 -17.610000 1 33",
" 39 HA -15.650000 -13.930000 -18.470000 1 33",
" 40 HA -15.200000 -15.460000 -18.110000 1 33",
" 41 HA -12.290000 -15.150000 -18.750000 1 34",
" 42 HA -13.170000 -16.430000 -19.260000 1 34",
" 43 HA -12.360000 -15.520000 -20.340000 1 34",
" 44 NH1 -14.870000 -17.180000 -23.570000 63 27 45 48",
" 45 CT1 -15.720000 -17.950000 -24.470000 23 44 46 49 50",
" 46 C -16.190000 -19.230000 -23.800000 20 45 47 66",
" 47 O -15.670000 -19.640000 -22.750000 74 46",
" 48 H -13.960000 -17.530000 -23.350000 3 44",
" 49 HB -16.500000 -17.360000 -24.670000 4 45",
" 50 CT2 -14.960000 -18.300000 -25.740000 26 45 51 55 56",
" 51 CT2 -14.450000 -17.110000 -26.500000 26 50 52 57 58",
" 52 CT2 -15.580000 -16.310000 -27.120000 26 51 53 59 60",
" 53 CT2 -16.200000 -17.050000 -28.290000 58 52 54 61 62",
" 54 NH3 -17.080000 -16.150000 -29.090000 65 53 63 64 65",
" 55 HA -15.560000 -18.820000 -26.340000 1 50",
" 56 HA -14.170000 -18.870000 -25.490000 1 50",
" 57 HA -13.840000 -17.420000 -27.230000 1 51",
" 58 HA -13.940000 -16.520000 -25.880000 1 51",
" 59 HA -15.220000 -15.440000 -27.440000 1 52",
" 60 HA -16.280000 -16.150000 -26.430000 1 52",
" 61 HA -16.750000 -17.810000 -27.940000 17 53",
" 62 HA -15.470000 -17.410000 -28.880000 17 53",
" 63 HC -17.470000 -16.670000 -29.850000 6 54",
" 64 HC -17.810000 -15.800000 -28.510000 6 54",
" 65 HC -16.540000 -15.390000 -29.450000 6 54",
" 66 NH1 -17.160000 -19.890000 -24.400000 63 46 67 70",
" 67 CT1 -17.630000 -21.160000 -23.890000 23 66 68 71 72",
" 68 C -17.490000 -22.240000 -24.950000 20 67 69 82",
" 69 O -17.800000 -22.000000 -26.120000 74 68",
" 70 H -17.570000 -19.510000 -25.230000 3 66",
" 71 HB -17.050000 -21.350000 -23.100000 4 67",
" 72 CT1 -19.110000 -21.060000 -23.450000 25 67 73 74 75",
" 73 CT3 -19.650000 -22.430000 -23.050000 27 72 76 77 78",
" 74 CT3 -19.250000 -20.050000 -22.320000 27 72 79 80 81",
" 75 HA -19.660000 -20.730000 -24.220000 1 72",
" 76 HA -20.610000 -22.340000 -22.770000 1 73",
" 77 HA -19.590000 -23.050000 -23.830000 1 73",
" 78 HA -19.110000 -22.800000 -22.290000 1 73",
" 79 HA -20.210000 -19.990000 -22.040000 1 74",
" 80 HA -18.690000 -20.350000 -21.540000 1 74",
" 81 HA -18.940000 -19.150000 -22.630000 1 74",
" 82 NH1 -17.020000 -23.410000 -24.550000 63 68 83 86",
" 83 CT1 -17.030000 -24.600000 -25.390000 23 82 84 87 88",
" 84 C -17.720000 -25.690000 -24.600000 20 83 85 101",
" 85 O -17.300000 -26.000000 -23.480000 74 84",
" 86 H -16.650000 -23.480000 -23.620000 3 82",
" 87 HB -17.520000 -24.380000 -26.230000 4 83",
" 88 CT2 -15.600000 -25.010000 -25.770000 26 83 89 92 93",
" 89 CT1 -15.430000 -26.200000 -26.720000 25 88 90 91 94",
" 90 CT3 -16.080000 -25.900000 -28.050000 27 89 95 96 97",
" 91 CT3 -13.960000 -26.540000 -26.920000 27 89 98 99 100",
" 92 HA -15.120000 -25.230000 -24.920000 1 88",
" 93 HA -15.170000 -24.220000 -26.200000 1 88",
" 94 HA -15.880000 -27.000000 -26.310000 1 89",
" 95 HA -15.970000 -26.680000 -28.660000 1 90",
" 96 HA -17.060000 -25.730000 -27.910000 1 90",
" 97 HA -15.660000 -25.090000 -28.460000 1 90",
" 98 HA -13.870000 -27.320000 -27.540000 1 91",
" 99 HA -13.480000 -25.750000 -27.310000 1 91",
" 100 HA -13.540000 -26.770000 -26.030000 1 91",
" 101 NH1 -18.780000 -26.270000 -25.150000 63 84 102 105",
" 102 CT2 -19.560000 -27.220000 -24.380000 28 101 103 106 107",
" 103 C -20.190000 -28.320000 -25.190000 20 102 104 108",
" 104 O -20.040000 -28.390000 -26.420000 74 103",
" 105 H -19.040000 -26.040000 -26.080000 3 101",
" 106 HB -20.280000 -26.700000 -23.920000 4 102",
" 107 HB -18.950000 -27.620000 -23.700000 4 102",
" 108 NH1 -20.910000 -29.190000 -24.490000 63 103 109 112",
" 109 CT1 -21.540000 -30.350000 -25.090000 23 108 110 113 114",
" 110 C -23.010000 -30.370000 -24.730000 20 109 111 120",
" 111 O -23.410000 -29.810000 -23.710000 74 110",
" 112 H -21.020000 -29.030000 -23.510000 3 108",
" 113 HB -21.420000 -30.250000 -26.070000 4 109",
" 114 CT2 -20.890000 -31.630000 -24.580000 54 109 115 118 119",
" 115 CC -19.440000 -31.740000 -24.980000 55 114 116 117",
" 116 OC -19.200000 -31.950000 -26.180000 78 115",
" 117 OC -18.550000 -31.600000 -24.110000 78 115",
" 118 HA -21.380000 -32.420000 -24.950000 1 114",
" 119 HA -20.940000 -31.650000 -23.580000 1 114",
" 120 NH1 -23.810000 -31.040000 -25.560000 63 110 121 124",
" 121 CT1 -25.230000 -31.210000 -25.290000 23 120 122 125 126",
" 122 C -25.490000 -32.630000 -24.840000 20 121 123 136",
" 123 O -25.040000 -33.580000 -25.470000 74 122",
" 124 H -23.420000 -31.430000 -26.390000 3 120",
" 125 HB -25.430000 -30.550000 -24.570000 4 121",
" 126 CT1 -26.080000 -30.920000 -26.540000 25 121 127 128 129",
" 127 CT3 -27.550000 -31.030000 -26.210000 27 126 130 131 132",
" 128 CT3 -25.770000 -29.550000 -27.090000 27 126 133 134 135",
" 129 HA -25.860000 -31.600000 -27.240000 1 126",
" 130 HA -28.090000 -30.850000 -27.030000 1 127",
" 131 HA -27.750000 -31.960000 -25.880000 1 127",
" 132 HA -27.790000 -30.370000 -25.500000 1 127",
" 133 HA -26.330000 -29.390000 -27.900000 1 128",
" 134 HA -25.970000 -28.860000 -26.400000 1 128",
" 135 HA -24.800000 -29.500000 -27.340000 1 128",
" 136 NH1 -26.230000 -32.780000 -23.750000 63 122 137 140",
" 137 CT1 -26.610000 -34.110000 -23.280000 23 136 138 141 142",
" 138 C -28.100000 -34.200000 -23.000000 20 137 139 155",
" 139 O -28.780000 -33.180000 -22.920000 74 138",
" 140 H -26.530000 -31.970000 -23.240000 3 136",
" 141 HB -26.370000 -34.700000 -24.060000 4 137",
" 142 CT1 -25.840000 -34.540000 -22.010000 25 137 143 144 146",
" 143 CT2 -26.220000 -33.670000 -20.810000 26 142 145 147 148",
" 144 CT3 -24.340000 -34.460000 -22.250000 27 142 149 150 151",
" 145 CT3 -25.640000 -34.160000 -19.480000 27 143 152 153 154",
" 146 HA -26.090000 -35.490000 -21.800000 1 142",
" 147 HA -25.890000 -32.740000 -20.980000 1 143",
" 148 HA -27.220000 -33.660000 -20.730000 1 143",
" 149 HA -23.860000 -34.740000 -21.420000 1 144",
" 150 HA -24.090000 -35.070000 -23.000000 1 144",
" 151 HA -24.090000 -33.520000 -22.490000 1 144",
" 152 HA -25.920000 -33.550000 -18.750000 1 145",
" 153 HA -25.970000 -35.080000 -19.290000 1 145",
" 154 HA -24.640000 -34.170000 -19.540000 1 145",
" 155 NH1 -28.600000 -35.420000 -22.870000 63 138 156 159",
" 156 CT1 -29.980000 -35.660000 -22.500000 23 155 157 160 161",
" 157 C -29.990000 -36.120000 -21.060000 20 156 158 170",
" 158 O -29.300000 -37.080000 -20.700000 74 157",
" 159 H -28.000000 -36.210000 -23.030000 3 155",
" 160 HB -30.490000 -34.810000 -22.630000 4 156",
" 161 CT2 -30.570000 -36.760000 -23.390000 26 156 162 166 167",
" 162 CT2 -31.960000 -37.220000 -23.000000 54 161 163 168 169",
" 163 CC -33.030000 -36.230000 -23.390000 55 162 164 165",
" 164 OC -32.730000 -35.310000 -24.180000 78 163",
" 165 OC -34.180000 -36.370000 -22.920000 78 163",
" 166 HA -29.960000 -37.550000 -23.350000 1 161",
" 167 HA -30.610000 -36.420000 -24.330000 1 161",
" 168 HA -31.990000 -37.340000 -22.000000 1 162",
" 169 HA -32.150000 -38.090000 -23.440000 1 162",
" 170 NH1 -30.740000 -35.410000 -20.230000 63 157 171 174",
" 171 CT1 -30.820000 -35.750000 -18.810000 23 170 172 175 176",
" 172 CC -32.250000 -36.040000 -18.390000 22 171 173 186",
" 173 OC -33.200000 -35.730000 -19.120000 79 172",
" 174 H -31.260000 -34.630000 -20.580000 3 170",
" 175 HB -30.250000 -36.560000 -18.730000 4 171",
" 176 CT1 -30.280000 -34.620000 -17.950000 25 171 177 178 179",
" 177 CT3 -28.800000 -34.400000 -18.210000 27 176 180 181 182",
" 178 CT3 -31.080000 -33.360000 -18.190000 27 176 183 184 185",
" 179 HA -30.380000 -34.850000 -16.980000 1 176",
" 180 HA -28.460000 -33.660000 -17.640000 1 177",
" 181 HA -28.300000 -35.240000 -18.000000 1 177",
" 182 HA -28.670000 -34.170000 -19.170000 1 177",
" 183 HA -30.720000 -32.620000 -17.620000 1 178",
" 184 HA -31.000000 -33.100000 -19.160000 1 178",
" 185 HA -32.040000 -33.520000 -17.970000 1 178",
" 186 OC -32.460000 -36.590000 -17.310000 79 172",
};
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Content.Server.Atmos.EntitySystems;
using Content.Server.Hands.Components;
using Content.Server.UserInterface;
using Content.Shared.Atmos;
using Content.Shared.Atmos.Components;
using Content.Shared.Interaction;
using Content.Shared.Popups;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Map;
using Robust.Shared.ViewVariables;
namespace Content.Server.Atmos.Components
{
[RegisterComponent]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(SharedGasAnalyzerComponent))]
public sealed class GasAnalyzerComponent : SharedGasAnalyzerComponent, IAfterInteract, IDropped, IActivate
{
[Dependency] private readonly IEntityManager _entities = default!;
private GasAnalyzerDanger _pressureDanger;
private float _timeSinceSync;
private const float TimeBetweenSyncs = 2f;
private bool _checkPlayer = false; // Check at the player pos or at some other tile?
private EntityCoordinates? _position; // The tile that we scanned
private AppearanceComponent? _appearance;
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(GasAnalyzerUiKey.Key);
protected override void Initialize()
{
base.Initialize();
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += UserInterfaceOnReceiveMessage;
UserInterface.OnClosed += UserInterfaceOnClose;
}
_entities.TryGetComponent(Owner, out _appearance);
}
public override ComponentState GetComponentState()
{
return new GasAnalyzerComponentState(_pressureDanger);
}
/// <summary>
/// Call this from other components to open the gas analyzer UI.
/// Uses the player position.
/// </summary>
/// <param name="session">The session to open the ui for</param>
public void OpenInterface(IPlayerSession session)
{
_checkPlayer = true;
_position = null;
UserInterface?.Open(session);
UpdateUserInterface();
UpdateAppearance(true);
Resync();
}
/// <summary>
/// Call this from other components to open the gas analyzer UI.
/// Uses a given position.
/// </summary>
/// <param name="session">The session to open the ui for</param>
/// <param name="pos">The position to analyze the gas</param>
public void OpenInterface(IPlayerSession session, EntityCoordinates pos)
{
_checkPlayer = false;
_position = pos;
UserInterface?.Open(session);
UpdateUserInterface();
UpdateAppearance(true);
Resync();
}
public void ToggleInterface(IPlayerSession session)
{
if (UserInterface == null)
return;
if (UserInterface.SessionHasOpen(session))
CloseInterface(session);
else
OpenInterface(session);
}
public void CloseInterface(IPlayerSession session)
{
_position = null;
UserInterface?.Close(session);
// Our OnClose will do the appearance stuff
Resync();
}
private void UserInterfaceOnClose(IPlayerSession obj)
{
UpdateAppearance(false);
}
private void UpdateAppearance(bool open)
{
_appearance?.SetData(GasAnalyzerVisuals.VisualState,
open ? GasAnalyzerVisualState.Working : GasAnalyzerVisualState.Off);
}
public void Update(float frameTime)
{
_timeSinceSync += frameTime;
if (_timeSinceSync > TimeBetweenSyncs)
{
Resync();
UpdateUserInterface();
}
}
private void Resync()
{
// Already get the pressure before Dirty(), because we can't get the EntitySystem in that thread or smth
var pressure = 0f;
var tile = EntitySystem.Get<AtmosphereSystem>().GetTileMixture(_entities.GetComponent<TransformComponent>(Owner).Coordinates);
if (tile != null)
{
pressure = tile.Pressure;
}
if (pressure >= Atmospherics.HazardHighPressure || pressure <= Atmospherics.HazardLowPressure)
{
_pressureDanger = GasAnalyzerDanger.Hazard;
}
else if (pressure >= Atmospherics.WarningHighPressure || pressure <= Atmospherics.WarningLowPressure)
{
_pressureDanger = GasAnalyzerDanger.Warning;
}
else
{
_pressureDanger = GasAnalyzerDanger.Nominal;
}
Dirty();
_timeSinceSync = 0f;
}
private void UpdateUserInterface()
{
if (UserInterface == null)
{
return;
}
string? error = null;
// Check if the player is still holding the gas analyzer => if not, don't update
foreach (var session in UserInterface.SubscribedSessions)
{
if (session.AttachedEntity is not {Valid: true} playerEntity)
return;
if (!_entities.TryGetComponent(playerEntity, out HandsComponent? handsComponent))
return;
if (handsComponent?.GetActiveHandItem?.Owner is not {Valid: true} activeHandEntity ||
!_entities.TryGetComponent(activeHandEntity, out GasAnalyzerComponent? gasAnalyzer))
{
return;
}
}
var pos = _entities.GetComponent<TransformComponent>(Owner).Coordinates;
if (!_checkPlayer && _position.HasValue)
{
// Check if position is out of range => don't update
if (!_position.Value.InRange(_entities, pos, SharedInteractionSystem.InteractionRange))
return;
pos = _position.Value;
}
var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
var tile = atmosphereSystem.GetTileMixture(pos);
if (tile == null)
{
error = "No Atmosphere!";
UserInterface.SetState(
new GasAnalyzerBoundUserInterfaceState(
0,
0,
null,
error));
return;
}
var gases = new List<GasEntry>();
for (var i = 0; i < Atmospherics.TotalNumberOfGases; i++)
{
var gas = atmosphereSystem.GetGas(i);
if (tile.Moles[i] <= Atmospherics.GasMinMoles) continue;
gases.Add(new GasEntry(gas.Name, tile.Moles[i], gas.Color));
}
UserInterface.SetState(
new GasAnalyzerBoundUserInterfaceState(
tile.Pressure,
tile.Temperature,
gases.ToArray(),
error));
}
private void UserInterfaceOnReceiveMessage(ServerBoundUserInterfaceMessage serverMsg)
{
var message = serverMsg.Message;
switch (message)
{
case GasAnalyzerRefreshMessage msg:
if (serverMsg.Session.AttachedEntity is not {Valid: true} player)
{
return;
}
if (!_entities.TryGetComponent(player, out HandsComponent? handsComponent))
{
Owner.PopupMessage(player, Loc.GetString("gas-analyzer-component-player-has-no-hands-message"));
return;
}
if (handsComponent.GetActiveHandItem?.Owner is not {Valid: true} activeHandEntity ||
!_entities.TryGetComponent(activeHandEntity, out GasAnalyzerComponent? gasAnalyzer))
{
serverMsg.Session.AttachedEntity.Value.PopupMessage(Loc.GetString("gas-analyzer-component-need-gas-analyzer-in-hand-message"));
return;
}
UpdateUserInterface();
Resync();
break;
}
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (!eventArgs.CanReach)
{
eventArgs.User.PopupMessage(Loc.GetString("gas-analyzer-component-player-cannot-reach-message"));
return true;
}
if (_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor))
{
OpenInterface(actor.PlayerSession, eventArgs.ClickLocation);
}
return true;
}
void IDropped.Dropped(DroppedEventArgs eventArgs)
{
if (_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor))
{
CloseInterface(actor.PlayerSession);
}
}
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (_entities.TryGetComponent(eventArgs.User, out ActorComponent? actor))
{
ToggleInterface(actor.PlayerSession);
return;
}
return;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Automation;
using Microsoft.WindowsAzure.Management.Automation.Models;
namespace Microsoft.WindowsAzure.Management.Automation
{
public static partial class JobScheduleOperationsExtensions
{
/// <summary>
/// Create a job schedule. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create job schedule
/// operation.
/// </param>
/// <returns>
/// The response model for the create job schedule operation.
/// </returns>
public static JobScheduleCreateResponse Create(this IJobScheduleOperations operations, string automationAccount, JobScheduleCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobScheduleOperations)s).CreateAsync(automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a job schedule. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create job schedule
/// operation.
/// </param>
/// <returns>
/// The response model for the create job schedule operation.
/// </returns>
public static Task<JobScheduleCreateResponse> CreateAsync(this IJobScheduleOperations operations, string automationAccount, JobScheduleCreateParameters parameters)
{
return operations.CreateAsync(automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Delete the job schedule identified by job schedule name. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='jobScheduleName'>
/// Required. The job schedule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IJobScheduleOperations operations, string automationAccount, Guid jobScheduleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobScheduleOperations)s).DeleteAsync(automationAccount, jobScheduleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete the job schedule identified by job schedule name. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='jobScheduleName'>
/// Required. The job schedule name.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IJobScheduleOperations operations, string automationAccount, Guid jobScheduleName)
{
return operations.DeleteAsync(automationAccount, jobScheduleName, CancellationToken.None);
}
/// <summary>
/// Retrieve the job schedule identified by job schedule name. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='jobScheduleName'>
/// Required. The job schedule name.
/// </param>
/// <returns>
/// The response model for the get job schedule operation.
/// </returns>
public static JobScheduleGetResponse Get(this IJobScheduleOperations operations, string automationAccount, Guid jobScheduleName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobScheduleOperations)s).GetAsync(automationAccount, jobScheduleName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the job schedule identified by job schedule name. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='jobScheduleName'>
/// Required. The job schedule name.
/// </param>
/// <returns>
/// The response model for the get job schedule operation.
/// </returns>
public static Task<JobScheduleGetResponse> GetAsync(this IJobScheduleOperations operations, string automationAccount, Guid jobScheduleName)
{
return operations.GetAsync(automationAccount, jobScheduleName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of job schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list job schedule operation.
/// </returns>
public static JobScheduleListResponse List(this IJobScheduleOperations operations, string automationAccount)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobScheduleOperations)s).ListAsync(automationAccount);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of job schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list job schedule operation.
/// </returns>
public static Task<JobScheduleListResponse> ListAsync(this IJobScheduleOperations operations, string automationAccount)
{
return operations.ListAsync(automationAccount, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list job schedule operation.
/// </returns>
public static JobScheduleListResponse ListNext(this IJobScheduleOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobScheduleOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of schedules. (see
/// http://aka.ms/azureautomationsdk/jobscheduleoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Automation.IJobScheduleOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list job schedule operation.
/// </returns>
public static Task<JobScheduleListResponse> ListNextAsync(this IJobScheduleOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WingtipCRMService.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Windows;
using PassWinmenu.Configuration;
using PassWinmenu.ExternalPrograms;
using PassWinmenu.ExternalPrograms.Gpg;
using PassWinmenu.PasswordManagement;
using PassWinmenu.src.Windows;
using PassWinmenu.Utilities;
using PassWinmenu.Utilities.ExtensionMethods;
using PassWinmenu.WinApi;
namespace PassWinmenu.Windows
{
internal class DialogCreator
{
private readonly INotificationService notificationService;
private readonly ISyncService syncService;
private readonly IPasswordManager passwordManager;
private readonly ClipboardHelper clipboard = new ClipboardHelper();
private readonly PathDisplayHelper pathDisplayHelper;
public DialogCreator(INotificationService notificationService, IPasswordManager passwordManager, ISyncService syncService)
{
this.notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
this.passwordManager = passwordManager ?? throw new ArgumentNullException(nameof(passwordManager));
this.syncService = syncService;
this.pathDisplayHelper = new PathDisplayHelper(ConfigManager.Config.Interface.DirectorySeparator);
}
private void EnsureStaThread()
{
}
/// <summary>
/// Opens a window where the user can choose the location for a new password file.
/// </summary>
/// <returns>The path to the file that the user has chosen</returns>
public string ShowFileSelectionWindow()
{
SelectionWindowConfiguration windowConfig;
try
{
windowConfig = SelectionWindowConfiguration.ParseMainWindowConfiguration(ConfigManager.Config);
}
catch (ConfigurationParseException e)
{
notificationService.Raise(e.Message, Severity.Error);
return null;
}
// Ask the user where the password file should be placed.
var pathWindow = new FileSelectionWindow(ConfigManager.Config.PasswordStore.Location, windowConfig);
pathWindow.ShowDialog();
if (!pathWindow.Success)
{
return null;
}
return pathWindow.GetSelection() + Program.EncryptedFileExtension;
}
/// <summary>
/// Opens the password menu and displays it to the user, allowing them to choose an existing password file.
/// </summary>
/// <param name="options">A list of options the user can choose from.</param>
/// <returns>One of the values contained in <paramref name="options"/>, or null if no option was chosen.</returns>
public string ShowPasswordMenu(IEnumerable<string> options)
{
SelectionWindowConfiguration windowConfig;
try
{
windowConfig = SelectionWindowConfiguration.ParseMainWindowConfiguration(ConfigManager.Config);
}
catch (ConfigurationParseException e)
{
notificationService.Raise(e.Message, Severity.Error);
return null;
}
var menu = new PasswordSelectionWindow(options, windowConfig);
menu.ShowDialog();
if (menu.Success)
{
return menu.GetSelection();
}
return null;
}
/// <summary>
/// Asks the user to choose a password file.
/// </summary>
/// <returns>
/// The path to the chosen password file (relative to the password directory),
/// or null if the user didn't choose anything.
/// </returns>
public PasswordFile RequestPasswordFile()
{
EnsureStaThread();
// Find GPG-encrypted password files
var passFiles = passwordManager.GetPasswordFiles(ConfigManager.Config.PasswordStore.PasswordFileMatch).ToList();
if (passFiles.Count == 0)
{
MessageBox.Show("Your password store doesn't appear to contain any passwords yet.", "Empty password store", MessageBoxButton.OK, MessageBoxImage.Information);
return null;
}
var selection = ShowPasswordMenu(passFiles.Select(pathDisplayHelper.GetDisplayPath));
if (selection == null) return null;
return passFiles.Single(f => pathDisplayHelper.GetDisplayPath(f) == selection);
}
public void EditWithEditWindow(DecryptedPasswordFile file)
{
Helpers.AssertOnUiThread();
using (var window = new EditWindow(pathDisplayHelper.GetDisplayPath(file), file.Content, ConfigManager.Config.PasswordStore.PasswordGeneration))
{
if (!window.ShowDialog() ?? true)
{
return;
}
try
{
var newFile = new DecryptedPasswordFile(file, window.PasswordContent.Text);
passwordManager.EncryptPassword(newFile);
syncService?.EditPassword(newFile.FullPath);
if (ConfigManager.Config.Notifications.Types.PasswordUpdated)
{
notificationService.Raise($"Password file \"{newFile.FileNameWithoutExtension}\" has been updated.", Severity.Info);
}
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Unable to save your password (encryption failed): {e.Message}");
// TODO: do we want to show the edit window again here?
}
}
}
public void EditPassword()
{
var selectedFile = RequestPasswordFile();
if (selectedFile == null) return;
if (ConfigManager.Config.Interface.PasswordEditor.UseBuiltin)
{
DecryptedPasswordFile decryptedFile;
try
{
decryptedFile = passwordManager.DecryptPassword(selectedFile, false);
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Unable to edit your password (decryption failed): {e.Message}");
return;
}
EditWithEditWindow(decryptedFile);
}
else
{
EditWithTextEditor(selectedFile);
}
}
/// <summary>
/// Ensures the file at the given path is deleted, warning the user if deletion failed.
/// </summary>
private void EnsureRemoval(string path)
{
try
{
File.Delete(path);
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Unable to delete the plaintext file at {path}.\n" +
$"An error occurred: {e.GetType().Name} ({e.Message}).\n\n" +
$"Please navigate to the given path and delete it manually.", "Plaintext file not deleted.");
}
}
private string CreateTemporaryPlaintextFile()
{
var tempDir = ConfigManager.Config.Interface.PasswordEditor.TemporaryFileDirectory;
if (string.IsNullOrWhiteSpace(tempDir))
{
Log.Send("No temporary file directory specified, using default.", LogLevel.Warning);
tempDir = Path.GetTempPath();
}
if (!Directory.Exists(tempDir))
{
Log.Send($"Temporary directory \"{tempDir}\" does not exist, it will be created.", LogLevel.Info);
Directory.CreateDirectory(tempDir);
}
var tempFile = Path.GetRandomFileName();
var tempPath = Path.Combine(tempDir, tempFile + Program.PlaintextFileExtension);
return tempPath;
}
public void EditWithTextEditor(PasswordFile selectedFile)
{
// Generate a random plaintext filename.
var plaintextFile = CreateTemporaryPlaintextFile();
try
{
var passwordFile = passwordManager.DecryptPassword(selectedFile, false);
File.WriteAllText(plaintextFile, passwordFile.Content);
}
catch (Exception e)
{
EnsureRemoval(plaintextFile);
notificationService.ShowErrorWindow($"Unable to edit your password (decryption failed): {e.Message}");
return;
}
// Open the file in the user's default editor
try
{
Process.Start(plaintextFile);
}
catch (Win32Exception e)
{
EnsureRemoval(plaintextFile);
notificationService.ShowErrorWindow($"Unable to open an editor to edit your password file ({e.Message}).");
return;
}
var result = MessageBox.Show(
"Please keep this window open until you're done editing the password file.\n" +
"Then click Yes to save your changes, or No to discard them.",
$"Save changes to {selectedFile.FileNameWithoutExtension}?",
MessageBoxButton.YesNo,
MessageBoxImage.Information);
if (result == MessageBoxResult.Yes)
{
// Fetch the content from the file, and delete it.
var content = File.ReadAllText(plaintextFile);
EnsureRemoval(plaintextFile);
// Re-encrypt the file.
var newPasswordFile = new DecryptedPasswordFile(selectedFile, content);
passwordManager.EncryptPassword(newPasswordFile);
syncService?.EditPassword(selectedFile.FullPath);
if (ConfigManager.Config.Notifications.Types.PasswordUpdated)
{
notificationService.Raise($"Password file \"{selectedFile}\" has been updated.", Severity.Info);
}
}
else
{
File.Delete(plaintextFile);
}
}
/// <summary>
/// Adds a new password to the password store.
/// </summary>
public void AddPassword()
{
EnsureStaThread();
var passwordFilePath = ShowFileSelectionWindow();
// passwordFileName will be null if no file was selected
if (passwordFilePath == null) return;
// Display the password generation window.
string password;
string metadata;
using (var passwordWindow = new PasswordWindow(Path.GetFileName(passwordFilePath), ConfigManager.Config.PasswordStore.PasswordGeneration))
{
passwordWindow.ShowDialog();
if (!passwordWindow.DialogResult.GetValueOrDefault())
{
return;
}
password = passwordWindow.Password.Text;
metadata = passwordWindow.ExtraContent.Text.Replace(Environment.NewLine, "\n");
}
PasswordFile passwordFile;
try
{
passwordFile = passwordManager.AddPassword(passwordFilePath, password, metadata);
}
catch (GpgException e)
{
notificationService.ShowErrorWindow("Unable to encrypt your password: " + e.Message);
return;
}
catch (ConfigurationException e)
{
notificationService.ShowErrorWindow("Unable to encrypt your password: " + e.Message);
return;
}
// Copy the newly generated password.
clipboard.Place(password, TimeSpan.FromSeconds(ConfigManager.Config.Interface.ClipboardTimeout));
if (ConfigManager.Config.Notifications.Types.PasswordGenerated)
{
notificationService.Raise($"The new password has been copied to your clipboard.\nIt will be cleared in {ConfigManager.Config.Interface.ClipboardTimeout:0.##} seconds.", Severity.Info);
}
// Add the password to Git
syncService?.AddPassword(passwordFile.FullPath);
}
/// <summary>
/// Asks the user to choose a password file, decrypts it, and copies the resulting value to the clipboard.
/// </summary>
public void DecryptPassword(bool copyToClipboard, bool typeUsername, bool typePassword)
{
var selectedFile = RequestPasswordFile();
// If the user cancels their selection, the password decryption should be cancelled too.
if (selectedFile == null) return;
KeyedPasswordFile passFile;
try
{
passFile = passwordManager.DecryptPassword(selectedFile, ConfigManager.Config.PasswordStore.FirstLineOnly);
}
catch (GpgError e)
{
notificationService.ShowErrorWindow("Password decryption failed: " + e.Message);
return;
}
catch (GpgException e)
{
notificationService.ShowErrorWindow("Password decryption failed. " + e.Message);
return;
}
catch (ConfigurationException e)
{
notificationService.ShowErrorWindow("Password decryption failed: " + e.Message);
return;
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Password decryption failed: An error occurred: {e.GetType().Name}: {e.Message}");
return;
}
if (copyToClipboard)
{
clipboard.Place(passFile.Password, TimeSpan.FromSeconds(ConfigManager.Config.Interface.ClipboardTimeout));
if (ConfigManager.Config.Notifications.Types.PasswordCopied)
{
notificationService.Raise($"The password has been copied to your clipboard.\nIt will be cleared in {ConfigManager.Config.Interface.ClipboardTimeout:0.##} seconds.", Severity.Info);
}
}
var usernameEntered = false;
if (typeUsername)
{
var username = new PasswordFileParser().GetUsername(passFile);
if (username != null)
{
KeyboardEmulator.EnterText(username, ConfigManager.Config.Output.DeadKeys);
usernameEntered = true;
}
}
if (typePassword)
{
// If a username has also been entered, press Tab to switch to the password field.
if (usernameEntered) KeyboardEmulator.EnterRawText("{TAB}");
KeyboardEmulator.EnterText(passFile.Password, ConfigManager.Config.Output.DeadKeys);
}
}
public void DecryptMetadata(bool copyToClipboard, bool type)
{
var selectedFile = RequestPasswordFile();
KeyedPasswordFile passFile;
try
{
passFile = passwordManager.DecryptPassword(selectedFile, ConfigManager.Config.PasswordStore.FirstLineOnly);
}
catch (GpgError e)
{
notificationService.ShowErrorWindow("Password decryption failed: " + e.Message);
return;
}
catch (GpgException e)
{
notificationService.ShowErrorWindow("Password decryption failed. " + e.Message);
return;
}
catch (ConfigurationException e)
{
notificationService.ShowErrorWindow("Password decryption failed: " + e.Message);
return;
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Password decryption failed: An error occurred: {e.GetType().Name}: {e.Message}");
return;
}
if (copyToClipboard)
{
clipboard.Place(passFile.Metadata, TimeSpan.FromSeconds(ConfigManager.Config.Interface.ClipboardTimeout));
if (ConfigManager.Config.Notifications.Types.PasswordCopied)
{
notificationService.Raise($"The key has been copied to your clipboard.\nIt will be cleared in {ConfigManager.Config.Interface.ClipboardTimeout:0.##} seconds.", Severity.Info);
}
}
if (type)
{
KeyboardEmulator.EnterText(passFile.Metadata, ConfigManager.Config.Output.DeadKeys);
}
}
public void GetKey(bool copyToClipboard, bool type, string key)
{
var selectedFile = RequestPasswordFile();
if(selectedFile == null) return;
KeyedPasswordFile passFile;
try
{
passFile = passwordManager.DecryptPassword(selectedFile, ConfigManager.Config.PasswordStore.FirstLineOnly);
}
catch (GpgError e)
{
notificationService.ShowErrorWindow("Password decryption failed: " + e.Message);
return;
}
catch (GpgException e)
{
notificationService.ShowErrorWindow("Password decryption failed. " + e.Message);
return;
}
catch (ConfigurationException e)
{
notificationService.ShowErrorWindow("Password decryption failed: " + e.Message);
return;
}
catch (Exception e)
{
notificationService.ShowErrorWindow($"Password decryption failed: An error occurred: {e.GetType().Name}: {e.Message}");
return;
}
if (string.IsNullOrWhiteSpace(key))
{
var keys = passFile.Keys.Select(k => k.Key).Distinct();
var selection = ShowPasswordMenu(keys);
if (selection == null) return;
key = selection;
}
var values = passFile.Keys.Where(k => k.Key == key).ToList();
if (values.Count == 0)
{
return;
}
string chosenValue;
if (values.Count > 1)
{
chosenValue = ShowPasswordMenu(values.Select(v => v.Value));
if (chosenValue == null)
{
return;
}
}
else
{
chosenValue = values[0].Value;
}
if (copyToClipboard)
{
clipboard.Place(chosenValue, TimeSpan.FromSeconds(ConfigManager.Config.Interface.ClipboardTimeout));
if (ConfigManager.Config.Notifications.Types.PasswordCopied)
{
notificationService.Raise($"The key has been copied to your clipboard.\nIt will be cleared in {ConfigManager.Config.Interface.ClipboardTimeout:0.##} seconds.", Severity.Info);
}
}
if (type)
{
KeyboardEmulator.EnterText(chosenValue, ConfigManager.Config.Output.DeadKeys);
}
}
public void ViewLogs()
{
var viewer = new LogViewer(string.Join("\n", Log.History.Select(l => l.ToString())));
viewer.ShowDialog();
}
}
internal class PathDisplayHelper
{
private readonly string directorySeparator;
public PathDisplayHelper(string directorySeparator)
{
this.directorySeparator = directorySeparator;
}
public string GetDisplayPath(PasswordFile file)
{
var names = new List<string>
{
file.FileNameWithoutExtension
};
var current = file.Directory;
while (!current.PathEquals(file.PasswordStore))
{
names.Insert(0, current.Name);
current = current.Parent;
}
return string.Join(directorySeparator, names);
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Reflection;
using Microsoft.Win32;
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
public partial class EventSource
{
#if FEATURE_MANAGED_ETW && FEATURE_PERFTRACING
// For non-Windows, we use a thread-local variable to hold the activity ID.
// On Windows, ETW has it's own thread-local variable and we participate in its use.
[ThreadStatic]
private static Guid s_currentThreadActivityId;
#endif // FEATURE_MANAGED_ETW && FEATURE_PERFTRACING
// ActivityID support (see also WriteEventWithRelatedActivityIdCore)
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. This API
/// should be used when the caller knows the thread's current activity (the one being
/// overwritten) has completed. Otherwise, callers should prefer the overload that
/// return the oldActivityThatWillContinue (below).
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
public static void SetCurrentThreadActivityId(Guid activityId)
{
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
#if FEATURE_MANAGED_ETW
#if FEATURE_ACTIVITYSAMPLING
Guid newId = activityId;
#endif // FEATURE_ACTIVITYSAMPLING
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
#if FEATURE_PERFTRACING
s_currentThreadActivityId = activityId;
#elif PLATFORM_WINDOWS
if (UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref activityId) == 0)
#endif // FEATURE_PERFTRACING
{
#if FEATURE_ACTIVITYSAMPLING
var activityDying = s_activityDying;
if (activityDying != null && newId != activityId)
{
if (activityId == Guid.Empty)
{
activityId = FallbackActivityId;
}
// OutputDebugString(string.Format("Activity dying: {0} -> {1}", activityId, newId));
activityDying(activityId); // This is actually the OLD activity ID.
}
#endif // FEATURE_ACTIVITYSAMPLING
}
#endif // FEATURE_MANAGED_ETW
}
/// <summary>
/// When a thread starts work that is on behalf of 'something else' (typically another
/// thread or network request) it should mark the thread as working on that other work.
/// This API marks the current thread as working on activity 'activityID'. It returns
/// whatever activity the thread was previously marked with. There is a convention that
/// callers can assume that callees restore this activity mark before the callee returns.
/// To encourage this, this API returns the old activity, so that it can be restored later.
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
///
/// It is common, and good practice after setting the thread to an activity to log an event
/// with a 'start' opcode to indicate that precise time/thread where the new activity
/// started.
/// </summary>
/// <param name="activityId">A Guid that represents the new activity with which to mark
/// the current thread</param>
/// <param name="oldActivityThatWillContinue">The Guid that represents the current activity
/// which will continue at some point in the future, on the current thread</param>
public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
{
oldActivityThatWillContinue = activityId;
#if FEATURE_MANAGED_ETW
// We ignore errors to keep with the convention that EventSources do not throw errors.
// Note we can't access m_throwOnWrites because this is a static method.
#if FEATURE_PERFTRACING
oldActivityThatWillContinue = s_currentThreadActivityId;
s_currentThreadActivityId = activityId;
#elif PLATFORM_WINDOWS
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID,
ref oldActivityThatWillContinue);
#endif // FEATURE_PERFTRACING
#endif // FEATURE_MANAGED_ETW
// We don't call the activityDying callback here because the caller has declared that
// it is not dying.
if (TplEtwProvider.Log != null)
TplEtwProvider.Log.SetActivityId(activityId);
}
/// <summary>
/// Retrieves the ETW activity ID associated with the current thread.
/// </summary>
public static Guid CurrentThreadActivityId
{
get
{
// We ignore errors to keep with the convention that EventSources do not throw
// errors. Note we can't access m_throwOnWrites because this is a static method.
Guid retVal = new Guid();
#if FEATURE_MANAGED_ETW
#if FEATURE_PERFTRACING
retVal = s_currentThreadActivityId;
#elif PLATFORM_WINDOWS
UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(
UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID,
ref retVal);
#endif // FEATURE_PERFTRACING
#endif // FEATURE_MANAGED_ETW
return retVal;
}
}
private int GetParameterCount(EventMetadata eventData)
{
return eventData.Parameters.Length;
}
private Type GetDataType(EventMetadata eventData, int parameterId)
{
return eventData.Parameters[parameterId].ParameterType;
}
private static string GetResourceString(string key, params object[] args)
{
return string.Format(Resources.GetResourceString(key), args);
}
private static readonly bool m_EventSourcePreventRecursion = false;
}
internal partial class ManifestBuilder
{
private string GetTypeNameHelper(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.Boolean:
return "win:Boolean";
case TypeCode.Byte:
return "win:UInt8";
case TypeCode.Char:
case TypeCode.UInt16:
return "win:UInt16";
case TypeCode.UInt32:
return "win:UInt32";
case TypeCode.UInt64:
return "win:UInt64";
case TypeCode.SByte:
return "win:Int8";
case TypeCode.Int16:
return "win:Int16";
case TypeCode.Int32:
return "win:Int32";
case TypeCode.Int64:
return "win:Int64";
case TypeCode.String:
return "win:UnicodeString";
case TypeCode.Single:
return "win:Float";
case TypeCode.Double:
return "win:Double";
case TypeCode.DateTime:
return "win:FILETIME";
default:
if (type == typeof(Guid))
return "win:GUID";
else if (type == typeof(IntPtr))
return "win:Pointer";
else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte))
return "win:Binary";
ManifestError(SR.Format(SR.EventSource_UnsupportedEventTypeInManifest, type.Name), true);
return string.Empty;
}
}
}
internal partial class EventProvider
{
internal unsafe int SetInformation(
UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass,
IntPtr data,
uint dataSize)
{
int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED;
if (!m_setInformationMissing)
{
try
{
status = UnsafeNativeMethods.ManifestEtw.EventSetInformation(
m_regHandle,
eventInfoClass,
(void*)data,
(int)dataSize);
}
catch (TypeLoadException)
{
m_setInformationMissing = true;
}
}
return status;
}
}
internal static class Resources
{
internal static string GetResourceString(string key, params object[] args)
{
return string.Format(Resources.GetResourceString(key), args);
}
}
}
| |
using System;
using System.Collections.Generic;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;
namespace BTDB.ODBLayer
{
public class ODBSetFieldHandler : IFieldHandler, IFieldHandlerWithNestedFieldHandlers, IFieldHandlerWithInit
{
readonly IObjectDB _odb;
readonly ITypeConvertorGenerator _typeConvertGenerator;
readonly byte[] _configuration;
readonly IFieldHandler _keysHandler;
int _configurationId;
Type? _type;
public ODBSetFieldHandler(IObjectDB odb, Type type, IFieldHandlerFactory fieldHandlerFactory)
{
_odb = odb;
_typeConvertGenerator = odb.TypeConvertorGenerator;
_type = type;
_keysHandler = fieldHandlerFactory.CreateFromType(type.GetGenericArguments()[0],
FieldHandlerOptions.Orderable | FieldHandlerOptions.AtEndOfStream);
var writer = new ByteBufferWriter();
writer.WriteFieldHandler(_keysHandler);
_configuration = writer.Data.ToByteArray();
CreateConfiguration();
}
public ODBSetFieldHandler(IObjectDB odb, byte[] configuration)
{
_odb = odb;
var fieldHandlerFactory = odb.FieldHandlerFactory;
_typeConvertGenerator = odb.TypeConvertorGenerator;
_configuration = configuration;
var reader = new ByteArrayReader(configuration);
_keysHandler = fieldHandlerFactory.CreateFromReader(reader,
FieldHandlerOptions.Orderable | FieldHandlerOptions.AtEndOfStream);
CreateConfiguration();
}
ODBSetFieldHandler(IObjectDB odb, byte[] configuration, IFieldHandler specializedKeyHandler)
{
_odb = odb;
_typeConvertGenerator = odb.TypeConvertorGenerator;
_configuration = configuration;
_keysHandler = specializedKeyHandler;
CreateConfiguration();
}
void CreateConfiguration()
{
HandledType();
var keyAndValueTypes = _type!.GetGenericArguments();
_configurationId = ODBDictionaryConfiguration.Register(_keysHandler, keyAndValueTypes[0], null, null);
var cfg = ODBDictionaryConfiguration.Get(_configurationId);
lock (cfg)
{
cfg.KeyReader ??= CreateReader(_keysHandler, keyAndValueTypes[0]);
cfg.KeyWriter ??= CreateWriter(_keysHandler, keyAndValueTypes[0]);
}
}
object CreateWriter(IFieldHandler fieldHandler, Type realType)
{
//Action<T, AbstractBufferedWriter, IWriterCtx>
var delegateType =
typeof(Action<,,>).MakeGenericType(realType, typeof(AbstractBufferedWriter), typeof(IWriterCtx));
var dm = ILBuilder.Instance.NewMethod(fieldHandler.Name + "Writer", delegateType);
var ilGenerator = dm.Generator;
void PushWriterOrCtx(IILGen il) => il.Ldarg((ushort) (1 + (fieldHandler.NeedsCtx() ? 1 : 0)));
fieldHandler.Save(ilGenerator, PushWriterOrCtx,
il => il.Ldarg(0).Do(_typeConvertGenerator.GenerateConversion(realType, fieldHandler.HandledType())!));
ilGenerator.Ret();
return dm.Create();
}
object CreateReader(IFieldHandler fieldHandler, Type realType)
{
//Func<AbstractBufferedReader, IReaderCtx, T>
var delegateType = typeof(Func<,,>).MakeGenericType(typeof(AbstractBufferedReader), typeof(IReaderCtx),
realType);
var dm = ILBuilder.Instance.NewMethod(fieldHandler.Name + "Reader", delegateType);
var ilGenerator = dm.Generator;
void PushReaderOrCtx(IILGen il) => il.Ldarg((ushort) (fieldHandler.NeedsCtx() ? 1 : 0));
fieldHandler.Load(ilGenerator, PushReaderOrCtx);
ilGenerator
.Do(_typeConvertGenerator.GenerateConversion(fieldHandler.HandledType(), realType)!)
.Ret();
return dm.Create();
}
public static string HandlerName => "ODBSet";
public string Name => HandlerName;
public byte[] Configuration => _configuration;
public static bool IsCompatibleWithStatic(Type type, FieldHandlerOptions options)
{
if ((options & FieldHandlerOptions.Orderable) != 0) return false;
return type.IsGenericType && IsCompatibleWithCore(type);
}
static bool IsCompatibleWithCore(Type type)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
return genericTypeDefinition == typeof(IOrderedSet<>);
}
public bool IsCompatibleWith(Type type, FieldHandlerOptions options)
{
return IsCompatibleWithStatic(type, options);
}
public Type HandledType()
{
return _type ?? GenerateType(null);
}
public bool NeedsCtx()
{
return true;
}
public void Load(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx)
{
var genericArguments = _type!.GetGenericArguments();
var instanceType = typeof(ODBSet<>).MakeGenericType(genericArguments);
var constructorInfo = instanceType.GetConstructor(
new[] {typeof(IInternalObjectDBTransaction), typeof(ODBDictionaryConfiguration), typeof(ulong)});
ilGenerator
.Do(pushReaderOrCtx)
.Castclass(typeof(IDBReaderCtx))
.Callvirt(() => default(IDBReaderCtx).GetTransaction())
.LdcI4(_configurationId)
.Call(() => ODBDictionaryConfiguration.Get(0))
.Do(Extensions.PushReaderFromCtx(pushReaderOrCtx))
.Callvirt(() => default(AbstractBufferedReader).ReadVUInt64())
.Newobj(constructorInfo!)
.Castclass(_type);
}
public bool NeedInit()
{
return true;
}
public void Init(IILGen ilGenerator, Action<IILGen> pushReaderCtx)
{
var genericArguments = _type!.GetGenericArguments();
var instanceType = typeof(ODBSet<>).MakeGenericType(genericArguments);
var constructorInfo = instanceType.GetConstructor(
new[] {typeof(IInternalObjectDBTransaction), typeof(ODBDictionaryConfiguration)});
ilGenerator
.Do(pushReaderCtx)
.Castclass(typeof(IDBReaderCtx))
.Callvirt(() => default(IDBReaderCtx).GetTransaction())
.LdcI4(_configurationId)
.Call(() => ODBDictionaryConfiguration.Get(0))
.Newobj(constructorInfo!)
.Castclass(_type);
}
public void Skip(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx)
{
ilGenerator
.Do(Extensions.PushReaderFromCtx(pushReaderOrCtx))
.Callvirt(() => default(AbstractBufferedReader).SkipVUInt64());
}
public void Save(IILGen ilGenerator, Action<IILGen> pushWriterOrCtx, Action<IILGen> pushValue)
{
var genericArguments = _type!.GetGenericArguments();
var instanceType = typeof(ODBSet<>).MakeGenericType(genericArguments);
ilGenerator
.Do(pushWriterOrCtx)
.Do(pushValue)
.LdcI4(_configurationId)
.Call(instanceType.GetMethod(nameof(ODBDictionary<int, int>.DoSave))!);
}
public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler? typeHandler)
{
if (_type != type)
GenerateType(type);
if (_type == type) return this;
if (!IsCompatibleWithCore(type)) return this;
var arguments = type.GetGenericArguments();
var wantedKeyHandler = default(IFieldHandler);
if (typeHandler is ODBSetFieldHandler dictTypeHandler)
{
wantedKeyHandler = dictTypeHandler._keysHandler;
}
var specializedKeyHandler = _keysHandler.SpecializeLoadForType(arguments[0], wantedKeyHandler);
if (wantedKeyHandler == specializedKeyHandler)
{
return typeHandler;
}
var res = new ODBSetFieldHandler(_odb, _configuration, specializedKeyHandler);
res.GenerateType(type);
return res;
}
Type GenerateType(Type? compatibleWith)
{
if (compatibleWith != null && compatibleWith.GetGenericTypeDefinition() == typeof(IOrderedSet<>))
{
return _type = typeof(IOrderedSet<>).MakeGenericType(_keysHandler.HandledType());
}
return _type = typeof(ISet<>).MakeGenericType(_keysHandler.HandledType());
}
public IFieldHandler SpecializeSaveForType(Type type)
{
if (_type != type)
GenerateType(type);
return this;
}
public IEnumerable<IFieldHandler> EnumerateNestedFieldHandlers()
{
yield return _keysHandler;
}
public NeedsFreeContent FreeContent(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx)
{
var fakeMethod = ILBuilder.Instance.NewMethod<Action>("Relation_fake");
var fakeGenerator = fakeMethod.Generator;
if (_keysHandler.FreeContent(fakeGenerator, _ => { }) == NeedsFreeContent.Yes)
throw new BTDBException("Not supported 'free content' in IOrderedSet");
ilGenerator
.Do(pushReaderOrCtx)
.Castclass(typeof(IDBReaderCtx))
.Do(Extensions.PushReaderFromCtx(pushReaderOrCtx))
.Callvirt(() => default(AbstractBufferedReader).ReadVUInt64())
.Callvirt(() => default(IDBReaderCtx).RegisterDict(0ul));
return NeedsFreeContent.Yes;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using MonoGame.Extended.BitmapFonts;
using System.Linq;
using System.Reflection;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using MonoGame.Extended.Collections;
using MonoGame.Extended.Gui.Controls;
using MonoGame.Extended.Gui.Serialization;
using MonoGame.Extended.TextureAtlases;
using Newtonsoft.Json;
namespace MonoGame.Extended.Gui
{
public class Skin
{
public Skin()
{
TextureAtlases = new List<TextureAtlas>();
Fonts = new List<BitmapFont>();
NinePatches = new List<NinePatchRegion2D>();
Styles = new KeyedCollection<string, ControlStyle>(s => s.Name ?? s.TargetType.Name);
}
[JsonProperty(Order = 0)]
public string Name { get; set; }
[JsonProperty(Order = 1)]
public IList<TextureAtlas> TextureAtlases { get; set; }
[JsonProperty(Order = 2)]
public IList<BitmapFont> Fonts { get; set; }
[JsonProperty(Order = 3)]
public IList<NinePatchRegion2D> NinePatches { get; set; }
[JsonProperty(Order = 4)]
public BitmapFont DefaultFont => Fonts.FirstOrDefault();
[JsonProperty(Order = 5)]
public Cursor Cursor { get; set; }
[JsonProperty(Order = 6)]
public KeyedCollection<string, ControlStyle> Styles { get; private set; }
public ControlStyle GetStyle(string name)
{
if (Styles.TryGetValue(name, out var controlStyle))
return controlStyle;
return null;
}
public ControlStyle GetStyle(Type controlType)
{
return GetStyle(controlType.FullName);
}
public void Apply(Control control)
{
// TODO: This allocates memory on each apply because it needs to apply styles in reverse
var types = new List<Type>();
var controlType = control.GetType();
while (controlType != null)
{
types.Add(controlType);
controlType = controlType.GetTypeInfo().BaseType;
}
for (var i = types.Count - 1; i >= 0; i--)
{
var style = GetStyle(types[i]);
style?.Apply(control);
}
}
public static Skin FromFile(ContentManager contentManager, string path, params Type[] customControlTypes)
{
using (var stream = TitleContainer.OpenStream(path))
{
return FromStream(contentManager, stream, customControlTypes);
}
}
public static Skin FromStream(ContentManager contentManager, Stream stream, params Type[] customControlTypes)
{
var skinSerializer = new GuiJsonSerializer(contentManager, customControlTypes);
using (var streamReader = new StreamReader(stream))
using (var jsonReader = new JsonTextReader(streamReader))
{
return skinSerializer.Deserialize<Skin>(jsonReader);
}
}
public T Create<T>(string template, Action<T> onCreate)
where T : Control, new()
{
var control = new T();
GetStyle(template).Apply(control);
onCreate(control);
return control;
}
public Control Create(Type type, string template)
{
var control = (Control)Activator.CreateInstance(type);
if (template != null)
GetStyle(template).Apply(control);
return control;
}
public static Skin Default { get; set; }
public static Skin CreateDefault(BitmapFont font)
{
Default = new Skin
{
Fonts = { font },
Styles =
{
new ControlStyle(typeof(Control)) {
{nameof(Control.BackgroundColor), new Color(51, 51, 55)},
{nameof(Control.BorderColor), new Color(67, 67, 70)},
{nameof(Control.BorderThickness), 1},
{nameof(Control.TextColor), new Color(241, 241, 241)},
{nameof(Control.Padding), new Thickness(5)},
{nameof(Control.DisabledStyle), new ControlStyle(typeof(Control)) {
{ nameof(Control.TextColor), new Color(78,78,80) }
}
}
},
new ControlStyle(typeof(LayoutControl)) {
{nameof(Control.BackgroundColor), Color.Transparent},
{nameof(Control.BorderColor), Color.Transparent },
{nameof(Control.BorderThickness), 0},
{nameof(Control.Padding), new Thickness(0)},
{nameof(Control.Margin), new Thickness(0)},
},
new ControlStyle(typeof(ComboBox)) {
{nameof(ComboBox.DropDownColor), new Color(71, 71, 75)},
{nameof(ComboBox.SelectedItemColor), new Color(0, 122, 204)},
{nameof(ComboBox.HorizontalTextAlignment), HorizontalAlignment.Left }
},
new ControlStyle(typeof(CheckBox))
{
{nameof(CheckBox.HorizontalTextAlignment), HorizontalAlignment.Left },
{nameof(CheckBox.BorderThickness), 0},
{nameof(CheckBox.BackgroundColor), Color.Transparent},
},
new ControlStyle(typeof(ListBox))
{
{nameof(ListBox.SelectedItemColor), new Color(0, 122, 204)},
{nameof(ListBox.HorizontalTextAlignment), HorizontalAlignment.Left }
},
new ControlStyle(typeof(Label)) {
{nameof(Label.BackgroundColor), Color.Transparent},
{nameof(Label.TextColor), Color.White},
{nameof(Label.BorderColor), Color.Transparent},
{nameof(Label.BorderThickness), 0},
{nameof(Label.HorizontalTextAlignment), HorizontalAlignment.Left},
{nameof(Label.VerticalTextAlignment), VerticalAlignment.Bottom},
{nameof(Control.Margin), new Thickness(5,0)},
{nameof(Control.Padding), new Thickness(0)},
},
new ControlStyle(typeof(TextBox)) {
{nameof(Control.BackgroundColor), Color.DarkGray},
{nameof(Control.TextColor), Color.Black},
{nameof(Control.BorderColor), new Color(67, 67, 70)},
{nameof(Control.BorderThickness), 2},
},
new ControlStyle(typeof(TextBox2)) {
{nameof(Control.BackgroundColor), Color.DarkGray},
{nameof(Control.TextColor), Color.Black},
{nameof(Control.BorderColor), new Color(67, 67, 70)},
{nameof(Control.BorderThickness), 2},
},
new ControlStyle(typeof(Button)) {
{
nameof(Button.HoverStyle), new ControlStyle {
{nameof(Button.BackgroundColor), new Color(62, 62, 64)},
{nameof(Button.BorderColor), Color.WhiteSmoke }
}
},
{
nameof(Button.PressedStyle), new ControlStyle {
{nameof(Button.BackgroundColor), new Color(0, 122, 204)}
}
}
},
new ControlStyle(typeof(ToggleButton)) {
{
nameof(ToggleButton.CheckedStyle), new ControlStyle {
{nameof(Button.BackgroundColor), new Color(0, 122, 204)}
}
},
{
nameof(ToggleButton.CheckedHoverStyle), new ControlStyle {
{nameof(Button.BorderColor), Color.WhiteSmoke}
}
}
},
new ControlStyle(typeof(ProgressBar)) {
{nameof(ProgressBar.BarColor), new Color(0, 122, 204) },
{nameof(ProgressBar.Height), 32 },
{nameof(ProgressBar.Padding), new Thickness(5, 4)},
}
}
};
return Default;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class HighPriorityProcessor : IdleProcessor
{
private readonly IncrementalAnalyzerProcessor _processor;
private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
// whether this processor is running or not
private Task _running;
public HighPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, backOffTimeSpanInMs, shutdownToken)
{
_processor = processor;
_lazyAnalyzers = lazyAnalyzers;
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter);
Start();
}
private ImmutableArray<IIncrementalAnalyzer> Analyzers
{
get
{
return _lazyAnalyzers.Value;
}
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
// we only put workitem in high priority queue if there is a text change.
// this is to prevent things like opening a file, changing in other files keep enquening
// expensive high priority work.
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
// check whether given item is for active document, otherwise, nothing to do here
if (_processor._documentTracker == null ||
_processor._documentTracker.GetActiveDocument() != item.DocumentId)
{
return;
}
// we need to clone due to waiter
EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile")));
}
private void EnqueueActiveFileItem(WorkItem item)
{
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_ActiveFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator);
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _workItemQueue.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
// okay, there must be at least one item in the map
// see whether we have work item for the document
WorkItem workItem;
CancellationTokenSource documentCancellation;
Contract.ThrowIfFalse(GetNextWorkItem(out workItem, out documentCancellation));
var solution = _processor.CurrentSolution;
// okay now we have work to do
await ProcessDocumentAsync(solution, this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation)
{
// GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail.
var documentId = _processor._documentTracker.GetActiveDocument();
if (documentId != null)
{
if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
{
return true;
}
}
return _workItemQueue.TryTakeAnyWork(
preferableProjectId: null,
dependencyGraph: this._processor.DependencyGraph,
workItem: out workItem,
source: out documentCancellation);
}
private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = solution.GetDocument(documentId);
if (document != null)
{
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
public void Shutdown()
{
_workItemQueue.Dispose();
}
}
}
}
}
}
| |
// This is a generated file created by Glue. To change this file, edit the camera settings in Glue.
// To access the camera settings, push the camera icon.
using Camera = FlatRedBall.Camera;
namespace MultiplayerPlatformerDemo
{
public class CameraSetupData
{
public float Scale { get; set; }
public float ScaleGum { get; set; }
public bool Is2D { get; set; }
public int ResolutionWidth { get; set; }
public int ResolutionHeight { get; set; }
public decimal? AspectRatio { get; set; }
public bool AllowWidowResizing { get; set; }
public bool IsFullScreen { get; set; }
public ResizeBehavior ResizeBehavior { get; set; }
public ResizeBehavior ResizeBehaviorGum { get; set; }
public WidthOrHeight DominantInternalCoordinates { get; set; }
public Microsoft.Xna.Framework.Graphics.TextureFilter TextureFilter { get; set; }
}
public enum ResizeBehavior
{
StretchVisibleArea,
IncreaseVisibleArea
}
public enum WidthOrHeight
{
Width,
Height
}
internal static class CameraSetup
{
static Microsoft.Xna.Framework.GraphicsDeviceManager graphicsDeviceManager;
public static CameraSetupData Data = new CameraSetupData
{
Scale = 500f,
ResolutionWidth = 256,
ResolutionHeight = 224,
Is2D = true,
IsFullScreen = false,
AllowWidowResizing = false,
TextureFilter = Microsoft.Xna.Framework.Graphics.TextureFilter.Point,
ResizeBehavior = ResizeBehavior.StretchVisibleArea,
ScaleGum = 100f,
ResizeBehaviorGum = ResizeBehavior.StretchVisibleArea,
DominantInternalCoordinates = WidthOrHeight.Height,
}
;
internal static void ResetCamera (Camera cameraToReset = null)
{
if (cameraToReset == null)
{
cameraToReset = FlatRedBall.Camera.Main;
}
cameraToReset.Orthogonal = Data.Is2D;
if (Data.Is2D)
{
cameraToReset.OrthogonalHeight = Data.ResolutionHeight;
cameraToReset.OrthogonalWidth = Data.ResolutionWidth;
cameraToReset.FixAspectRatioYConstant();
}
else
{
cameraToReset.UsePixelCoordinates3D(0);
var zoom = cameraToReset.DestinationRectangle.Height / (float)Data.ResolutionHeight;
cameraToReset.Z /= zoom;
}
if (Data.AspectRatio != null)
{
SetAspectRatioTo(Data.AspectRatio.Value, Data.DominantInternalCoordinates, Data.ResolutionWidth, Data.ResolutionHeight);
}
}
internal static void SetupCamera (Camera cameraToSetUp, Microsoft.Xna.Framework.GraphicsDeviceManager graphicsDeviceManager)
{
CameraSetup.graphicsDeviceManager = graphicsDeviceManager;
FlatRedBall.FlatRedBallServices.GraphicsOptions.TextureFilter = Data.TextureFilter;
ResetWindow();
ResetCamera(cameraToSetUp);
ResetGumResolutionValues();
FlatRedBall.FlatRedBallServices.GraphicsOptions.SizeOrOrientationChanged += HandleResolutionChange;
}
internal static void ResetWindow ()
{
#if WINDOWS || DESKTOP_GL
FlatRedBall.FlatRedBallServices.Game.Window.AllowUserResizing = Data.AllowWidowResizing;
if (Data.IsFullScreen)
{
#if DESKTOP_GL
graphicsDeviceManager.HardwareModeSwitch = false;
FlatRedBall.FlatRedBallServices.Game.Window.Position = new Microsoft.Xna.Framework.Point(0,0);
FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution(Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width, Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height, FlatRedBall.Graphics.WindowedFullscreenMode.FullscreenBorderless);
#elif WINDOWS
System.IntPtr hWnd = FlatRedBall.FlatRedBallServices.Game.Window.Handle;
var control = System.Windows.Forms.Control.FromHandle(hWnd);
var form = control.FindForm();
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
form.WindowState = System.Windows.Forms.FormWindowState.Maximized;
#endif
}
else
{
var width = (int)(Data.ResolutionWidth * Data.Scale / 100.0f);
var height = (int)(Data.ResolutionHeight * Data.Scale / 100.0f);
// subtract to leave room for windows borders
var maxWidth = Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width - 6;
var maxHeight = Microsoft.Xna.Framework.Graphics.GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height - 28;
width = System.Math.Min(width, maxWidth);
height = System.Math.Min(height, maxHeight);
if (FlatRedBall.FlatRedBallServices.Game.Window.Position.Y < 25)
{
FlatRedBall.FlatRedBallServices.Game.Window.Position = new Microsoft.Xna.Framework.Point(FlatRedBall.FlatRedBallServices.Game.Window.Position.X, 25);
}
FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution(width, height);
}
#elif IOS || ANDROID
FlatRedBall.FlatRedBallServices.GraphicsOptions.SetFullScreen(FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth, FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight);
#elif UWP
if (Data.IsFullScreen)
{
FlatRedBall.FlatRedBallServices.GraphicsOptions.SetFullScreen(Data.ResolutionWidth, Data.ResolutionHeight);
}
else
{
FlatRedBall.FlatRedBallServices.GraphicsOptions.SetResolution(Data.ResolutionWidth, Data.ResolutionHeight);
var newWindowSize = new Windows.Foundation.Size(Data.ResolutionWidth, Data.ResolutionHeight);
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TryResizeView(newWindowSize);
}
#endif
}
private static void HandleResolutionChange (object sender, System.EventArgs args)
{
if (Data.AspectRatio != null)
{
SetAspectRatioTo(Data.AspectRatio.Value, Data.DominantInternalCoordinates, Data.ResolutionWidth, Data.ResolutionHeight);
}
if (Data.Is2D && Data.ResizeBehavior == ResizeBehavior.IncreaseVisibleArea)
{
FlatRedBall.Camera.Main.OrthogonalHeight = FlatRedBall.Camera.Main.DestinationRectangle.Height / (Data.Scale/ 100.0f);
FlatRedBall.Camera.Main.FixAspectRatioYConstant();
}
ResetGumResolutionValues();
}
public static void ResetGumResolutionValues ()
{
if (Data.ResizeBehaviorGum == ResizeBehavior.IncreaseVisibleArea)
{
global::RenderingLibrary.SystemManagers.Default.Renderer.Camera.Zoom = Data.Scale/100.0f;
Gum.Wireframe.GraphicalUiElement.CanvasWidth = Gum.Managers.ObjectFinder.Self.GumProjectSave.DefaultCanvasWidth;
Gum.Wireframe.GraphicalUiElement.CanvasHeight = Gum.Managers.ObjectFinder.Self.GumProjectSave.DefaultCanvasHeight;
}
else
{
Gum.Wireframe.GraphicalUiElement.CanvasHeight = Data.ResolutionHeight / (Data.ScaleGum/100.0f);
if (Data.AspectRatio != null)
{
Gum.Wireframe.GraphicalUiElement.CanvasWidth = Data.ResolutionWidth / (Data.ScaleGum/100.0f);
var resolutionAspectRatio = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth / (decimal)FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight;
int destinationRectangleWidth;
int destinationRectangleHeight;
int x = 0;
int y = 0;
if (Data.AspectRatio.Value > resolutionAspectRatio)
{
destinationRectangleWidth = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth;
destinationRectangleHeight = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleWidth / (float)Data.AspectRatio.Value);
}
else
{
destinationRectangleHeight = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight;
destinationRectangleWidth = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleHeight * (float)Data.AspectRatio.Value);
}
var canvasHeight = Gum.Wireframe.GraphicalUiElement.CanvasHeight;
var zoom = (float)destinationRectangleHeight / (float)Gum.Wireframe.GraphicalUiElement.CanvasHeight;
if(global::RenderingLibrary.SystemManagers.Default != null)
{
global::RenderingLibrary.SystemManagers.Default.Renderer.Camera.Zoom = zoom;
foreach(var layer in global::RenderingLibrary.SystemManagers.Default.Renderer.Layers)
{
if(layer.LayerCameraSettings != null)
{
layer.LayerCameraSettings.Zoom = zoom;
}
}
}
}
else
{
// since a fixed aspect ratio isn't specified, adjust the width according to the
// current game aspect ratio and the canvas height
var currentAspectRatio = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth / (float)
FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight;
Gum.Wireframe.GraphicalUiElement.CanvasWidth =
Gum.Wireframe.GraphicalUiElement.CanvasHeight * currentAspectRatio;
var graphicsHeight = Gum.Wireframe.GraphicalUiElement.CanvasHeight;
var windowHeight = FlatRedBall.Camera.Main.DestinationRectangle.Height;
var zoom = windowHeight / (float)graphicsHeight;
if(global::RenderingLibrary.SystemManagers.Default != null)
{
global::RenderingLibrary.SystemManagers.Default.Renderer.Camera.Zoom = zoom;
foreach(var layer in global::RenderingLibrary.SystemManagers.Default.Renderer.Layers)
{
if(layer.LayerCameraSettings != null)
{
layer.LayerCameraSettings.Zoom = zoom;
}
}
}
}
}
}
private static void SetAspectRatioTo (decimal aspectRatio, WidthOrHeight dominantInternalCoordinates, int desiredWidth, int desiredHeight)
{
var resolutionAspectRatio = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth / (decimal)FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight;
int destinationRectangleWidth;
int destinationRectangleHeight;
int x = 0;
int y = 0;
if (aspectRatio > resolutionAspectRatio)
{
destinationRectangleWidth = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth;
destinationRectangleHeight = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleWidth / (float)aspectRatio);
y = (FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight - destinationRectangleHeight) / 2;
}
else
{
destinationRectangleHeight = FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionHeight;
destinationRectangleWidth = FlatRedBall.Math.MathFunctions.RoundToInt(destinationRectangleHeight * (float)aspectRatio);
x = (FlatRedBall.FlatRedBallServices.GraphicsOptions.ResolutionWidth - destinationRectangleWidth) / 2;
}
foreach (var camera in FlatRedBall.SpriteManager.Cameras)
{
int currentX = x;
int currentY = y;
int currentWidth = destinationRectangleWidth;
int currentHeight = destinationRectangleHeight;
switch(camera.CurrentSplitScreenViewport)
{
case Camera.SplitScreenViewport.TopLeft:
currentWidth /= 2;
currentHeight /= 2;
break;
case Camera.SplitScreenViewport.TopRight:
currentX = x + destinationRectangleWidth / 2;
currentWidth /= 2;
currentHeight /= 2;
break;
case Camera.SplitScreenViewport.BottomLeft:
currentY = y + destinationRectangleHeight / 2;
currentWidth /= 2;
currentHeight /= 2;
break;
case Camera.SplitScreenViewport.BottomRight:
currentX = x + destinationRectangleWidth / 2;
currentY = y + destinationRectangleHeight / 2;
currentWidth /= 2;
currentHeight /= 2;
break;
case Camera.SplitScreenViewport.TopHalf:
currentHeight /= 2;
break;
case Camera.SplitScreenViewport.BottomHalf:
currentY = y + destinationRectangleHeight / 2;
currentHeight /= 2;
break;
case Camera.SplitScreenViewport.LeftHalf:
currentWidth /= 2;
break;
case Camera.SplitScreenViewport.RightHalf:
currentX = x + destinationRectangleWidth / 2;
currentWidth /= 2;
break;
}
camera.DestinationRectangle = new Microsoft.Xna.Framework.Rectangle(currentX, currentY, currentWidth, currentHeight);
if (dominantInternalCoordinates == WidthOrHeight.Height)
{
camera.OrthogonalHeight = desiredHeight;
camera.FixAspectRatioYConstant();
}
else
{
camera.OrthogonalWidth = desiredWidth;
camera.FixAspectRatioXConstant();
}
}
}
#if WINDOWS
internal static readonly System.IntPtr HWND_TOPMOST = new System.IntPtr(-1);
internal static readonly System.IntPtr HWND_NOTOPMOST = new System.IntPtr(-2);
internal static readonly System.IntPtr HWND_TOP = new System.IntPtr(0);
internal static readonly System.IntPtr HWND_BOTTOM = new System.IntPtr(1);
[System.Flags]
internal enum SetWindowPosFlags : uint
{
IgnoreMove = 0x0002,
IgnoreResize = 0x0001,
}
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
internal static extern bool SetWindowPos(System.IntPtr hWnd, System.IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);
public static void SetWindowAlwaysOnTop()
{
var hWnd = FlatRedBall.FlatRedBallServices.Game.Window.Handle;
SetWindowPos(
hWnd,
HWND_TOPMOST,
0, 0,
0, 0, //FlatRedBallServices.GraphicsOptions.ResolutionWidth, FlatRedBallServices.GraphicsOptions.ResolutionHeight,
SetWindowPosFlags.IgnoreMove | SetWindowPosFlags.IgnoreResize
);
}
public static void UnsetWindowAlwaysOnTop()
{
var hWnd = FlatRedBall.FlatRedBallServices.Game.Window.Handle;
SetWindowPos(
hWnd,
HWND_NOTOPMOST,
0, 0,
0, 0, //FlatRedBallServices.GraphicsOptions.ResolutionWidth, FlatRedBallServices.GraphicsOptions.ResolutionHeight,
SetWindowPosFlags.IgnoreMove | SetWindowPosFlags.IgnoreResize
);
}
#else
public static void SetWindowAlwaysOnTop()
{
// not supported on this platform, do nothing
}
public static void UnsetWindowAlwaysOnTop()
{
// not supported on this platform, do nothings
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using OLEDB.Test.ModuleCore;
using System;
using XmlReaderTest.Common;
namespace XmlReaderTest
{
public partial class WrappedReaderTest : CGenericTestModule
{
private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
{
CModInfo.CommandLine = "/async";
RunTestCase(testCaseGenerator);
}
private static void RunTestCase(Func<CTestBase> testCaseGenerator)
{
var module = new WrappedReaderTest();
module.Init(null);
module.AddChild(testCaseGenerator());
module.Execute();
Assert.Equal(0, module.FailCount);
}
private static void RunTest(Func<CTestBase> testCaseGenerator)
{
RunTestCase(testCaseGenerator);
RunTestCaseAsync(testCaseGenerator);
}
[Fact]
[OuterLoop]
public static void ErrorConditionReader()
{
RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XMLExceptionReader()
{
RunTest(() => new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void LinePosReader()
{
RunTest(() => new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void DepthReader()
{
RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void NamespaceReader()
{
RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void LookupNamespaceReader()
{
RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void HasValueReader()
{
RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void IsEmptyElementReader()
{
RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlSpaceReader()
{
RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlLangReader()
{
RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void SkipReader()
{
RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void InvalidXMLReader()
{
RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeAccessReader()
{
RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ThisNameReader()
{
RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeReader()
{
RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeOrdinalReader()
{
RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeNameReader()
{
RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ThisOrdinalReader()
{
RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeOrdinalReader()
{
RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToFirstAttributeReader()
{
RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToNextAttributeReader()
{
RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeTestReader()
{
RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeXmlDeclarationReader()
{
RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration DCR52258", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsReader()
{
RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsPrefixReader()
{
RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadInnerXmlReader()
{
RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToContentReader()
{
RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void IsStartElementReader()
{
RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStartElementReader()
{
RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadEndElementReader()
{
RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ResolveEntityReader()
{
RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadAttributeValueReader()
{
RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadReader()
{
RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToElementReader()
{
RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void DisposeReader()
{
RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void BufferBoundariesReader()
{
RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterClose()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileBeforeRead()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
}
[Fact]
[OuterLoop]
public static void ReadSubtreeReader()
{
RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToDescendantReader()
{
RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToNextSiblingReader()
{
RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadValueReader()
{
RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBase64Reader()
{
RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBase64Reader()
{
RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBinHexReader()
{
RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBinHexReader()
{
RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "WrappedReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToFollowingReader()
{
RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "WrappedReader" } });
}
}
}
| |
namespace Humidifier.EC2
{
using System.Collections.Generic;
using LaunchTemplateTypes;
public class LaunchTemplate : Humidifier.Resource
{
public static class Attributes
{
public static string LatestVersionNumber = "LatestVersionNumber" ;
public static string DefaultVersionNumber = "DefaultVersionNumber" ;
}
public override string AWSTypeName
{
get
{
return @"AWS::EC2::LaunchTemplate";
}
}
/// <summary>
/// LaunchTemplateName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html#cfn-ec2-launchtemplate-launchtemplatename
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic LaunchTemplateName
{
get;
set;
}
/// <summary>
/// LaunchTemplateData
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html#cfn-ec2-launchtemplate-launchtemplatedata
/// Required: False
/// UpdateType: Mutable
/// Type: LaunchTemplateData
/// </summary>
public LaunchTemplateData LaunchTemplateData
{
get;
set;
}
}
namespace LaunchTemplateTypes
{
public class PrivateIpAdd
{
/// <summary>
/// PrivateIpAddress
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html#cfn-ec2-launchtemplate-privateipadd-privateipaddress
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PrivateIpAddress
{
get;
set;
}
/// <summary>
/// Primary
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html#cfn-ec2-launchtemplate-privateipadd-primary
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Primary
{
get;
set;
}
}
public class BlockDeviceMapping
{
/// <summary>
/// Ebs
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs
/// Required: False
/// UpdateType: Mutable
/// Type: Ebs
/// </summary>
public Ebs Ebs
{
get;
set;
}
/// <summary>
/// NoDevice
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-nodevice
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic NoDevice
{
get;
set;
}
/// <summary>
/// VirtualName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-virtualname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic VirtualName
{
get;
set;
}
/// <summary>
/// DeviceName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping.html#cfn-ec2-launchtemplate-blockdevicemapping-devicename
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DeviceName
{
get;
set;
}
}
public class SpotOptions
{
/// <summary>
/// SpotInstanceType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-spotinstancetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic SpotInstanceType
{
get;
set;
}
/// <summary>
/// InstanceInterruptionBehavior
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-instanceinterruptionbehavior
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InstanceInterruptionBehavior
{
get;
set;
}
/// <summary>
/// MaxPrice
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-maxprice
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MaxPrice
{
get;
set;
}
/// <summary>
/// BlockDurationMinutes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-blockdurationminutes
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic BlockDurationMinutes
{
get;
set;
}
/// <summary>
/// ValidUntil
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions-validuntil
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ValidUntil
{
get;
set;
}
}
public class ElasticGpuSpecification
{
/// <summary>
/// Type
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-elasticgpuspecification.html#cfn-ec2-launchtemplate-elasticgpuspecification-type
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Type
{
get;
set;
}
}
public class TagSpecification
{
/// <summary>
/// ResourceType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-tagspecification.html#cfn-ec2-launchtemplate-tagspecification-resourcetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ResourceType
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-tagspecification.html#cfn-ec2-launchtemplate-tagspecification-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Tag
/// </summary>
public List<Tag> Tags
{
get;
set;
}
}
public class IamInstanceProfile
{
/// <summary>
/// Arn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile.html#cfn-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile-arn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Arn
{
get;
set;
}
/// <summary>
/// Name
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile.html#cfn-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile-name
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Name
{
get;
set;
}
}
public class LicenseSpecification
{
/// <summary>
/// LicenseConfigurationArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-licensespecification.html#cfn-ec2-launchtemplate-licensespecification-licenseconfigurationarn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LicenseConfigurationArn
{
get;
set;
}
}
public class Ebs
{
/// <summary>
/// SnapshotId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-snapshotid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic SnapshotId
{
get;
set;
}
/// <summary>
/// VolumeType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-volumetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic VolumeType
{
get;
set;
}
/// <summary>
/// KmsKeyId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-kmskeyid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic KmsKeyId
{
get;
set;
}
/// <summary>
/// Encrypted
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-encrypted
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Encrypted
{
get;
set;
}
/// <summary>
/// Iops
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-iops
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Iops
{
get;
set;
}
/// <summary>
/// VolumeSize
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-volumesize
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic VolumeSize
{
get;
set;
}
/// <summary>
/// DeleteOnTermination
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-blockdevicemapping-ebs.html#cfn-ec2-launchtemplate-blockdevicemapping-ebs-deleteontermination
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic DeleteOnTermination
{
get;
set;
}
}
public class HibernationOptions
{
/// <summary>
/// Configured
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-hibernationoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-hibernationoptions-configured
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Configured
{
get;
set;
}
}
public class LaunchTemplateData
{
/// <summary>
/// SecurityGroups
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-securitygroups
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic SecurityGroups
{
get;
set;
}
/// <summary>
/// TagSpecifications
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-tagspecifications
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: TagSpecification
/// </summary>
public List<TagSpecification> TagSpecifications
{
get;
set;
}
/// <summary>
/// UserData
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-userdata
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic UserData
{
get;
set;
}
/// <summary>
/// BlockDeviceMappings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-blockdevicemappings
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: BlockDeviceMapping
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get;
set;
}
/// <summary>
/// IamInstanceProfile
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-iaminstanceprofile
/// Required: False
/// UpdateType: Mutable
/// Type: IamInstanceProfile
/// </summary>
public IamInstanceProfile IamInstanceProfile
{
get;
set;
}
/// <summary>
/// KernelId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-kernelid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic KernelId
{
get;
set;
}
/// <summary>
/// EbsOptimized
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-ebsoptimized
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic EbsOptimized
{
get;
set;
}
/// <summary>
/// ElasticGpuSpecifications
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-elasticgpuspecifications
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: ElasticGpuSpecification
/// </summary>
public List<ElasticGpuSpecification> ElasticGpuSpecifications
{
get;
set;
}
/// <summary>
/// ElasticInferenceAccelerators
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-elasticinferenceaccelerators
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: LaunchTemplateElasticInferenceAccelerator
/// </summary>
public List<LaunchTemplateElasticInferenceAccelerator> ElasticInferenceAccelerators
{
get;
set;
}
/// <summary>
/// Placement
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-placement
/// Required: False
/// UpdateType: Mutable
/// Type: Placement
/// </summary>
public Placement Placement
{
get;
set;
}
/// <summary>
/// NetworkInterfaces
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-networkinterfaces
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: NetworkInterface
/// </summary>
public List<NetworkInterface> NetworkInterfaces
{
get;
set;
}
/// <summary>
/// ImageId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-imageid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ImageId
{
get;
set;
}
/// <summary>
/// InstanceType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-instancetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InstanceType
{
get;
set;
}
/// <summary>
/// Monitoring
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-monitoring
/// Required: False
/// UpdateType: Mutable
/// Type: Monitoring
/// </summary>
public Monitoring Monitoring
{
get;
set;
}
/// <summary>
/// HibernationOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-hibernationoptions
/// Required: False
/// UpdateType: Mutable
/// Type: HibernationOptions
/// </summary>
public HibernationOptions HibernationOptions
{
get;
set;
}
/// <summary>
/// MetadataOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions
/// Required: False
/// UpdateType: Mutable
/// Type: MetadataOptions
/// </summary>
public MetadataOptions MetadataOptions
{
get;
set;
}
/// <summary>
/// LicenseSpecifications
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-licensespecifications
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: LicenseSpecification
/// </summary>
public List<LicenseSpecification> LicenseSpecifications
{
get;
set;
}
/// <summary>
/// InstanceInitiatedShutdownBehavior
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-instanceinitiatedshutdownbehavior
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InstanceInitiatedShutdownBehavior
{
get;
set;
}
/// <summary>
/// CpuOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-cpuoptions
/// Required: False
/// UpdateType: Mutable
/// Type: CpuOptions
/// </summary>
public CpuOptions CpuOptions
{
get;
set;
}
/// <summary>
/// SecurityGroupIds
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-securitygroupids
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic SecurityGroupIds
{
get;
set;
}
/// <summary>
/// KeyName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-keyname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic KeyName
{
get;
set;
}
/// <summary>
/// DisableApiTermination
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-disableapitermination
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic DisableApiTermination
{
get;
set;
}
/// <summary>
/// InstanceMarketOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions
/// Required: False
/// UpdateType: Mutable
/// Type: InstanceMarketOptions
/// </summary>
public InstanceMarketOptions InstanceMarketOptions
{
get;
set;
}
/// <summary>
/// RamDiskId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-ramdiskid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic RamDiskId
{
get;
set;
}
/// <summary>
/// CapacityReservationSpecification
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification
/// Required: False
/// UpdateType: Mutable
/// Type: CapacityReservationSpecification
/// </summary>
public CapacityReservationSpecification CapacityReservationSpecification
{
get;
set;
}
/// <summary>
/// CreditSpecification
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata.html#cfn-ec2-launchtemplate-launchtemplatedata-creditspecification
/// Required: False
/// UpdateType: Mutable
/// Type: CreditSpecification
/// </summary>
public CreditSpecification CreditSpecification
{
get;
set;
}
}
public class InstanceMarketOptions
{
/// <summary>
/// SpotOptions
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-spotoptions
/// Required: False
/// UpdateType: Mutable
/// Type: SpotOptions
/// </summary>
public SpotOptions SpotOptions
{
get;
set;
}
/// <summary>
/// MarketType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-instancemarketoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-instancemarketoptions-markettype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic MarketType
{
get;
set;
}
}
public class CreditSpecification
{
/// <summary>
/// CpuCredits
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-creditspecification.html#cfn-ec2-launchtemplate-launchtemplatedata-creditspecification-cpucredits
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic CpuCredits
{
get;
set;
}
}
public class Monitoring
{
/// <summary>
/// Enabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-monitoring.html#cfn-ec2-launchtemplate-launchtemplatedata-monitoring-enabled
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Enabled
{
get;
set;
}
}
public class MetadataOptions
{
/// <summary>
/// HttpPutResponseHopLimit
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-metadataoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions-httpputresponsehoplimit
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic HttpPutResponseHopLimit
{
get;
set;
}
/// <summary>
/// HttpTokens
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-metadataoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions-httptokens
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HttpTokens
{
get;
set;
}
/// <summary>
/// HttpEndpoint
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-metadataoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-metadataoptions-httpendpoint
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HttpEndpoint
{
get;
set;
}
}
public class Placement
{
/// <summary>
/// GroupName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-groupname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic GroupName
{
get;
set;
}
/// <summary>
/// Tenancy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-tenancy
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Tenancy
{
get;
set;
}
/// <summary>
/// SpreadDomain
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-spreaddomain
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic SpreadDomain
{
get;
set;
}
/// <summary>
/// PartitionNumber
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-partitionnumber
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic PartitionNumber
{
get;
set;
}
/// <summary>
/// AvailabilityZone
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-availabilityzone
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic AvailabilityZone
{
get;
set;
}
/// <summary>
/// Affinity
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-affinity
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Affinity
{
get;
set;
}
/// <summary>
/// HostId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-hostid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HostId
{
get;
set;
}
/// <summary>
/// HostResourceGroupArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-placement.html#cfn-ec2-launchtemplate-launchtemplatedata-placement-hostresourcegrouparn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HostResourceGroupArn
{
get;
set;
}
}
public class CapacityReservationSpecification
{
/// <summary>
/// CapacityReservationPreference
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification.html#cfn-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification-capacityreservationpreference
/// Required: False
/// UpdateType: Mutable
/// Type: dynamic
/// </summary>
public dynamic CapacityReservationPreference
{
get;
set;
}
/// <summary>
/// CapacityReservationTarget
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification.html#cfn-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification-capacityreservationtarget
/// Required: False
/// UpdateType: Mutable
/// Type: CapacityReservationTarget
/// </summary>
public CapacityReservationTarget CapacityReservationTarget
{
get;
set;
}
}
public class Ipv6Add
{
/// <summary>
/// Ipv6Address
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-ipv6add.html#cfn-ec2-launchtemplate-ipv6add-ipv6address
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Ipv6Address
{
get;
set;
}
}
public class CapacityReservationTarget
{
/// <summary>
/// CapacityReservationId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-capacityreservationtarget.html#cfn-ec2-launchtemplate-capacityreservationtarget-capacityreservationid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic CapacityReservationId
{
get;
set;
}
}
public class NetworkInterface
{
/// <summary>
/// Description
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-description
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Description
{
get;
set;
}
/// <summary>
/// PrivateIpAddress
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-privateipaddress
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PrivateIpAddress
{
get;
set;
}
/// <summary>
/// PrivateIpAddresses
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-privateipaddresses
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: PrivateIpAdd
/// </summary>
public List<PrivateIpAdd> PrivateIpAddresses
{
get;
set;
}
/// <summary>
/// SecondaryPrivateIpAddressCount
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-secondaryprivateipaddresscount
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic SecondaryPrivateIpAddressCount
{
get;
set;
}
/// <summary>
/// DeviceIndex
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-deviceindex
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic DeviceIndex
{
get;
set;
}
/// <summary>
/// SubnetId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-subnetid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic SubnetId
{
get;
set;
}
/// <summary>
/// Ipv6Addresses
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-ipv6addresses
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Ipv6Add
/// </summary>
public List<Ipv6Add> Ipv6Addresses
{
get;
set;
}
/// <summary>
/// AssociatePublicIpAddress
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-associatepublicipaddress
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic AssociatePublicIpAddress
{
get;
set;
}
/// <summary>
/// NetworkInterfaceId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-networkinterfaceid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic NetworkInterfaceId
{
get;
set;
}
/// <summary>
/// InterfaceType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-interfacetype
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InterfaceType
{
get;
set;
}
/// <summary>
/// Ipv6AddressCount
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-ipv6addresscount
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Ipv6AddressCount
{
get;
set;
}
/// <summary>
/// Groups
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-groups
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Groups
{
get;
set;
}
/// <summary>
/// DeleteOnTermination
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-networkinterface.html#cfn-ec2-launchtemplate-networkinterface-deleteontermination
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic DeleteOnTermination
{
get;
set;
}
}
public class CpuOptions
{
/// <summary>
/// ThreadsPerCore
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-cpuoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-cpuoptions-threadspercore
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic ThreadsPerCore
{
get;
set;
}
/// <summary>
/// CoreCount
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-cpuoptions.html#cfn-ec2-launchtemplate-launchtemplatedata-cpuoptions-corecount
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic CoreCount
{
get;
set;
}
}
public class LaunchTemplateElasticInferenceAccelerator
{
/// <summary>
/// Type
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator.html#cfn-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator-type
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Type
{
get;
set;
}
/// <summary>
/// Count
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator.html#cfn-ec2-launchtemplate-launchtemplateelasticinferenceaccelerator-count
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Count
{
get;
set;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.