context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// dnlib: See LICENSE.txt for more info
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using dnlib.Utils;
using dnlib.DotNet.MD;
using dnlib.DotNet.Writer;
using dnlib.Threading;
#if THREAD_SAFE
using ThreadSafe = dnlib.Threading.Collections;
#else
using ThreadSafe = System.Collections.Generic;
#endif
namespace dnlib.DotNet {
/// <summary>
/// A high-level representation of a row in the Assembly table
/// </summary>
public abstract class AssemblyDef : IHasCustomAttribute, IHasDeclSecurity, IAssembly, IListListener<ModuleDef>, ITypeDefFinder, IDnlibDef {
/// <summary>
/// The row id in its table
/// </summary>
protected uint rid;
/// <inheritdoc/>
public MDToken MDToken {
get { return new MDToken(Table.Assembly, rid); }
}
/// <inheritdoc/>
public uint Rid {
get { return rid; }
set { rid = value; }
}
/// <inheritdoc/>
public int HasCustomAttributeTag {
get { return 14; }
}
/// <inheritdoc/>
public int HasDeclSecurityTag {
get { return 2; }
}
/// <summary>
/// From column Assembly.HashAlgId
/// </summary>
public AssemblyHashAlgorithm HashAlgorithm {
get { return hashAlgorithm; }
set { hashAlgorithm = value; }
}
/// <summary/>
protected AssemblyHashAlgorithm hashAlgorithm;
/// <summary>
/// From columns Assembly.MajorVersion, Assembly.MinorVersion, Assembly.BuildNumber,
/// Assembly.RevisionNumber.
/// </summary>
/// <exception cref="ArgumentNullException">If <paramref name="value"/> is <c>null</c></exception>
public Version Version {
get { return version; }
set {
if (value == null)
throw new ArgumentNullException("value");
version = value;
}
}
/// <summary/>
protected Version version;
/// <summary>
/// From column Assembly.Flags
/// </summary>
public AssemblyAttributes Attributes {
get { return (AssemblyAttributes)attributes; }
set { attributes = (int)value; }
}
/// <summary>Attributes</summary>
protected int attributes;
/// <summary>
/// From column Assembly.PublicKey
/// </summary>
/// <remarks>An empty <see cref="PublicKey"/> is created if the caller writes <c>null</c></remarks>
public PublicKey PublicKey {
get { return publicKey; }
set { publicKey = value ?? new PublicKey(); }
}
/// <summary/>
protected PublicKey publicKey;
/// <summary>
/// Gets the public key token which is calculated from <see cref="PublicKey"/>
/// </summary>
public PublicKeyToken PublicKeyToken {
get { return publicKey.Token; }
}
/// <summary>
/// From column Assembly.Name
/// </summary>
public UTF8String Name {
get { return name; }
set { name = value; }
}
/// <summary>Name</summary>
protected UTF8String name;
/// <summary>
/// From column Assembly.Locale
/// </summary>
public UTF8String Culture {
get { return culture; }
set { culture = value; }
}
/// <summary>Name</summary>
protected UTF8String culture;
/// <inheritdoc/>
public ThreadSafe.IList<DeclSecurity> DeclSecurities {
get {
if (declSecurities == null)
InitializeDeclSecurities();
return declSecurities;
}
}
/// <summary/>
protected ThreadSafe.IList<DeclSecurity> declSecurities;
/// <summary>Initializes <see cref="declSecurities"/></summary>
protected virtual void InitializeDeclSecurities() {
Interlocked.CompareExchange(ref declSecurities, ThreadSafeListCreator.Create<DeclSecurity>(), null);
}
/// <inheritdoc/>
public PublicKeyBase PublicKeyOrToken {
get { return publicKey; }
}
/// <inheritdoc/>
public string FullName {
get { return GetFullNameWithPublicKeyToken(); }
}
/// <inheritdoc/>
public string FullNameToken {
get { return GetFullNameWithPublicKeyToken(); }
}
/// <summary>
/// Gets all modules. The first module is always the <see cref="ManifestModule"/>.
/// </summary>
public ThreadSafe.IList<ModuleDef> Modules {
get {
if (modules == null)
InitializeModules();
return modules;
}
}
/// <summary/>
protected LazyList<ModuleDef> modules;
/// <summary>Initializes <see cref="modules"/></summary>
protected virtual void InitializeModules() {
Interlocked.CompareExchange(ref modules, new LazyList<ModuleDef>(this), null);
}
/// <summary>
/// Gets all custom attributes
/// </summary>
public CustomAttributeCollection CustomAttributes {
get {
if (customAttributes == null)
InitializeCustomAttributes();
return customAttributes;
}
}
/// <summary/>
protected CustomAttributeCollection customAttributes;
/// <summary>Initializes <see cref="customAttributes"/></summary>
protected virtual void InitializeCustomAttributes() {
Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null);
}
/// <inheritdoc/>
public bool HasCustomAttributes {
get { return CustomAttributes.Count > 0; }
}
/// <inheritdoc/>
public bool HasDeclSecurities {
get { return DeclSecurities.Count > 0; }
}
/// <summary>
/// <c>true</c> if <see cref="Modules"/> is not empty
/// </summary>
public bool HasModules {
get { return Modules.Count > 0; }
}
/// <summary>
/// Gets the manifest (main) module. This is always the first module in <see cref="Modules"/>.
/// <c>null</c> is returned if <see cref="Modules"/> is empty.
/// </summary>
public ModuleDef ManifestModule {
get { return Modules.Get(0, null); }
}
/// <summary>
/// Modify <see cref="attributes"/> property: <see cref="attributes"/> =
/// (<see cref="attributes"/> & <paramref name="andMask"/>) | <paramref name="orMask"/>.
/// </summary>
/// <param name="andMask">Value to <c>AND</c></param>
/// <param name="orMask">Value to OR</param>
void ModifyAttributes(AssemblyAttributes andMask, AssemblyAttributes orMask) {
#if THREAD_SAFE
int origVal, newVal;
do {
origVal = attributes;
newVal = (origVal & (int)andMask) | (int)orMask;
} while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal);
#else
attributes = (attributes & (int)andMask) | (int)orMask;
#endif
}
/// <summary>
/// Set or clear flags in <see cref="attributes"/>
/// </summary>
/// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should
/// be cleared</param>
/// <param name="flags">Flags to set or clear</param>
void ModifyAttributes(bool set, AssemblyAttributes flags) {
#if THREAD_SAFE
int origVal, newVal;
do {
origVal = attributes;
if (set)
newVal = origVal | (int)flags;
else
newVal = origVal & ~(int)flags;
} while (Interlocked.CompareExchange(ref attributes, newVal, origVal) != origVal);
#else
if (set)
attributes |= (int)flags;
else
attributes &= ~(int)flags;
#endif
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.PublicKey"/> bit
/// </summary>
public bool HasPublicKey {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PublicKey) != 0; }
set { ModifyAttributes(value, AssemblyAttributes.PublicKey); }
}
/// <summary>
/// Gets/sets the processor architecture
/// </summary>
public AssemblyAttributes ProcessorArchitecture {
get { return (AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask; }
set { ModifyAttributes(~AssemblyAttributes.PA_Mask, value & AssemblyAttributes.PA_Mask); }
}
/// <summary>
/// Gets/sets the processor architecture
/// </summary>
public AssemblyAttributes ProcessorArchitectureFull {
get { return (AssemblyAttributes)attributes & AssemblyAttributes.PA_FullMask; }
set { ModifyAttributes(~AssemblyAttributes.PA_FullMask, value & AssemblyAttributes.PA_FullMask); }
}
/// <summary>
/// <c>true</c> if unspecified processor architecture
/// </summary>
public bool IsProcessorArchitectureNone {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_None; }
}
/// <summary>
/// <c>true</c> if neutral (PE32) architecture
/// </summary>
public bool IsProcessorArchitectureMSIL {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_MSIL; }
}
/// <summary>
/// <c>true</c> if x86 (PE32) architecture
/// </summary>
public bool IsProcessorArchitectureX86 {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_x86; }
}
/// <summary>
/// <c>true</c> if IA-64 (PE32+) architecture
/// </summary>
public bool IsProcessorArchitectureIA64 {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_IA64; }
}
/// <summary>
/// <c>true</c> if x64 (PE32+) architecture
/// </summary>
public bool IsProcessorArchitectureX64 {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_AMD64; }
}
/// <summary>
/// <c>true</c> if ARM (PE32) architecture
/// </summary>
public bool IsProcessorArchitectureARM {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_ARM; }
}
/// <summary>
/// <c>true</c> if eg. reference assembly (not runnable)
/// </summary>
public bool IsProcessorArchitectureNoPlatform {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Mask) == AssemblyAttributes.PA_NoPlatform; }
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.PA_Specified"/> bit
/// </summary>
public bool IsProcessorArchitectureSpecified {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.PA_Specified) != 0; }
set { ModifyAttributes(value, AssemblyAttributes.PA_Specified); }
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.EnableJITcompileTracking"/> bit
/// </summary>
public bool EnableJITcompileTracking {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.EnableJITcompileTracking) != 0; }
set { ModifyAttributes(value, AssemblyAttributes.EnableJITcompileTracking); }
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.DisableJITcompileOptimizer"/> bit
/// </summary>
public bool DisableJITcompileOptimizer {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.DisableJITcompileOptimizer) != 0; }
set { ModifyAttributes(value, AssemblyAttributes.DisableJITcompileOptimizer); }
}
/// <summary>
/// Gets/sets the <see cref="AssemblyAttributes.Retargetable"/> bit
/// </summary>
public bool IsRetargetable {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.Retargetable) != 0; }
set { ModifyAttributes(value, AssemblyAttributes.Retargetable); }
}
/// <summary>
/// Gets/sets the content type
/// </summary>
public AssemblyAttributes ContentType {
get { return (AssemblyAttributes)attributes & AssemblyAttributes.ContentType_Mask; }
set { ModifyAttributes(~AssemblyAttributes.ContentType_Mask, value & AssemblyAttributes.ContentType_Mask); }
}
/// <summary>
/// <c>true</c> if content type is <c>Default</c>
/// </summary>
public bool IsContentTypeDefault {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_Default; }
}
/// <summary>
/// <c>true</c> if content type is <c>WindowsRuntime</c>
/// </summary>
public bool IsContentTypeWindowsRuntime {
get { return ((AssemblyAttributes)attributes & AssemblyAttributes.ContentType_Mask) == AssemblyAttributes.ContentType_WindowsRuntime; }
}
/// <summary>
/// Finds a module in this assembly
/// </summary>
/// <param name="name">Name of module</param>
/// <returns>A <see cref="ModuleDef"/> instance or <c>null</c> if it wasn't found.</returns>
public ModuleDef FindModule(UTF8String name) {
foreach (var module in Modules.GetSafeEnumerable()) {
if (module == null)
continue;
if (UTF8String.CaseInsensitiveEquals(module.Name, name))
return module;
}
return null;
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a file
/// </summary>
/// <param name="fileName">File name of an existing .NET assembly</param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="fileName"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(string fileName) {
return Load(fileName, (ModuleCreationOptions)null);
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a file
/// </summary>
/// <param name="fileName">File name of an existing .NET assembly</param>
/// <param name="context">Module context or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="fileName"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(string fileName, ModuleContext context) {
return Load(fileName, new ModuleCreationOptions(context));
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a file
/// </summary>
/// <param name="fileName">File name of an existing .NET assembly</param>
/// <param name="options">Module creation options or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="fileName"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(string fileName, ModuleCreationOptions options) {
if (fileName == null)
throw new ArgumentNullException("fileName");
ModuleDef module = null;
try {
module = ModuleDefMD.Load(fileName, options);
var asm = module.Assembly;
if (asm == null)
throw new BadImageFormatException(string.Format("{0} is only a .NET module, not a .NET assembly. Use ModuleDef.Load().", fileName));
return asm;
}
catch {
if (module != null)
module.Dispose();
throw;
}
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a byte[]
/// </summary>
/// <param name="data">Contents of a .NET assembly</param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="data"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(byte[] data) {
return Load(data, (ModuleCreationOptions)null);
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a byte[]
/// </summary>
/// <param name="data">Contents of a .NET assembly</param>
/// <param name="context">Module context or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="data"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(byte[] data, ModuleContext context) {
return Load(data, new ModuleCreationOptions(context));
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a byte[]
/// </summary>
/// <param name="data">Contents of a .NET assembly</param>
/// <param name="options">Module creation options or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="data"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(byte[] data, ModuleCreationOptions options) {
if (data == null)
throw new ArgumentNullException("data");
ModuleDef module = null;
try {
module = ModuleDefMD.Load(data, options);
var asm = module.Assembly;
if (asm == null)
throw new BadImageFormatException(string.Format("{0} is only a .NET module, not a .NET assembly. Use ModuleDef.Load().", module.ToString()));
return asm;
}
catch {
if (module != null)
module.Dispose();
throw;
}
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a memory location
/// </summary>
/// <param name="addr">Address of a .NET assembly</param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="addr"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(IntPtr addr) {
return Load(addr, (ModuleCreationOptions)null);
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a memory location
/// </summary>
/// <param name="addr">Address of a .NET assembly</param>
/// <param name="context">Module context or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="addr"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(IntPtr addr, ModuleContext context) {
return Load(addr, new ModuleCreationOptions(context));
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a memory location
/// </summary>
/// <param name="addr">Address of a .NET assembly</param>
/// <param name="options">Module creation options or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="addr"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(IntPtr addr, ModuleCreationOptions options) {
if (addr == IntPtr.Zero)
throw new ArgumentNullException("addr");
ModuleDef module = null;
try {
module = ModuleDefMD.Load(addr, options);
var asm = module.Assembly;
if (asm == null)
throw new BadImageFormatException(string.Format("{0} (addr: {1:X8}) is only a .NET module, not a .NET assembly. Use ModuleDef.Load().", module.ToString(), addr.ToInt64()));
return asm;
}
catch {
if (module != null)
module.Dispose();
throw;
}
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a stream
/// </summary>
/// <remarks>This will read all bytes from the stream and call <see cref="Load(byte[])"/>.
/// It's better to use one of the other Load() methods.</remarks>
/// <param name="stream">The stream</param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(Stream stream) {
return Load(stream, (ModuleCreationOptions)null);
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a stream
/// </summary>
/// <remarks>This will read all bytes from the stream and call <see cref="Load(byte[],ModuleContext)"/>.
/// It's better to use one of the other Load() methods.</remarks>
/// <param name="stream">The stream</param>
/// <param name="context">Module context or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(Stream stream, ModuleContext context) {
return Load(stream, new ModuleCreationOptions(context));
}
/// <summary>
/// Creates an <see cref="AssemblyDef"/> instance from a stream
/// </summary>
/// <remarks>This will read all bytes from the stream and call <see cref="Load(byte[],ModuleContext)"/>.
/// It's better to use one of the other Load() methods.</remarks>
/// <param name="stream">The stream</param>
/// <param name="options">Module creation options or <c>null</c></param>
/// <returns>A new <see cref="AssemblyDef"/> instance</returns>
/// <exception cref="ArgumentNullException">If <paramref name="stream"/> is <c>null</c></exception>
/// <exception cref="BadImageFormatException">If it's not a .NET assembly (eg. not a .NET file or only a .NET module)</exception>
public static AssemblyDef Load(Stream stream, ModuleCreationOptions options) {
if (stream == null)
throw new ArgumentNullException("stream");
ModuleDef module = null;
try {
module = ModuleDefMD.Load(stream, options);
var asm = module.Assembly;
if (asm == null)
throw new BadImageFormatException(string.Format("{0} is only a .NET module, not a .NET assembly. Use ModuleDef.Load().", module.ToString()));
return asm;
}
catch {
if (module != null)
module.Dispose();
throw;
}
}
/// <summary>
/// Gets the assembly name with the public key
/// </summary>
public string GetFullNameWithPublicKey() {
return GetFullName(publicKey);
}
/// <summary>
/// Gets the assembly name with the public key token
/// </summary>
public string GetFullNameWithPublicKeyToken() {
return GetFullName(publicKey.Token);
}
string GetFullName(PublicKeyBase pkBase) {
return Utils.GetAssemblyNameString(name, version, culture, pkBase, Attributes);
}
/// <summary>
/// Finds a <see cref="TypeDef"/>. For speed, enable <see cref="ModuleDef.EnableTypeDefFindCache"/>
/// if possible (read the documentation first).
/// </summary>
/// <param name="fullName">Full name of the type (no assembly information)</param>
/// <param name="isReflectionName"><c>true</c> if it's a reflection name, and nested
/// type names are separated by a <c>+</c> character. If <c>false</c>, nested type names
/// are separated by a <c>/</c> character.</param>
/// <returns>An existing <see cref="TypeDef"/> or <c>null</c> if it wasn't found.</returns>
public TypeDef Find(string fullName, bool isReflectionName) {
foreach (var module in Modules.GetSafeEnumerable()) {
if (module == null)
continue;
var type = module.Find(fullName, isReflectionName);
if (type != null)
return type;
}
return null;
}
/// <summary>
/// Finds a <see cref="TypeDef"/>. Its scope (i.e., module or assembly) is ignored when
/// looking up the type. For speed, enable <see cref="ModuleDef.EnableTypeDefFindCache"/>
/// if possible (read the documentation first).
/// </summary>
/// <param name="typeRef">The type ref</param>
/// <returns>An existing <see cref="TypeDef"/> or <c>null</c> if it wasn't found.</returns>
public TypeDef Find(TypeRef typeRef) {
foreach (var module in Modules.GetSafeEnumerable()) {
if (module == null)
continue;
var type = module.Find(typeRef);
if (type != null)
return type;
}
return null;
}
/// <summary>
/// Writes the assembly to a file on disk. If the file exists, it will be truncated.
/// </summary>
/// <param name="filename">Filename</param>
public void Write(string filename) {
Write(filename, null);
}
/// <summary>
/// Writes the assembly to a file on disk. If the file exists, it will be truncated.
/// </summary>
/// <param name="filename">Filename</param>
/// <param name="options">Writer options</param>
public void Write(string filename, ModuleWriterOptions options) {
ManifestModule.Write(filename, options);
}
/// <summary>
/// Writes the assembly to a stream.
/// </summary>
/// <param name="dest">Destination stream</param>
public void Write(Stream dest) {
Write(dest, null);
}
/// <summary>
/// Writes the assembly to a stream.
/// </summary>
/// <param name="dest">Destination stream</param>
/// <param name="options">Writer options</param>
public void Write(Stream dest, ModuleWriterOptions options) {
ManifestModule.Write(dest, options);
}
/// <summary>
/// Checks whether this assembly is a friend assembly of <paramref name="targetAsm"/>
/// </summary>
/// <param name="targetAsm">Target assembly</param>
public bool IsFriendAssemblyOf(AssemblyDef targetAsm) {
if (targetAsm == null)
return false;
if (this == targetAsm)
return true;
// Both must be unsigned or both must be signed according to the
// InternalsVisibleToAttribute documentation.
if (PublicKeyBase.IsNullOrEmpty2(publicKey) != PublicKeyBase.IsNullOrEmpty2(targetAsm.PublicKey))
return false;
foreach (var ca in targetAsm.CustomAttributes.FindAll("System.Runtime.CompilerServices.InternalsVisibleToAttribute")) {
if (ca.ConstructorArguments.Count != 1)
continue;
var arg = ca.ConstructorArguments.Get(0, default(CAArgument));
if (arg.Type.GetElementType() != ElementType.String)
continue;
var asmName = arg.Value as UTF8String;
if (UTF8String.IsNull(asmName))
continue;
var asmInfo = new AssemblyNameInfo(asmName);
if (asmInfo.Name != name)
continue;
if (!PublicKeyBase.IsNullOrEmpty2(publicKey)) {
if (!PublicKey.Equals(asmInfo.PublicKeyOrToken as PublicKey))
continue;
}
else if (!PublicKeyBase.IsNullOrEmpty2(asmInfo.PublicKeyOrToken))
continue;
return true;
}
return false;
}
/// <summary>
/// Adds or updates an existing <c>System.Reflection.AssemblySignatureKeyAttribute</c>
/// attribute. This attribute is used in enhanced strong naming with key migration.
/// See http://msdn.microsoft.com/en-us/library/hh415055.aspx
/// </summary>
/// <param name="identityPubKey">Identity public key</param>
/// <param name="identityKey">Identity strong name key pair</param>
/// <param name="signaturePubKey">Signature public key</param>
public void UpdateOrCreateAssemblySignatureKeyAttribute(StrongNamePublicKey identityPubKey, StrongNameKey identityKey, StrongNamePublicKey signaturePubKey) {
var manifestModule = ManifestModule;
if (manifestModule == null)
return;
// Remove all existing attributes
var ca = CustomAttributes.ExecuteLocked<CustomAttribute, object, CustomAttribute>(null, (tsList, arg) => {
CustomAttribute foundCa = null;
for (int i = 0; i < tsList.Count_NoLock(); i++) {
var caTmp = tsList.Get_NoLock(i);
if (caTmp.TypeFullName != "System.Reflection.AssemblySignatureKeyAttribute")
continue;
tsList.RemoveAt_NoLock(i);
i--;
if (foundCa == null)
foundCa = caTmp;
}
return foundCa;
});
if (IsValidAssemblySignatureKeyAttribute(ca))
ca.NamedArguments.Clear();
else
ca = CreateAssemblySignatureKeyAttribute();
var counterSig = StrongNameKey.CreateCounterSignatureAsString(identityPubKey, identityKey, signaturePubKey);
ca.ConstructorArguments[0] = new CAArgument(manifestModule.CorLibTypes.String, new UTF8String(signaturePubKey.ToString()));
ca.ConstructorArguments[1] = new CAArgument(manifestModule.CorLibTypes.String, new UTF8String(counterSig));
CustomAttributes.Add(ca);
}
bool IsValidAssemblySignatureKeyAttribute(CustomAttribute ca) {
#if THREAD_SAFE
return false;
#else
if (ca == null)
return false;
var ctor = ca.Constructor;
if (ctor == null)
return false;
var sig = ctor.MethodSig;
if (sig == null || sig.Params.Count != 2)
return false;
if (sig.Params[0].GetElementType() != ElementType.String)
return false;
if (sig.Params[1].GetElementType() != ElementType.String)
return false;
if (ca.ConstructorArguments.Count != 2)
return false;
return true;
#endif
}
CustomAttribute CreateAssemblySignatureKeyAttribute() {
var manifestModule = ManifestModule;
var owner = manifestModule.UpdateRowId(new TypeRefUser(manifestModule, "System.Reflection", "AssemblySignatureKeyAttribute", manifestModule.CorLibTypes.AssemblyRef));
var methodSig = MethodSig.CreateInstance(manifestModule.CorLibTypes.Void, manifestModule.CorLibTypes.String, manifestModule.CorLibTypes.String);
var ctor = manifestModule.UpdateRowId(new MemberRefUser(manifestModule, MethodDef.InstanceConstructorName, methodSig, owner));
var ca = new CustomAttribute(ctor);
ca.ConstructorArguments.Add(new CAArgument(manifestModule.CorLibTypes.String, UTF8String.Empty));
ca.ConstructorArguments.Add(new CAArgument(manifestModule.CorLibTypes.String, UTF8String.Empty));
return ca;
}
/// <inheritdoc/>
void IListListener<ModuleDef>.OnLazyAdd(int index, ref ModuleDef module) {
if (module == null)
return;
#if DEBUG
if (module.Assembly == null)
throw new InvalidOperationException("Module.Assembly == null");
#endif
}
/// <inheritdoc/>
void IListListener<ModuleDef>.OnAdd(int index, ModuleDef module) {
if (module == null)
return;
if (module.Assembly != null)
throw new InvalidOperationException("Module already has an assembly. Remove it from that assembly before adding it to this assembly.");
module.Assembly = this;
}
/// <inheritdoc/>
void IListListener<ModuleDef>.OnRemove(int index, ModuleDef module) {
if (module != null)
module.Assembly = null;
}
/// <inheritdoc/>
void IListListener<ModuleDef>.OnResize(int index) {
}
/// <inheritdoc/>
void IListListener<ModuleDef>.OnClear() {
foreach (var module in Modules.GetEnumerable_NoLock()) {
if (module != null)
module.Assembly = null;
}
}
/// <inheritdoc/>
public override string ToString() {
return FullName;
}
}
/// <summary>
/// An Assembly row created by the user and not present in the original .NET file
/// </summary>
public class AssemblyDefUser : AssemblyDef {
/// <summary>
/// Default constructor
/// </summary>
public AssemblyDefUser()
: this(UTF8String.Empty, new Version(0, 0, 0, 0)) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyDefUser(UTF8String name)
: this(name, new Version(0, 0, 0, 0), new PublicKey()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <param name="version">Version</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyDefUser(UTF8String name, Version version)
: this(name, version, new PublicKey()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <param name="version">Version</param>
/// <param name="publicKey">Public key</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyDefUser(UTF8String name, Version version, PublicKey publicKey)
: this(name, version, publicKey, UTF8String.Empty) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">Simple name</param>
/// <param name="version">Version</param>
/// <param name="publicKey">Public key</param>
/// <param name="locale">Locale</param>
/// <exception cref="ArgumentNullException">If any of the args is invalid</exception>
public AssemblyDefUser(UTF8String name, Version version, PublicKey publicKey, UTF8String locale) {
if ((object)name == null)
throw new ArgumentNullException("name");
if (version == null)
throw new ArgumentNullException("version");
if ((object)locale == null)
throw new ArgumentNullException("locale");
this.modules = new LazyList<ModuleDef>(this);
this.name = name;
this.version = version;
this.publicKey = publicKey ?? new PublicKey();
this.culture = locale;
this.attributes = (int)AssemblyAttributes.None;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="asmName">Assembly name info</param>
/// <exception cref="ArgumentNullException">If <paramref name="asmName"/> is <c>null</c></exception>
public AssemblyDefUser(AssemblyName asmName)
: this(new AssemblyNameInfo(asmName)) {
this.hashAlgorithm = (AssemblyHashAlgorithm)asmName.HashAlgorithm;
this.attributes = (int)asmName.Flags;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="asmName">Assembly name info</param>
/// <exception cref="ArgumentNullException">If <paramref name="asmName"/> is <c>null</c></exception>
public AssemblyDefUser(IAssembly asmName) {
if (asmName == null)
throw new ArgumentNullException("asmName");
this.modules = new LazyList<ModuleDef>(this);
this.name = asmName.Name;
this.version = asmName.Version ?? new Version(0, 0, 0, 0);
this.publicKey = asmName.PublicKeyOrToken as PublicKey ?? new PublicKey();
this.culture = asmName.Culture;
this.attributes = (int)AssemblyAttributes.None;
this.hashAlgorithm = AssemblyHashAlgorithm.SHA1;
}
}
/// <summary>
/// Created from a row in the Assembly table
/// </summary>
sealed class AssemblyDefMD : AssemblyDef, IMDTokenProviderMD {
/// <summary>The module where this instance is located</summary>
readonly ModuleDefMD readerModule;
readonly uint origRid;
/// <inheritdoc/>
public uint OrigRid {
get { return origRid; }
}
/// <inheritdoc/>
protected override void InitializeDeclSecurities() {
var list = readerModule.MetaData.GetDeclSecurityRidList(Table.Assembly, origRid);
var tmp = new LazyList<DeclSecurity>((int)list.Length, list, (list2, index) => readerModule.ResolveDeclSecurity(((RidList)list2)[index]));
Interlocked.CompareExchange(ref declSecurities, tmp, null);
}
/// <inheritdoc/>
protected override void InitializeModules() {
var list = readerModule.GetModuleRidList();
var tmp = new LazyList<ModuleDef>((int)list.Length + 1, this, list, (list2, index) => {
ModuleDef module;
if (index == 0)
module = readerModule;
else
module = readerModule.ReadModule(((RidList)list2)[index - 1], this);
if (module == null)
module = new ModuleDefUser("INVALID", Guid.NewGuid());
module.Assembly = this;
return module;
});
Interlocked.CompareExchange(ref modules, tmp, null);
}
/// <inheritdoc/>
protected override void InitializeCustomAttributes() {
var list = readerModule.MetaData.GetCustomAttributeRidList(Table.Assembly, origRid);
var tmp = new CustomAttributeCollection((int)list.Length, list, (list2, index) => readerModule.ReadCustomAttribute(((RidList)list2)[index]));
Interlocked.CompareExchange(ref customAttributes, tmp, null);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">The module which contains this <c>Assembly</c> row</param>
/// <param name="rid">Row ID</param>
/// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception>
/// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception>
public AssemblyDefMD(ModuleDefMD readerModule, uint rid) {
#if DEBUG
if (readerModule == null)
throw new ArgumentNullException("readerModule");
if (readerModule.TablesStream.AssemblyTable.IsInvalidRID(rid))
throw new BadImageFormatException(string.Format("Assembly rid {0} does not exist", rid));
#endif
this.origRid = rid;
this.rid = rid;
this.readerModule = readerModule;
if (rid != 1)
this.modules = new LazyList<ModuleDef>(this);
uint publicKey, name;
uint culture = readerModule.TablesStream.ReadAssemblyRow(origRid, out this.hashAlgorithm, out this.version, out this.attributes, out publicKey, out name);
this.name = readerModule.StringsStream.ReadNoNull(name);
this.culture = readerModule.StringsStream.ReadNoNull(culture);
this.publicKey = new PublicKey(readerModule.BlobStream.Read(publicKey));
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Text;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
#nullable disable
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating BSON data.
/// </summary>
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonWriter : JsonWriter
{
private readonly BsonBinaryWriter _writer;
private BsonToken _root;
private BsonToken _parent;
private string _propertyName;
/// <summary>
/// Gets or sets the <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON.
/// When set to <see cref="DateTimeKind.Unspecified" /> no conversion will occur.
/// </summary>
/// <value>The <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON.</value>
public DateTimeKind DateTimeKindHandling
{
get => _writer.DateTimeKindHandling;
set => _writer.DateTimeKindHandling = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonWriter"/> class.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to write to.</param>
public BsonWriter(Stream stream)
{
ValidationUtils.ArgumentNotNull(stream, nameof(stream));
_writer = new BsonBinaryWriter(new BinaryWriter(stream));
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonWriter"/> class.
/// </summary>
/// <param name="writer">The <see cref="BinaryWriter"/> to write to.</param>
public BsonWriter(BinaryWriter writer)
{
ValidationUtils.ArgumentNotNull(writer, nameof(writer));
_writer = new BsonBinaryWriter(writer);
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying <see cref="Stream"/> and also flushes the underlying stream.
/// </summary>
public override void Flush()
{
_writer.Flush();
}
/// <summary>
/// Writes the end.
/// </summary>
/// <param name="token">The token.</param>
protected override void WriteEnd(JsonToken token)
{
base.WriteEnd(token);
RemoveParent();
if (Top == 0)
{
_writer.WriteToken(_root);
}
}
/// <summary>
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
{
throw JsonWriterException.Create(this, "Cannot write JSON comment as BSON.", null);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public override void WriteStartConstructor(string name)
{
throw JsonWriterException.Create(this, "Cannot write JSON constructor as BSON.", null);
}
/// <summary>
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
{
throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRawValue(string json)
{
throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public override void WriteStartArray()
{
base.WriteStartArray();
AddParent(new BsonArray());
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public override void WriteStartObject()
{
base.WriteStartObject();
AddParent(new BsonObject());
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public override void WritePropertyName(string name)
{
base.WritePropertyName(name);
_propertyName = name;
}
/// <summary>
/// Closes this writer.
/// If <see cref="JsonWriter.CloseOutput"/> is set to <c>true</c>, the underlying <see cref="Stream"/> is also closed.
/// If <see cref="JsonWriter.AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseOutput)
{
_writer?.Close();
}
}
private void AddParent(BsonToken container)
{
AddToken(container);
_parent = container;
}
private void RemoveParent()
{
_parent = _parent.Parent;
}
private void AddValue(object value, BsonType type)
{
AddToken(new BsonValue(value, type));
}
internal void AddToken(BsonToken token)
{
if (_parent != null)
{
if (_parent is BsonObject bo)
{
bo.Add(_propertyName, token);
_propertyName = null;
}
else
{
((BsonArray)_parent).Add(token);
}
}
else
{
if (token.Type != BsonType.Object && token.Type != BsonType.Array)
{
throw JsonWriterException.Create(this, "Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type), null);
}
_parent = token;
_root = token;
}
}
#region WriteValue methods
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object value)
{
#if HAVE_BIG_INTEGER
if (value is BigInteger i)
{
SetWriteState(JsonToken.Integer, null);
AddToken(new BsonBinary(i.ToByteArray(), BsonBinaryType.Binary));
}
else
#endif
{
base.WriteValue(value);
}
}
/// <summary>
/// Writes a null value.
/// </summary>
public override void WriteNull()
{
base.WriteNull();
AddToken(BsonEmpty.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public override void WriteUndefined()
{
base.WriteUndefined();
AddToken(BsonEmpty.Undefined);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string value)
{
base.WriteValue(value);
AddToken(value == null ? BsonEmpty.Null : new BsonString(value, true));
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public override void WriteValue(int value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(uint value)
{
if (value > int.MaxValue)
{
throw JsonWriterException.Create(this, "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.", null);
}
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public override void WriteValue(long value)
{
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(ulong value)
{
if (value > long.MaxValue)
{
throw JsonWriterException.Create(this, "Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.", null);
}
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public override void WriteValue(float value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public override void WriteValue(double value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public override void WriteValue(bool value)
{
base.WriteValue(value);
AddToken(value ? BsonBoolean.True : BsonBoolean.False);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public override void WriteValue(short value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(ushort value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public override void WriteValue(char value)
{
base.WriteValue(value);
string s = null;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
s = value.ToString(CultureInfo.InvariantCulture);
#else
s = value.ToString();
#endif
AddToken(new BsonString(s, true));
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public override void WriteValue(byte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(sbyte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public override void WriteValue(decimal value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public override void WriteValue(DateTime value)
{
base.WriteValue(value);
value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);
AddValue(value, BsonType.Date);
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public override void WriteValue(DateTimeOffset value)
{
base.WriteValue(value);
AddValue(value, BsonType.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public override void WriteValue(byte[] value)
{
if (value == null)
{
WriteNull();
return;
}
base.WriteValue(value);
AddToken(new BsonBinary(value, BsonBinaryType.Binary));
}
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public override void WriteValue(Guid value)
{
base.WriteValue(value);
AddToken(new BsonBinary(value.ToByteArray(), BsonBinaryType.Uuid));
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public override void WriteValue(TimeSpan value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri value)
{
if (value == null)
{
WriteNull();
return;
}
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
#endregion
/// <summary>
/// Writes a <see cref="Byte"/>[] value that represents a BSON object id.
/// </summary>
/// <param name="value">The Object ID value to write.</param>
public void WriteObjectId(byte[] value)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value.Length != 12)
{
throw JsonWriterException.Create(this, "An object id must be 12 bytes", null);
}
// hack to update the writer state
SetWriteState(JsonToken.Undefined, null);
AddValue(value, BsonType.Oid);
}
/// <summary>
/// Writes a BSON regex.
/// </summary>
/// <param name="pattern">The regex pattern.</param>
/// <param name="options">The regex options.</param>
public void WriteRegex(string pattern, string options)
{
ValidationUtils.ArgumentNotNull(pattern, nameof(pattern));
// hack to update the writer state
SetWriteState(JsonToken.Undefined, null);
AddToken(new BsonRegex(pattern, options));
}
}
}
| |
/****************************************************************************
Copyright (c) 2010 cocos2d-x.org
Copyright (c) 2011-2012 openxlive.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.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using System.Globalization;
using System;
#if !WINDOWS_PHONE && !WINDOWS &&!NETFX_CORE
#if MACOS
using MonoMac.OpenGL;
#elif WINDOWSGL || LINUX
using OpenTK.Graphics.OpenGL;
#else
using OpenTK.Graphics.ES20;
using BeginMode = OpenTK.Graphics.ES20.All;
using EnableCap = OpenTK.Graphics.ES20.All;
using TextureTarget = OpenTK.Graphics.ES20.All;
using BufferTarget = OpenTK.Graphics.ES20.All;
using BufferUsageHint = OpenTK.Graphics.ES20.All;
using DrawElementsType = OpenTK.Graphics.ES20.All;
using GetPName = OpenTK.Graphics.ES20.All;
using FramebufferErrorCode = OpenTK.Graphics.ES20.All;
using FramebufferTarget = OpenTK.Graphics.ES20.All;
using FramebufferAttachment = OpenTK.Graphics.ES20.All;
using RenderbufferTarget = OpenTK.Graphics.ES20.All;
using RenderbufferStorage = OpenTK.Graphics.ES20.All;
#endif
#endif
namespace CocosSharp
{
internal class CCUtils
{
#if !WINDOWS_PHONE
#if OPENGL
static List<string> GLExtensions = null;
public static List<string> GetGLExtensions()
{
// Setup extensions.
if(GLExtensions == null) {
List<string> extensions = new List<string>();
#if GLES
var extstring = GL.GetString(RenderbufferStorage.Extensions);
CheckGLError();
#elif MACOS
// for right now there are errors with GL before we even get here so the
// CheckGLError for MACOS is throwing errors even though the extensions are read
// correctly. Placed this here for now so that we can continue the processing
// until we find the real error.
var extstring = GL.GetString(StringName.Extensions);
#else
var extstring = GL.GetString(StringName.Extensions);
CheckGLError();
#endif
if (!string.IsNullOrEmpty(extstring))
{
extensions.AddRange(extstring.Split(' '));
CCLog.Log("Supported GL extensions:");
foreach (string extension in extensions)
CCLog.Log(extension);
}
GLExtensions = extensions;
}
return GLExtensions;
}
public static void CheckGLError()
{
#if GLES && (!ANGLE && !IOS)
All error = GL.GetError();
if (error != All.False)
throw new Exception("GL.GetError() returned " + error.ToString());
#elif OPENGL
var error = GL.GetError();
if (error != ErrorCode.NoError)
throw new Exception("GL.GetError() returned " + error.ToString());
#endif
}
#endif
#endif
/// <summary>
/// Returns the Cardinal Spline position for a given set of control points, tension and time
/// </summary>
/// <param name="p0"></param>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <param name="p3"></param>
/// <param name="tension"></param>
/// <param name="t"></param>
/// <returns></returns>
public static CCPoint CCCardinalSplineAt(CCPoint p0, CCPoint p1, CCPoint p2, CCPoint p3, float tension, float t)
{
float t2 = t * t;
float t3 = t2 * t;
/*
* Formula: s(-ttt + 2tt - t)P1 + s(-ttt + tt)P2 + (2ttt - 3tt + 1)P2 + s(ttt - 2tt + t)P3 + (-2ttt + 3tt)P3 + s(ttt - tt)P4
*/
float s = (1 - tension) / 2;
float b1 = s * ((-t3 + (2 * t2)) - t); // s(-t3 + 2 t2 - t)P1
float b2 = s * (-t3 + t2) + (2 * t3 - 3 * t2 + 1); // s(-t3 + t2)P2 + (2 t3 - 3 t2 + 1)P2
float b3 = s * (t3 - 2 * t2 + t) + (-2 * t3 + 3 * t2); // s(t3 - 2 t2 + t)P3 + (-2 t3 + 3 t2)P3
float b4 = s * (t3 - t2); // s(t3 - t2)P4
float x = (p0.X * b1 + p1.X * b2 + p2.X * b3 + p3.X * b4);
float y = (p0.Y * b1 + p1.Y * b2 + p2.Y * b3 + p3.Y * b4);
return new CCPoint(x, y);
}
/// <summary>
/// Parses an int value using the default number style and the invariant culture parser.
/// </summary>
/// <param name="toParse">The value to parse</param>
/// <returns>The int value of the string</returns>
public static int CCParseInt(string toParse)
{
// http://www.cocos2d-x.org/boards/17/topics/11690
// Issue #17
// https://github.com/cocos2d/cocos2d-x-for-xna/issues/17
return int.Parse(toParse, CultureInfo.InvariantCulture);
}
/// <summary>
/// Parses aint value for the given string using the given number style and using
/// the invariant culture parser.
/// </summary>
/// <param name="toParse">The value to parse.</param>
/// <param name="ns">The number style used to parse the int value.</param>
/// <returns>The int value of the string.</returns>
public static int CCParseInt(string toParse, NumberStyles ns)
{
// http://www.cocos2d-x.org/boards/17/topics/11690
// Issue #17
// https://github.com/cocos2d/cocos2d-x-for-xna/issues/17
return int.Parse(toParse, ns, CultureInfo.InvariantCulture);
}
/// <summary>
/// Parses a float value using the default number style and the invariant culture parser.
/// </summary>
/// <param name="toParse">The value to parse</param>
/// <returns>The float value of the string.</returns>
public static float CCParseFloat(string toParse)
{
// http://www.cocos2d-x.org/boards/17/topics/11690
// Issue #17
// https://github.com/cocos2d/cocos2d-x-for-xna/issues/17
return float.Parse(toParse, CultureInfo.InvariantCulture);
}
/// <summary>
/// Parses a float value for the given string using the given number style and using
/// the invariant culture parser.
/// </summary>
/// <param name="toParse">The value to parse.</param>
/// <param name="ns">The number style used to parse the float value.</param>
/// <returns>The float value of the string.</returns>
public static float CCParseFloat(string toParse, NumberStyles ns)
{
// http://www.cocos2d-x.org/boards/17/topics/11690
// https://github.com/cocos2d/cocos2d-x-for-xna/issues/17
return float.Parse(toParse, ns, CultureInfo.InvariantCulture);
}
/// <summary>
/// Returns the next Power of Two for the given value. If x = 3, then this returns 4.
/// If x = 4 then 4 is returned. If the value is a power of two, then the same value
/// is returned.
/// </summary>
/// <param name="x">The base of the POT test</param>
/// <returns>The next power of 2 (1, 2, 4, 8, 16, 32, 64, 128, etc)</returns>
public static long CCNextPOT(long x)
{
x = x - 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return x + 1;
}
/// <summary>
/// Returns the next Power of Two for the given value. If x = 3, then this returns 4.
/// If x = 4 then 4 is returned. If the value is a power of two, then the same value
/// is returned.
/// </summary>
/// <param name="x">The base of the POT test</param>
/// <returns>The next power of 2 (1, 2, 4, 8, 16, 32, 64, 128, etc)</returns>
public static int CCNextPOT(int x)
{
x = x - 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return x + 1;
}
public static void Split(string src, string token, List<string> vect)
{
int nend = 0;
int nbegin = 0;
while (nend != -1)
{
nend = src.IndexOf(token, nbegin);
if (nend == -1)
vect.Add(src.Substring(nbegin, src.Length - nbegin));
else
vect.Add(src.Substring(nbegin, nend - nbegin));
nbegin = nend + token.Length;
}
}
// first, judge whether the form of the string like this: {x,y}
// if the form is right,the string will be splited into the parameter strs;
// or the parameter strs will be empty.
// if the form is right return true,else return false.
public static bool SplitWithForm(string pStr, List<string> strs)
{
bool bRet = false;
do
{
if (pStr == null)
{
break;
}
// string is empty
string content = pStr;
if (content.Length == 0)
{
break;
}
int nPosLeft = content.IndexOf('{');
int nPosRight = content.IndexOf('}');
// don't have '{' and '}'
if (nPosLeft == -1 || nPosRight == -1)
{
break;
}
// '}' is before '{'
if (nPosLeft > nPosRight)
{
break;
}
string pointStr = content.Substring(nPosLeft + 1, nPosRight - nPosLeft - 1);
// nothing between '{' and '}'
if (pointStr.Length == 0)
{
break;
}
int nPos1 = pointStr.IndexOf('{');
int nPos2 = pointStr.IndexOf('}');
// contain '{' or '}'
if (nPos1 != -1 || nPos2 != -1) break;
Split(pointStr, ",", strs);
if (strs.Count != 2 || strs[0].Length == 0 || strs[1].Length == 0)
{
strs.Clear();
break;
}
bRet = true;
} while (false);
return bRet;
}
}
}
| |
// 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.Concurrent;
using System.Data.Common;
using System.Diagnostics;
namespace System.Data.ProviderBase
{
// set_ConnectionString calls DbConnectionFactory.GetConnectionPoolGroup
// when not found a new pool entry is created and potentially added
// DbConnectionPoolGroup starts in the Active state
// Open calls DbConnectionFactory.GetConnectionPool
// if the existing pool entry is Disabled, GetConnectionPoolGroup is called for a new entry
// DbConnectionFactory.GetConnectionPool calls DbConnectionPoolGroup.GetConnectionPool
// DbConnectionPoolGroup.GetConnectionPool will return pool for the current identity
// or null if identity is restricted or pooling is disabled or state is disabled at time of add
// state changes are Active->Active, Idle->Active
// DbConnectionFactory.PruneConnectionPoolGroups calls Prune
// which will QueuePoolForRelease on all empty pools
// and once no pools remain, change state from Active->Idle->Disabled
// Once Disabled, factory can remove its reference to the pool entry
internal sealed class DbConnectionPoolGroup
{
private readonly DbConnectionOptions _connectionOptions;
private readonly DbConnectionPoolKey _poolKey;
private readonly DbConnectionPoolGroupOptions _poolGroupOptions;
private ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> _poolCollection;
private int _state; // see PoolGroupState* below
private DbConnectionPoolGroupProviderInfo _providerInfo;
private DbMetaDataFactory _metaDataFactory;
// always lock this before changing _state, we don't want to move out of the 'Disabled' state
// PoolGroupStateUninitialized = 0;
private const int PoolGroupStateActive = 1; // initial state, GetPoolGroup from cache, connection Open
private const int PoolGroupStateIdle = 2; // all pools are pruned via Clear
private const int PoolGroupStateDisabled = 4; // factory pool entry pruning method
internal DbConnectionPoolGroup(DbConnectionOptions connectionOptions, DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolGroupOptions)
{
Debug.Assert(null != connectionOptions, "null connection options");
_connectionOptions = connectionOptions;
_poolKey = key;
_poolGroupOptions = poolGroupOptions;
// always lock this object before changing state
// HybridDictionary does not create any sub-objects until add
// so it is safe to use for non-pooled connection as long as
// we check _poolGroupOptions first
_poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
_state = PoolGroupStateActive;
}
internal DbConnectionOptions ConnectionOptions => _connectionOptions;
internal DbConnectionPoolKey PoolKey => _poolKey;
internal DbConnectionPoolGroupProviderInfo ProviderInfo
{
get
{
return _providerInfo;
}
set
{
_providerInfo = value;
if (null != value)
{
_providerInfo.PoolGroup = this;
}
}
}
internal bool IsDisabled => (PoolGroupStateDisabled == _state);
internal DbConnectionPoolGroupOptions PoolGroupOptions => _poolGroupOptions;
internal DbMetaDataFactory MetaDataFactory
{
get
{
return _metaDataFactory;
}
set
{
_metaDataFactory = value;
}
}
internal int Clear()
{
// must be multi-thread safe with competing calls by Clear and Prune via background thread
// will return the number of connections in the group after clearing has finished
// First, note the old collection and create a new collection to be used
ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool> oldPoolCollection = null;
lock (this)
{
if (_poolCollection.Count > 0)
{
oldPoolCollection = _poolCollection;
_poolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
}
}
// Then, if a new collection was created, release the pools from the old collection
if (oldPoolCollection != null)
{
foreach (var entry in oldPoolCollection)
{
DbConnectionPool pool = entry.Value;
if (pool != null)
{
DbConnectionFactory connectionFactory = pool.ConnectionFactory;
connectionFactory.QueuePoolForRelease(pool, true);
}
}
}
// Finally, return the pool collection count - this may be non-zero if something was added while we were clearing
return _poolCollection.Count;
}
internal DbConnectionPool GetConnectionPool(DbConnectionFactory connectionFactory)
{
// When this method returns null it indicates that the connection
// factory should not use pooling.
// We don't support connection pooling on Win9x;
// PoolGroupOptions will only be null when we're not supposed to pool
// connections.
DbConnectionPool pool = null;
if (null != _poolGroupOptions)
{
DbConnectionPoolIdentity currentIdentity = DbConnectionPoolIdentity.NoIdentity;
if (_poolGroupOptions.PoolByIdentity)
{
// if we're pooling by identity (because integrated security is
// being used for these connections) then we need to go out and
// search for the connectionPool that matches the current identity.
currentIdentity = DbConnectionPoolIdentity.GetCurrent();
// If the current token is restricted in some way, then we must
// not attempt to pool these connections.
if (currentIdentity.IsRestricted)
{
currentIdentity = null;
}
}
if (null != currentIdentity)
{
if (!_poolCollection.TryGetValue(currentIdentity, out pool)) // find the pool
{
lock (this)
{
// Did someone already add it to the list?
if (!_poolCollection.TryGetValue(currentIdentity, out pool))
{
DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions);
DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo);
if (MarkPoolGroupAsActive())
{
// If we get here, we know for certain that we there isn't
// a pool that matches the current identity, so we have to
// add the optimistically created one
newPool.Startup(); // must start pool before usage
bool addResult = _poolCollection.TryAdd(currentIdentity, newPool);
Debug.Assert(addResult, "No other pool with current identity should exist at this point");
pool = newPool;
}
else
{
// else pool entry has been disabled so don't create new pools
Debug.Assert(PoolGroupStateDisabled == _state, "state should be disabled");
// don't need to call connectionFactory.QueuePoolForRelease(newPool) because
// pool callbacks were delayed and no risk of connections being created
newPool.Shutdown();
}
}
else
{
// else found an existing pool to use instead
Debug.Assert(PoolGroupStateActive == _state, "state should be active since a pool exists and lock holds");
}
}
}
// the found pool could be in any state
}
}
if (null == pool)
{
lock (this)
{
// keep the pool entry state active when not pooling
MarkPoolGroupAsActive();
}
}
return pool;
}
private bool MarkPoolGroupAsActive()
{
// when getting a connection, make the entry active if it was idle (but not disabled)
// must always lock this before calling
if (PoolGroupStateIdle == _state)
{
_state = PoolGroupStateActive;
}
return (PoolGroupStateActive == _state);
}
internal bool Prune()
{
// must only call from DbConnectionFactory.PruneConnectionPoolGroups on background timer thread
// must lock(DbConnectionFactory._connectionPoolGroups.SyncRoot) before calling ReadyToRemove
// to avoid conflict with DbConnectionFactory.CreateConnectionPoolGroup replacing pool entry
lock (this)
{
if (_poolCollection.Count > 0)
{
var newPoolCollection = new ConcurrentDictionary<DbConnectionPoolIdentity, DbConnectionPool>();
foreach (var entry in _poolCollection)
{
DbConnectionPool pool = entry.Value;
if (pool != null)
{
// Actually prune the pool if there are no connections in the pool and no errors occurred.
// Empty pool during pruning indicates zero or low activity, but
// an error state indicates the pool needs to stay around to
// throttle new connection attempts.
if ((!pool.ErrorOccurred) && (0 == pool.Count))
{
// Order is important here. First we remove the pool
// from the collection of pools so no one will try
// to use it while we're processing and finally we put the
// pool into a list of pools to be released when they
// are completely empty.
DbConnectionFactory connectionFactory = pool.ConnectionFactory;
connectionFactory.QueuePoolForRelease(pool, false);
}
else
{
newPoolCollection.TryAdd(entry.Key, entry.Value);
}
}
}
_poolCollection = newPoolCollection;
}
// must be pruning thread to change state and no connections
// otherwise pruning thread risks making entry disabled soon after user calls ClearPool
if (0 == _poolCollection.Count)
{
if (PoolGroupStateActive == _state)
{
_state = PoolGroupStateIdle;
}
else if (PoolGroupStateIdle == _state)
{
_state = PoolGroupStateDisabled;
}
}
return (PoolGroupStateDisabled == _state);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System;
using System.Diagnostics.Contracts;
namespace System.Text
{
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
// calls to the GetChars method. The decoder maintains state between the
// conversions, allowing it to correctly decode byte sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Decoder abstract base
// class are typically obtained through calls to the GetDecoder method
// of Encoding objects.
//
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class Decoder
{
internal DecoderFallback m_fallback = null;
internal DecoderFallbackBuffer m_fallbackBuffer = null;
protected Decoder()
{
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
[System.Runtime.InteropServices.ComVisible(false)]
public DecoderFallback Fallback
{
get
{
return m_fallback;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
// Can't change fallback if buffer is wrong
if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
throw new ArgumentException(
SR.Argument_FallbackBufferNotEmpty, "value");
m_fallback = value;
m_fallbackBuffer = null;
}
}
// Note: we don't test for threading here because async access to Encoders and Decoders
// doesn't work anyway.
[System.Runtime.InteropServices.ComVisible(false)]
public DecoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
// Reset the Decoder
//
// Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This
// would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
//
// If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset().
//
// Virtual implimentation has to call GetChars with flush and a big enough buffer to clear a 0 byte string
// We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big.
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Reset()
{
byte[] byteTemp = { };
char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)];
GetChars(byteTemp, 0, 0, charTemp, 0, true);
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
// Returns the number of characters the next call to GetChars will
// produce if presented with the given range of bytes. The returned value
// takes into account the state in which the decoder was left following the
// last call to GetChars. The state of the decoder is not affected
// by a call to this method.
//
public abstract int GetCharCount(byte[] bytes, int index, int count);
[System.Runtime.InteropServices.ComVisible(false)]
public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
return GetCharCount(bytes, index, count);
}
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implementation)
[System.Security.SecurityCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
internal virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
{
// Validate input parameters
if (bytes == null)
throw new ArgumentNullException("bytes",
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException("count",
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
byte[] arrbyte = new byte[count];
int index;
for (index = 0; index < count; index++)
arrbyte[index] = bytes[index];
return GetCharCount(arrbyte, 0, count);
}
// Decodes a range of bytes in a byte array into a range of characters
// in a character array. The method decodes byteCount bytes from
// bytes starting at index byteIndex, storing the resulting
// characters in chars starting at index charIndex. The
// decoding takes into account the state in which the decoder was left
// following the last call to this method.
//
// An exception occurs if the character array is not large enough to
// hold the complete decoding of the bytes. The GetCharCount method
// can be used to determine the exact number of characters that will be
// produced for a given range of bytes. Alternatively, the
// GetMaxCharCount method of the Encoding that produced this
// decoder can be used to determine the maximum number of characters that
// will be produced for a given number of bytes, regardless of the actual
// byte values.
//
public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex);
public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
return GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
// We expect this to be the workhorse for NLS Encodings, but for existing
// ones we need a working (if slow) default implimentation)
//
// WARNING WARNING WARNING
//
// WARNING: If this breaks it could be a security threat. Obviously we
// call this internally, so you need to make sure that your pointers, counts
// and indexes are correct when you call this method.
//
// In addition, we have internal code, which will be marked as "safe" calling
// this code. However this code is dependent upon the implimentation of an
// external GetChars() method, which could be overridden by a third party and
// the results of which cannot be guaranteed. We use that result to copy
// the char[] to our char* output buffer. If the result count was wrong, we
// could easily overflow our output buffer. Therefore we do an extra test
// when we copy the buffer so that we don't overflow charCount either.
[System.Security.SecurityCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
internal virtual unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, bool flush)
{
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? "chars" : "bytes",
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Get the byte array to convert
byte[] arrByte = new byte[byteCount];
int index;
for (index = 0; index < byteCount; index++)
arrByte[index] = bytes[index];
// Get the char array to fill
char[] arrChar = new char[charCount];
// Do the work
int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
// The only way this could fail is a bug in GetChars
Contract.Assert(result <= charCount, "Returned more chars than we have space for");
// Copy the char array
// WARNING: We MUST make sure that we don't copy too many chars. We can't
// rely on result because it could be a 3rd party implimentation. We need
// to make sure we never copy more than charCount chars no matter the value
// of result
if (result < charCount)
charCount = result;
// We check both result and charCount so that we don't accidentally overrun
// our pointer buffer just because of any GetChars bug.
for (index = 0; index < charCount; index++)
chars[index] = arrChar[index];
return charCount;
}
// This method is used when the output buffer might not be large enough.
// It will decode until it runs out of bytes, and then it will return
// true if it the entire input was converted. In either case it
// will also return the number of converted bytes and output characters used.
// It will only throw a buffer overflow exception if the entire lenght of chars[] is
// too small to store the next char. (like 0 or maybe 1 or 4 for some encodings)
// We're done processing this buffer only if completed returns true.
//
// Might consider checking Max...Count to avoid the extra counting step.
//
// Note that if all of the input bytes are not consumed, then we'll do a /2, which means
// that its likely that we didn't consume as many bytes as we could have. For some
// applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? "bytes" : "chars"),
SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException("bytes",
SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException("chars",
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
bytesUsed = byteCount;
// Its easy to do if it won't overrun our buffer.
while (bytesUsed > 0)
{
if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount)
{
charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush);
completed = (bytesUsed == byteCount &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
return;
}
// Try again with 1/2 the count, won't flush then 'cause won't read it all
flush = false;
bytesUsed /= 2;
}
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(SR.Argument_ConversionOverflow);
}
}
}
| |
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 InvestmentApi.Web.Areas.HelpPage.ModelDescriptions;
using InvestmentApi.Web.Areas.HelpPage.Models;
namespace InvestmentApi.Web.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);
}
}
}
}
| |
/*
* Copyright 2013 Splunk, 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.
*/
namespace Splunk.Client.AcceptanceTests
{
using Splunk.Client;
using Splunk.Client.Helpers;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
/// <summary>
/// Application tests
/// </summary>
public class ApplicationTest
{
/// <summary>
/// The app tests
/// </summary>
[Trait("acceptance-test", "Splunk.Client.Application")]
[MockContext]
[Fact]
public async Task Application()
{
using (var service = await SdkHelper.CreateService())
{
ApplicationCollection apps = service.Applications;
await apps.GetAllAsync();
foreach (Application app in apps)
{
await CheckApplication(app);
}
for (int i = 0; i < apps.Count; i++)
{
await CheckApplication(apps[i]);
}
if (await service.Applications.RemoveAsync("sdk-tests"))
{
await service.Server.RestartAsync(2 * 60 * 1000);
await service.LogOnAsync();
}
ApplicationAttributes attributes = new ApplicationAttributes
{
ApplicationAuthor = "me",
Description = "this is a description",
Label = "SDKTEST",
Visible = false
};
var testApp = await service.Applications.CreateAsync("sdk-tests", "barebones", attributes);
testApp = await service.Applications.GetAsync("sdk-tests");
Assert.Equal("SDKTEST", testApp.Label);
Assert.Equal("me", testApp.ApplicationAuthor);
Assert.Equal("nobody", testApp.Author);
Assert.False(testApp.Configured);
Assert.False(testApp.Visible);
Assert.DoesNotThrow(() =>
{
bool p = testApp.CheckForUpdates;
});
attributes = new ApplicationAttributes
{
ApplicationAuthor = "not me",
Description = "new description",
Label = "new label",
Visible = false,
Version = "1.5"
};
//// Update the application
await testApp.UpdateAsync(attributes, true);
await testApp.GetAsync();
Assert.Equal("not me", testApp.ApplicationAuthor);
Assert.Equal("nobody", testApp.Author);
Assert.Equal("new description", testApp.Description);
Assert.Equal("new label", testApp.Label);
Assert.Equal("1.5", testApp.Version);
Assert.False(testApp.Visible);
ApplicationUpdateInfo updateInfo = await testApp.GetUpdateInfoAsync();
Assert.NotNull(updateInfo.Eai.Acl);
//// Package the application
ApplicationArchiveInfo archiveInfo = await testApp.PackageAsync();
Assert.Equal("Package", archiveInfo.Title);
Assert.NotEqual(DateTime.MinValue, archiveInfo.Updated);
Assert.DoesNotThrow(() =>
{
string p = archiveInfo.ApplicationName;
});
Assert.True(archiveInfo.ApplicationName.Length > 0);
Assert.DoesNotThrow(() =>
{
Eai p = archiveInfo.Eai;
});
Assert.NotNull(archiveInfo.Eai);
Assert.NotNull(archiveInfo.Eai.Acl);
Assert.DoesNotThrow(() =>
{
string p = archiveInfo.Path;
});
Assert.True(archiveInfo.Path.Length > 0);
Assert.DoesNotThrow(() =>
{
bool p = archiveInfo.Refresh;
});
Assert.DoesNotThrow(() =>
{
Uri p = archiveInfo.Uri;
});
Assert.True(archiveInfo.Uri.AbsolutePath.Length > 0);
Assert.True(await service.Applications.RemoveAsync("sdk-tests"));
await service.Server.RestartAsync(2 * 60 * 1000);
}
}
#region Privates/internals
internal async Task CheckApplication(Application app)
{
ApplicationSetupInfo setupInfo = null;
try
{
setupInfo = await app.GetSetupInfoAsync();
//// TODO: Install an app which hits this code before this test runs
Assert.NotNull(setupInfo.Eai);
Assert.DoesNotThrow(() => { bool p = setupInfo.Refresh; });
}
catch (InternalServerErrorException e)
{
Assert.Contains("Internal Server Error", e.Message);
}
ApplicationArchiveInfo archiveInfo = await app.PackageAsync();
Assert.DoesNotThrow(() =>
{
string p = app.Author;
Assert.NotNull(p);
});
Assert.DoesNotThrow(() => { string p = app.ApplicationAuthor; });
Assert.DoesNotThrow(() => { bool p = app.CheckForUpdates; });
Assert.DoesNotThrow(() => { string p = app.Description; });
Assert.DoesNotThrow(() => { string p = app.Label; });
Assert.DoesNotThrow(() => { bool p = app.Refresh; });
Assert.DoesNotThrow(() => { string p = app.Version; });
Assert.DoesNotThrow(() => { bool p = app.Configured; });
Assert.DoesNotThrow(() => { bool p = app.StateChangeRequiresRestart; });
Assert.DoesNotThrow(() => { bool p = app.Visible; });
ApplicationUpdateInfo updateInfo = await app.GetUpdateInfoAsync();
Assert.NotNull(updateInfo.Eai);
if (updateInfo.Update != null)
{
var update = updateInfo.Update;
Assert.DoesNotThrow(() =>
{
string p = updateInfo.Update.ApplicationName;
});
Assert.DoesNotThrow(() =>
{
Uri p = updateInfo.Update.ApplicationUri;
});
Assert.DoesNotThrow(() =>
{
string p = updateInfo.Update.ApplicationName;
});
Assert.DoesNotThrow(() =>
{
string p = updateInfo.Update.ChecksumType;
});
Assert.DoesNotThrow(() =>
{
string p = updateInfo.Update.Homepage;
});
Assert.DoesNotThrow(() =>
{
bool p = updateInfo.Update.ImplicitIdRequired;
});
Assert.DoesNotThrow(() =>
{
long p = updateInfo.Update.Size;
});
Assert.DoesNotThrow(() =>
{
string p = updateInfo.Update.Version;
});
}
Assert.DoesNotThrow(() => { DateTime p = updateInfo.Updated; });
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableListTest : ImmutableListTestBase
{
private enum Operation
{
Add,
AddRange,
Insert,
InsertRange,
RemoveAt,
RemoveRange,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new List<int>();
var actual = ImmutableList<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the list.", value);
expected.Add(value);
actual = actual.Add(value);
VerifyBalanced(actual);
break;
case Operation.AddRange:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the list.", inputLength);
expected.AddRange(values);
actual = actual.AddRange(values);
VerifyBalanced(actual);
break;
case Operation.Insert:
int position = random.Next(expected.Count + 1);
value = random.Next();
Debug.WriteLine("Adding \"{0}\" to position {1} in the list.", value, position);
expected.Insert(position, value);
actual = actual.Insert(position, value);
VerifyBalanced(actual);
break;
case Operation.InsertRange:
inputLength = random.Next(100);
values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
position = random.Next(expected.Count + 1);
Debug.WriteLine("Adding {0} elements to position {1} in the list.", inputLength, position);
expected.InsertRange(position, values);
actual = actual.InsertRange(position, values);
VerifyBalanced(actual);
break;
case Operation.RemoveAt:
if (expected.Count > 0)
{
position = random.Next(expected.Count);
Debug.WriteLine("Removing element at position {0} from the list.", position);
expected.RemoveAt(position);
actual = actual.RemoveAt(position);
VerifyBalanced(actual);
}
break;
case Operation.RemoveRange:
position = random.Next(expected.Count);
inputLength = random.Next(expected.Count - position);
Debug.WriteLine("Removing {0} elements starting at position {1} from the list.", inputLength, position);
expected.RemoveRange(position, inputLength);
actual = actual.RemoveRange(position, inputLength);
VerifyBalanced(actual);
break;
}
Assert.Equal<int>(expected, actual);
}
}
[Fact]
public void EmptyTest()
{
var empty = ImmutableList<GenericParameterHelper>.Empty;
Assert.Same(empty, ImmutableList<GenericParameterHelper>.Empty);
Assert.Same(empty, empty.Clear());
Assert.Same(empty, ((IImmutableList<GenericParameterHelper>)empty).Clear());
Assert.True(empty.IsEmpty);
Assert.Equal(0, empty.Count);
Assert.Equal(-1, empty.IndexOf(new GenericParameterHelper()));
Assert.Equal(-1, empty.IndexOf(null));
}
[Fact]
public void GetHashCodeVariesByInstance()
{
Assert.NotEqual(ImmutableList.Create<int>().GetHashCode(), ImmutableList.Create(5).GetHashCode());
}
[Fact]
public void AddAndIndexerTest()
{
var list = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
Assert.False(list.IsEmpty);
Assert.Equal(i, list.Count);
}
for (int i = 1; i <= 10; i++)
{
Assert.Equal(i * 10, list[i - 1]);
}
var bulkList = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10).Select(i => i * 10));
Assert.Equal<int>(list.ToArray(), bulkList.ToArray());
}
[Fact]
public void AddRangeTest()
{
var list = ImmutableList<int>.Empty;
list = list.AddRange(new[] { 1, 2, 3 });
list = list.AddRange(Enumerable.Range(4, 2));
list = list.AddRange(ImmutableList<int>.Empty.AddRange(new[] { 6, 7, 8 }));
list = list.AddRange(new int[0]);
list = list.AddRange(ImmutableList<int>.Empty.AddRange(Enumerable.Range(9, 1000)));
Assert.Equal(Enumerable.Range(1, 1008), list);
}
[Fact]
public void AddRangeOptimizationsTest()
{
// All these optimizations are tested based on filling an empty list.
var emptyList = ImmutableList.Create<string>();
// Adding an empty list to an empty list should yield the original list.
Assert.Same(emptyList, emptyList.AddRange(new string[0]));
// Adding a non-empty immutable list to an empty one should return the added list.
var nonEmptyListDefaultComparer = ImmutableList.Create("5");
Assert.Same(nonEmptyListDefaultComparer, emptyList.AddRange(nonEmptyListDefaultComparer));
// Adding a Builder instance to an empty list should be seen through.
var builderOfNonEmptyListDefaultComparer = nonEmptyListDefaultComparer.ToBuilder();
Assert.Same(nonEmptyListDefaultComparer, emptyList.AddRange(builderOfNonEmptyListDefaultComparer));
}
[Fact]
public void AddRangeBalanceTest()
{
int randSeed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
int expectedTotalSize = 0;
var list = ImmutableList<int>.Empty;
// Add some small batches, verifying balance after each
for (int i = 0; i < 128; i++)
{
int batchSize = random.Next(32);
Debug.WriteLine("Adding {0} elements to the list", batchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, batchSize));
VerifyBalanced(list);
expectedTotalSize += batchSize;
}
// Add a single large batch to the end
int largeBatchSize = random.Next(32768) + 32768;
Debug.WriteLine("Adding {0} elements to the list", largeBatchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, largeBatchSize));
VerifyBalanced(list);
expectedTotalSize += largeBatchSize;
Assert.Equal(Enumerable.Range(1, expectedTotalSize), list);
list.Root.VerifyHeightIsWithinTolerance();
}
[Fact]
public void InsertRangeRandomBalanceTest()
{
int randSeed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
var immutableList = ImmutableList.CreateBuilder<int>();
var list = new List<int>();
const int maxBatchSize = 32;
int valueCounter = 0;
for (int i = 0; i < 24; i++)
{
int startPosition = random.Next(list.Count + 1);
int length = random.Next(maxBatchSize + 1);
int[] values = new int[length];
for (int j = 0; j < length; j++)
{
values[j] = ++valueCounter;
}
immutableList.InsertRange(startPosition, values);
list.InsertRange(startPosition, values);
Assert.Equal(list, immutableList);
immutableList.Root.VerifyBalanced();
}
immutableList.Root.VerifyHeightIsWithinTolerance();
}
[Fact]
public void InsertTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(1, 5));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(-1, 5));
list = list.Insert(0, 10);
list = list.Insert(1, 20);
list = list.Insert(2, 30);
list = list.Insert(2, 25);
list = list.Insert(1, 15);
list = list.Insert(0, 5);
Assert.Equal(6, list.Count);
var expectedList = new[] { 5, 10, 15, 20, 25, 30 };
var actualList = list.ToArray();
Assert.Equal<int>(expectedList, actualList);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(7, 5));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(-1, 5));
}
[Fact]
public void InsertBalanceTest()
{
var list = ImmutableList.Create(1);
list = list.Insert(0, 2);
list = list.Insert(1, 3);
VerifyBalanced(list);
}
[Fact]
public void InsertRangeTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(1, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, new[] { 1 }));
list = list.InsertRange(0, new[] { 1, 4, 5 });
list = list.InsertRange(1, new[] { 2, 3 });
list = list.InsertRange(2, new int[0]);
Assert.Equal(Enumerable.Range(1, 5), list);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(6, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, new[] { 1 }));
}
[Fact]
public void InsertRangeImmutableTest()
{
var list = ImmutableList<int>.Empty;
var nonEmptyList = ImmutableList.Create(1);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(1, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, nonEmptyList));
list = list.InsertRange(0, ImmutableList.Create(1, 104, 105));
list = list.InsertRange(1, ImmutableList.Create(2, 3));
list = list.InsertRange(2, ImmutableList<int>.Empty);
list = list.InsertRange(3, ImmutableList<int>.Empty.InsertRange(0, Enumerable.Range(4, 100)));
Assert.Equal(Enumerable.Range(1, 105), list);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(106, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, nonEmptyList));
}
[Fact]
public void NullHandlingTest()
{
var list = ImmutableList<GenericParameterHelper>.Empty;
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
list = list.Add((GenericParameterHelper)null);
Assert.Equal(1, list.Count);
Assert.Null(list[0]);
Assert.True(list.Contains(null));
Assert.Equal(0, list.IndexOf(null));
list = list.Remove((GenericParameterHelper)null);
Assert.Equal(0, list.Count);
Assert.True(list.IsEmpty);
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
}
[Fact]
public void Remove_NullEqualityComparer()
{
var collection = ImmutableList.Create(1, 2, 3);
var modified = collection.Remove(2, null);
Assert.Equal(new[] { 1, 3 }, modified);
// Try again through the explicit interface implementation.
IImmutableList<int> collectionIface = collection;
var modified2 = collectionIface.Remove(2, null);
Assert.Equal(new[] { 1, 3 }, modified2);
}
[Fact]
public void RemoveTest()
{
ImmutableList<int> list = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.Remove(30);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.Remove(100);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.Remove(10);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
var removeList = new int[] { 20, 70 };
list = list.RemoveAll(removeList.Contains);
Assert.Equal(5, list.Count);
Assert.False(list.Contains(20));
Assert.False(list.Contains(70));
IImmutableList<int> list2 = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list2 = list2.Add(i * 10);
}
list2 = list2.Remove(30);
Assert.Equal(9, list2.Count);
Assert.False(list2.Contains(30));
list2 = list2.Remove(100);
Assert.Equal(8, list2.Count);
Assert.False(list2.Contains(100));
list2 = list2.Remove(10);
Assert.Equal(7, list2.Count);
Assert.False(list2.Contains(10));
list2 = list2.RemoveAll(removeList.Contains);
Assert.Equal(5, list2.Count);
Assert.False(list2.Contains(20));
Assert.False(list2.Contains(70));
}
[Fact]
public void RemoveNonExistentKeepsReference()
{
var list = ImmutableList<int>.Empty;
Assert.Same(list, list.Remove(3));
}
/// <summary>
/// Verifies that RemoveRange does not enumerate its argument if the list is empty
/// and therefore could not possibly have any elements to remove anyway.
/// </summary>
/// <remarks>
/// While this would seem an implementation detail and simply an optimization,
/// it turns out that changing this behavior now *could* represent a breaking change
/// because if the enumerable were to throw an exception, that exception would not be
/// observed previously, but would start to be thrown if this behavior changed.
/// So this is a test to lock the behavior in place.
/// </remarks>
/// <seealso cref="ImmutableSetTest.ExceptDoesEnumerateSequenceIfThisIsEmpty"/>
[Fact]
public void RemoveRangeDoesNotEnumerateSequenceIfThisIsEmpty()
{
var list = ImmutableList<int>.Empty;
list.RemoveRange(Enumerable.Range(1, 1).Select<int, int>(n => { throw new ShouldNotBeInvokedException(); }));
}
[Fact]
public void RemoveAtTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(1));
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.RemoveAt(2);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.RemoveAt(8);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.RemoveAt(0);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
}
[Fact]
public void IndexOfAndContainsTest()
{
var expectedList = new List<string>(new[] { "Microsoft", "Windows", "Bing", "Visual Studio", "Comics", "Computers", "Laptops" });
var list = ImmutableList<string>.Empty;
foreach (string newElement in expectedList)
{
Assert.False(list.Contains(newElement));
list = list.Add(newElement);
Assert.True(list.Contains(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(newElement.ToUpperInvariant()));
foreach (string existingElement in expectedList.TakeWhile(v => v != newElement))
{
Assert.True(list.Contains(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(existingElement.ToUpperInvariant()));
}
}
}
[Fact]
public void Indexer()
{
var list = ImmutableList.CreateRange(Enumerable.Range(1, 3));
Assert.Equal(1, list[0]);
Assert.Equal(2, list[1]);
Assert.Equal(3, list[2]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list[3]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list[-1]);
Assert.Equal(3, ((IList)list)[2]);
Assert.Equal(3, ((IList<int>)list)[2]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
IndexOfTests.IndexOfTest(
seq => (IImmutableList<int>)ImmutableList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableList.CreateRange(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
IndexOfTests.LastIndexOfTest(
seq => (IImmutableList<int>)ImmutableList.CreateRange(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void ReplaceTest()
{
// Verify replace at beginning, middle, and end.
var list = ImmutableList<int>.Empty.Add(3).Add(5).Add(8);
Assert.Equal<int>(new[] { 4, 5, 8 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, list.Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, list.Replace(8, 9));
Assert.Equal<int>(new[] { 4, 5, 8 }, ((IImmutableList<int>)list).Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, ((IImmutableList<int>)list).Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, ((IImmutableList<int>)list).Replace(8, 9));
// Verify replacement of first element when there are duplicates.
list = ImmutableList<int>.Empty.Add(3).Add(3).Add(5);
Assert.Equal<int>(new[] { 4, 3, 5 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, list.Replace(3, 4).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 3, 5 }, ((IImmutableList<int>)list).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, ((IImmutableList<int>)list).Replace(3, 4).Replace(3, 4));
}
[Fact]
public void ReplaceWithEqualityComparerTest()
{
var list = ImmutableList.Create(new Person { Name = "Andrew", Age = 20 });
var newAge = new Person { Name = "Andrew", Age = 21 };
var updatedList = list.Replace(newAge, newAge, new NameOnlyEqualityComparer());
Assert.Equal(newAge.Age, updatedList[0].Age);
// Try again with a null equality comparer, which should use the default EQ.
updatedList = list.Replace(list[0], newAge);
Assert.NotSame(list, updatedList);
// Finally, try one last time using the interface implementation.
IImmutableList<Person> iface = list;
var updatedIface = iface.Replace(list[0], newAge);
Assert.NotSame(iface, updatedIface);
}
[Fact]
public void ReplaceMissingThrowsTest()
{
Assert.Throws<ArgumentException>("oldValue", () => ImmutableList<int>.Empty.Replace(5, 3));
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableList<int>.Empty.Equals(null));
Assert.False(ImmutableList<int>.Empty.Equals("hi"));
Assert.True(ImmutableList<int>.Empty.Equals(ImmutableList<int>.Empty));
Assert.False(ImmutableList<int>.Empty.Add(3).Equals(ImmutableList<int>.Empty.Add(3)));
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
ImmutableList<string> list = ImmutableList.Create<string>();
Assert.Equal(0, list.Count);
list = ImmutableList.Create("a");
Assert.Equal(1, list.Count);
list = ImmutableList.Create("a", "b");
Assert.Equal(2, list.Count);
list = ImmutableList.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableList()
{
ImmutableList<string> list = new[] { "a", "b" }.ToImmutableList();
Assert.Equal(2, list.Count);
list = new[] { "a", "b" }.ToImmutableList();
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableListOfSameType()
{
var list = ImmutableList.Create("a");
Assert.Same(list, list.ToImmutableList());
}
[Fact]
public void RemoveAllNullTest()
{
Assert.Throws<ArgumentNullException>("match", () => ImmutableList<int>.Empty.RemoveAll(null));
}
[Fact]
public void RemoveRangeArrayTest()
{
Assert.True(ImmutableList<int>.Empty.RemoveRange(0, 0).IsEmpty);
var list = ImmutableList.Create(1, 2, 3);
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveRange(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>("count", () => list.RemoveRange(0, -1));
Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveRange(4, 0));
Assert.Throws<ArgumentOutOfRangeException>("count", () => list.RemoveRange(0, 4));
Assert.Throws<ArgumentOutOfRangeException>("count", () => list.RemoveRange(2, 2));
Assert.Equal(list, list.RemoveRange(3, 0));
}
[Fact]
public void RemoveRange_EnumerableEqualityComparer_AcceptsNullEQ()
{
var list = ImmutableList.Create(1, 2, 3);
var removed2eq = list.RemoveRange(new[] { 2 }, null);
Assert.Equal(2, removed2eq.Count);
Assert.Equal(new[] { 1, 3 }, removed2eq);
}
[Fact]
public void RemoveRangeEnumerableTest()
{
var list = ImmutableList.Create(1, 2, 3);
Assert.Throws<ArgumentNullException>("items", () => list.RemoveRange(null));
ImmutableList<int> removed2 = list.RemoveRange(new[] { 2 });
Assert.Equal(2, removed2.Count);
Assert.Equal(new[] { 1, 3 }, removed2);
ImmutableList<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 });
Assert.Equal(1, removed13.Count);
Assert.Equal(new[] { 2 }, removed13);
Assert.Equal(new[] { 2 }, ((IImmutableList<int>)list).RemoveRange(new[] { 1, 3, 5 }));
Assert.Same(list, list.RemoveRange(new[] { 5 }));
Assert.Same(ImmutableList.Create<int>(), ImmutableList.Create<int>().RemoveRange(new[] { 1 }));
var listWithDuplicates = ImmutableList.Create(1, 2, 2, 3);
Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 }));
Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 }));
Assert.Throws<ArgumentNullException>("items", () => ((IImmutableList<int>)ImmutableList.Create(1, 2, 3)).RemoveRange(null));
Assert.Equal(new[] { 1, 3 }, ((IImmutableList<int>)ImmutableList.Create(1, 2, 3)).RemoveRange(new[] { 2 }));
}
[Fact]
public void EnumeratorTest()
{
var list = ImmutableList.Create("a");
var enumerator = list.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableList.Create(1);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(collection[0], enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void ReverseTest2()
{
var emptyList = ImmutableList.Create<int>();
Assert.Same(emptyList, emptyList.Reverse());
var populatedList = ImmutableList.Create(3, 2, 1);
Assert.Equal(Enumerable.Range(1, 3), populatedList.Reverse());
}
[Fact]
public void SetItem()
{
var emptyList = ImmutableList.Create<int>();
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[-1]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[0]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => emptyList[1]);
var listOfOne = emptyList.Add(5);
Assert.Throws<ArgumentOutOfRangeException>("index", () => listOfOne[-1]);
Assert.Equal(5, listOfOne[0]);
Assert.Throws<ArgumentOutOfRangeException>("index", () => listOfOne[1]);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableList.Create<int>();
Assert.True(collection.IsSynchronized);
}
[Fact]
public void IListIsReadOnly()
{
IList list = ImmutableList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.True(list.IsFixedSize);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact]
public void IListOfTIsReadOnly()
{
IList<int> list = ImmutableList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableList.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableList.Create<double>(1, 2, 3));
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableList.Create<string>("1", "2", "3"), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
[Fact]
public void UsableWithCollectibleAssemblies()
{
var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("dynamic_assembly"), AssemblyBuilderAccess.RunAndCollect);
var module = assembly.DefineDynamicModule("dynamic");
var typeBuilder = module.DefineType("Dummy");
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
var dummType = typeBuilder.CreateTypeInfo();
var createMethod = typeof(ImmutableList).GetMethods().Where(m => m.Name == "Create" && m.GetParameters().Length == 0).Single().MakeGenericMethod(dummType.AsType());
var list = (IEnumerable)createMethod.Invoke(null, null);
var addMethod = list.GetType().GetMethod("Add");
list = (IEnumerable)addMethod.Invoke(list, new object[] { Activator.CreateInstance(dummType.AsType()) });
list.GetEnumerator(); // ensure this doesn't throw
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableList<T>.Empty.AddRange(contents);
}
protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test)
{
var expected = list.ToList();
expected.RemoveAll(test);
var actual = list.RemoveAll(test);
Assert.Equal<T>(expected, actual.ToList());
}
protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var actual = list.Reverse(index, count);
Assert.Equal<T>(expected, actual.ToList());
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list)
{
return list.Sort().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison)
{
return list.Sort(comparison).ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer)
{
return list.Sort(comparer).ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer)
{
return list.Sort(index, count, comparer).ToList();
}
internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list)
{
return list;
}
private static void VerifyBalanced<T>(ImmutableList<T> tree)
{
tree.Root.VerifyBalanced();
}
private struct Person
{
public string Name { get; set; }
public int Age { get; set; }
}
private class NameOnlyEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Net;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using OpenLiveWriter.CoreServices.Progress;
using OpenLiveWriter.CoreServices.Threading;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Downloads the file addressed by a URL to a local file.
/// </summary>
public class UrlDownloadToFile :
IBindStatusCallback, IHttpNegotiate, IAuthenticate,
IWindowForBindingUI, IHttpSecurity
{
public static bool IsDownloadableUrl(string url)
{
try
{
Uri uri = new Uri(url);
foreach (string scheme in DownloadableSchemes)
if (uri.Scheme == scheme)
return true;
}
catch(Exception)
{
//may occur if the URL is malformed
}
return false;
}
/// <summary>
/// Simple wrapper function that downloads a url and returns a file path
/// (uses all defaults, including writing the file to a temporary path)
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string Download(string url)
{
return Download(url, NO_TIMEOUT) ;
}
public static string Download(string url, int timeoutMs)
{
return Download(url, timeoutMs, null) ;
}
public static string Download(string url, WinInetCredentialsContext credentialsContext)
{
return Download(url, NO_TIMEOUT, credentialsContext) ;
}
/// <summary>
/// Simple wrapper function that downloads a url and returns a file path
/// (uses all defaults, including writing the file to a temporary path)
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string Download(string url, int timeoutMs, WinInetCredentialsContext credentialsContext)
{
// do the download (will use cached images correctly, etc.)
UrlDownloadToFile urlDownloadToFile = new UrlDownloadToFile();
urlDownloadToFile.Url = url ;
urlDownloadToFile.TimeoutMs = timeoutMs ;
urlDownloadToFile.CredentialsContext = credentialsContext ;
urlDownloadToFile.Download();
// return a bitmap based on the file
return urlDownloadToFile.FilePath ;
}
public enum DownloadActions
{
GET,
POST,
}
public UrlDownloadToFile()
{
_downloadAction = DownloadActions.GET;
}
public string Url
{
get
{
return _url;
}
set
{
_url = value;
}
}
private string _url;
public string FilePath
{
get
{
if (_filePath == null)
{
_filePath = TempFileManager.Instance.CreateTempFile();
}
return _filePath;
}
set
{
_filePath = value;
}
}
private string _filePath;
public int TimeoutMs
{
get
{
return _timeoutMs ;
}
set
{
_timeoutMs = value ;
}
}
private int _timeoutMs = NO_TIMEOUT;
private const int NO_TIMEOUT = -1 ;
public WinInetCredentialsContext CredentialsContext
{
set
{
if ( value != null )
{
if ( value.NetworkCredential != null )
_networkCredential = value.NetworkCredential ;
if ( value.CookieString != null)
_cookieString = value.CookieString.Cookies ;
}
}
}
private NetworkCredential _networkCredential = null;
private string _cookieString = null;
public DownloadActions DownloadAction
{
get
{
return _downloadAction;
}
set
{
_downloadAction = value;
}
}
private DownloadActions _downloadAction;
public byte[] PostData
{
get
{
return _postData;
}
set
{
_postData = value;
}
}
private byte[] _postData;
public bool ShowSecurityUI
{
get
{
return _showSecurityUI;
}
set
{
_showSecurityUI = value;
}
}
private bool _showSecurityUI = false;
public object Download()
{
return Download(SilentProgressHost.Instance) ;
}
public object Download( IProgressHost progressHost )
{
ResetTimeoutState() ;
_finalUrl = Url;
ProgressHost = progressHost;
// call the URLDownloadToFile (synchronous, notifies us of progress
// via calls to IBindStatusCallback)
SetCookies();
int result = UrlMon.URLDownloadToFile(
IntPtr.Zero, Url, FilePath, 0, this ) ;
// check for errors in the call
// TODO: account for errors that we purposely generate (E_ACCESSDENIED)
// HRESULT E_ABORT 0x80004004
switch (result)
{
case HRESULT.S_OK: // The download suceeded
break;
case HRESULT.E_ABORT: // The download has been cancelled
//case HRESULT.E_ACCESSDENIED: // no idea
if (progressHost.CancelRequested)
throw new OperationCancelledException();
break;
default:
throw new COMException("Unable to download file " + Url, result );
};
return this;
}
private void ResetTimeoutState()
{
_timedOut = false ;
_timeoutTime = DateTime.MinValue ;
// if the download has a timeout then calculate the end-time
if ( TimeoutMs != NO_TIMEOUT )
{
_timeoutTime = DateTime.Now.AddMilliseconds(TimeoutMs) ;
}
}
private void SetCookies()
{
if ( _cookieString != null )
WinInet.InternetSetCookies(Url, null, _cookieString);
}
public bool TimedOut
{
get
{
return _timedOut ;
}
}
private bool _timedOut = false ;
private DateTime _timeoutTime = DateTime.MinValue;
public string ResponseHeaders
{
get
{
return m_responseHeaders;
}
}
private string m_responseHeaders;
public string FinalUrl
{
get
{
return _finalUrl;
}
}
private string _finalUrl;
public string ContentType
{
get
{
return m_contentType;
}
}
private string m_contentType = null;
private static string[] DownloadableSchemes = new string[] { Uri.UriSchemeFile, Uri.UriSchemeHttp, Uri.UriSchemeHttps };
private IProgressHost ProgressHost;
#region IBindStatusCallback Members
/// <summary>
/// Provides information about how the bind operation should be handled when called by an asynchronous moniker.
/// </summary>
void IBindStatusCallback.GetBindInfo(ref uint grfBINDF, ref BINDINFO pbindinfo)
{
if ( DownloadAction == DownloadActions.POST )
{
grfBINDF |= (uint)BINDF.FORMS_SUBMIT ;
grfBINDF |= (uint)BINDF.IGNORESECURITYPROBLEM;
pbindinfo.dwBindVerb = BINDVERB.POST ;
pbindinfo.stgmedData.tymed = TYMED.HGLOBAL ;
pbindinfo.stgmedData.contents = Marshal.AllocHGlobal(PostData.Length) ;
Marshal.Copy(PostData, 0, pbindinfo.stgmedData.contents , PostData.Length);
pbindinfo.stgmedData.pUnkForRelease = IntPtr.Zero ;
pbindinfo.cbstgmedData = (uint)PostData.Length ;
}
LOG( "IBindStatusCallback", "GetBindInfo" ) ;
}
/// <summary>
/// Notifies the client about the callback methods it is registered to receive.
/// </summary>
void IBindStatusCallback.OnStartBinding(uint dwReserved, IntPtr pib)
{
LOG( "IBindStatusCallback", "OnStartBinding" ) ;
}
/// <summary>
/// The moniker calls this method repeatedly to indicate the current progress of the bind
/// operation, typically at reasonable intervals during a lengthy operation.
///
/// The client can use the progress notification to provide progress information to the
/// user from the ulProgress, ulProgressMax, and szStatusText parameters, or to make
/// programmatic decisions based on the ulStatusCode parameter.
/// </summary>
int IBindStatusCallback.OnProgress(uint ulProgress, uint ulProgressMax, BINDSTATUS ulStatusCode, string szStatusText)
{
//Debug.WriteLine( String.Format( "IBindStatusCallback.OnProgress {0}: {1} ({2}/{3})", ulStatusCode, szStatusText != null ? szStatusText : String.Empty, ulProgress, ulProgressMax ) ) ;
// check for timeout
if ( TimeoutMs != NO_TIMEOUT )
{
if ( DateTime.Now > _timeoutTime )
{
_timedOut = true ;
return HRESULT.E_ABORT ;
}
}
if (ulStatusCode == BINDSTATUS.ENDDOWNLOADDATA)
// We've completed the download of the file
return HRESULT.S_OK ;
else if (ulStatusCode == BINDSTATUS.MIMETYPEAVAILABLE)
// record the mime type
m_contentType = szStatusText;
else if (ulStatusCode == BINDSTATUS.REDIRECTING)
_finalUrl = szStatusText;
else if ((ProgressHost != null && ProgressHost.CancelRequested) || ThreadHelper.Interrupted)
// Cancel this operation
return HRESULT.E_ABORT;
else
{
if (ProgressHost != null)
// UrlDownloadToFile can sometimes return progress that exceeds 100%- stop this from happening
ProgressHost.UpdateProgress((int)(Math.Min(ulProgressMax, ulProgress)), (int)ulProgressMax, String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.ProgressDownloading), Url));
}
return HRESULT.S_OK ;
}
/// <summary>
/// This method is always called, whether the bind operation succeeded, failed, or was aborted by a client.
/// </summary>
void IBindStatusCallback.OnStopBinding(int hresult, string szError)
{
LOG( "IBindStatusCallback", "OnStopBinding" ) ;
}
/// <summary>
/// Obtains the priority for the bind operation when called by an asynchronous moniker.
/// </summary>
void IBindStatusCallback.GetPriority(out int pnPriority)
{
LOG_UN( "IBindStatusCallback", "GetPriority" ) ;
// just in case....
pnPriority = THREAD_PRIORITY.NORMAL ;
}
/// <summary>
/// This is not currently implemented and should never be called.
/// </summary>
void IBindStatusCallback.OnLowResource(uint reserved)
{
// not implemented
LOG_UN( "IBindStatusCallback", "OnLowResource" ) ;
}
/// <summary>
/// Provides data to the client as it becomes available during asynchronous bind operations.
/// </summary>
void IBindStatusCallback.OnDataAvailable(BSCF grfBSCF, uint dwSize, ref FORMATETC pformatetc, ref STGMEDIUM pstgmed)
{
// never called by URLDownloadToFile
LOG_UN( "IBindStatusCallback", "OnDataAvailable" ) ;
}
/// <summary>
/// Passes the requested object interface pointer to the client.
/// </summary>
void IBindStatusCallback.OnObjectAvailable(ref Guid riid, IntPtr punk)
{
// never called by URLDownloadToFile
LOG_UN( "IBindStatusCallback", "OnObjectAvailable" ) ;
}
#endregion
#region IHttpNegotiate Members
/// <summary>
/// The URL moniker calls this method before sending an HTTP request.
/// It notifies the client of the URL being bound to at the beginning
/// of the HTTP transaction. It also allows the client to add
/// additional headers, such as Accept-Language, to the request.
/// </summary>
public int BeginningTransaction(string szURL, string szHeaders, uint dwReserved, out IntPtr pszAdditionalHeaders)
{
LOG( "IHttpNegotiate", "BeginningTransaction" ) ;
string additionalHeaders = null;
// Send form header
if (DownloadAction == DownloadActions.POST)
{
additionalHeaders = additionalHeaders + "Content-Type: application/x-www-form-urlencoded\r\n";
}
if (additionalHeaders == null)
pszAdditionalHeaders = IntPtr.Zero ;
else
pszAdditionalHeaders = Marshal.StringToCoTaskMemUni(additionalHeaders);
return HRESULT.S_OK ;
}
/// <summary>
/// The URL moniker calls this method when it receives a response to an
/// HTTP request. If dwResponseCode indicates a success, the client can
/// examine the response headers and can optionally abort the bind operation.
/// If dwResponseCode indicates a failure, the client can add HTTP headers
/// to the request before it is sent again.
/// </summary>
public int OnResponse(uint dwResponseCode, string szResponseHeaders, string szRequestHeaders, out IntPtr pszAdditionalRequestHeaders)
{
LOG( "IHttpNegotiate", "OnResponse" ) ;
m_responseHeaders = szResponseHeaders;
// NOTE: use Marshal.StringToCoTaskMemUni if you want to add additional
// headers, e.g. pszAdditionalHeaders = Marshal.StringToCoTakMemUni("headers")
// They presumably free this memory -- the documentation doesn't specify
pszAdditionalRequestHeaders = IntPtr.Zero ;
return HRESULT.S_OK ;
}
#endregion
#region IAuthenticate Members
/// <summary>
/// Supplies authentication support to a URL moniker from a client application.
///
/// If we need to support automatically logging users in to download files, we
/// should implement a response here (the operation should call this in order
/// to get the authentication information to send with the request). The
/// current implementation for URLs appears to only support based authentication
/// at this time.
/// </summary>
public int Authenticate(out IntPtr phwnd, out IntPtr pszUsername, out IntPtr pszPassword)
{
LOG( "IAuthenticate", "Authenticate" ) ;
if ( _networkCredential != null )
{
phwnd = IntPtr.Zero; // no ui
pszUsername = Marshal.StringToCoTaskMemUni(_networkCredential.UserName) ;
pszPassword = Marshal.StringToCoTaskMemUni(_networkCredential.Password);
return HRESULT.S_OK ;
}
else
{
phwnd = IntPtr.Zero ;
pszUsername = IntPtr.Zero ;
pszPassword = IntPtr.Zero ;
return HRESULT.E_ACCESSDENIED ;
}
}
#endregion
#region IWindowForBindingUI
/// <summary>
/// This interface allows clients of URL monikers to display information
/// in the client's user interface when necessary.
///
/// We always request silent, so this should never be called.
/// </summary>
[PreserveSig]
int IWindowForBindingUI.GetWindow( ref Guid rguidReason, out IntPtr phwnd)
{
//This now happens for IE8 post-beta 2
//LOG_UN( "IWindowForBindingUI", "GetWindow" ) ;
phwnd = User32.GetDesktopWindow();
return HRESULT.S_OK ;
}
#endregion
#region IHttpSecurity Members
/// <summary>
/// Undocumented, but likely used to get the client window so
/// notification ui can be displayed. We request silent operation,
/// so this should never be called.
/// </summary>
int IHttpSecurity.GetWindow(ref Guid rguidReason, out IntPtr phwnd)
{
LOG( "IHttpSecurity", "GetWindow" ) ;
phwnd = User32.GetDesktopWindow() ;
return HRESULT.S_OK ;
}
/// <summary>
/// Notifies the client application about an authentication problem.
///
/// We are requesting to ignore these problems, so this should never get called.
/// </summary>
int IHttpSecurity.OnSecurityProblem(uint dwProblem)
{
LOG( "IHttpSecurity", "OnSecurityProblem" ) ;
if (ShowSecurityUI)
return HRESULT.S_FALSE;
else
return HRESULT.E_ABORT;
}
#endregion
#region Debug helpers
/// <summary>
/// Log access to an interface method
/// </summary>
/// <param name="iface">name of interface</param>
/// <param name="method">name of method</param>
[Conditional("DEBUG")]
private static void LOG( string iface, string method )
{
//Debug.WriteLine( String.Format( "{0}.{1}", iface, method ) ) ;
}
/// <summary>
/// Log an unexpected access to an interface method (during active
/// development this will assert to notify us of a new use of our
/// interface implementations)
/// </summary>
/// <param name="iface">name of interface</param>
/// <param name="method">name of method</param>
[Conditional("DEBUG")]
private static void LOG_UN( string iface, string method )
{
Debug.Fail(
String.Format( CultureInfo.InvariantCulture, "Unexpected call to {0}.{1}", iface, method ) ) ;
LOG( iface, method ) ;
}
#endregion
}
public class WinInetCredentialsContext
{
public WinInetCredentialsContext(NetworkCredential credential)
: this(credential, null)
{
}
public WinInetCredentialsContext(CookieString cookieString)
: this(null, cookieString)
{
}
public WinInetCredentialsContext(NetworkCredential credential, CookieString cookieString)
{
_networkCredential = credential ;
_cookieString = cookieString ;
}
public NetworkCredential NetworkCredential
{
get { return _networkCredential; }
}
private NetworkCredential _networkCredential = null ;
public CookieString CookieString
{
get { return _cookieString; }
}
private CookieString _cookieString ;
}
public class CookieString
{
public CookieString(string url, string cookies)
{
_url = url ;
_cookies = cookies ;
}
public string Url
{
get { return _url; }
}
private string _url ;
public string Cookies
{
get { return _cookies; }
}
private string _cookies ;
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Xml;
using XmlRpcLight.Enums;
namespace XmlRpcLight.Test {
public class Utils {
public static XmlDocument Serialize(
string testName,
object obj,
Encoding encoding,
MappingAction action) {
Stream stm = new MemoryStream();
var xtw = new XmlTextWriter(stm, Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xtw.Indentation = 2;
xtw.WriteStartDocument();
var ser = new XmlRpcSerializer();
ser.Serialize(xtw, obj, action);
xtw.Flush();
//Console.WriteLine(testName);
stm.Position = 0;
TextReader trdr = new StreamReader(stm, new UTF8Encoding(), true, 4096);
String s = trdr.ReadLine();
while (s != null) {
//Console.WriteLine(s);
s = trdr.ReadLine();
}
stm.Position = 0;
var xdoc = new XmlDocument();
xdoc.PreserveWhitespace = true;
xdoc.Load(stm);
return xdoc;
}
public static string SerializeToString(
string testName,
object obj,
MappingAction action) {
var strwrtr = new StringWriter();
var xtw = new XmlTextWriter(strwrtr);
// xtw.Formatting = formatting;
// xtw.Indentation = indentation;
xtw.WriteStartDocument();
var ser = new XmlRpcSerializer();
ser.Serialize(xtw, obj, action);
xtw.Flush();
//Console.WriteLine(testName);
//Console.WriteLine(strwrtr.ToString());
return strwrtr.ToString();
}
//----------------------------------------------------------------------//
public static object Parse(
string xml,
Type valueType,
MappingAction action,
out Type parsedType,
out Type parsedArrayType) {
var sr = new StringReader(xml);
var xdoc = new XmlDocument();
xdoc.PreserveWhitespace = true;
xdoc.Load(sr);
return Parse(xdoc, valueType, action,
out parsedType, out parsedArrayType);
}
public static object Parse(
XmlDocument xdoc,
Type valueType,
MappingAction action,
out Type parsedType,
out Type parsedArrayType) {
XmlNode node = SelectValueNode(xdoc.SelectSingleNode("value"));
var parseStack
= new XmlRpcSerializer.ParseStack("request");
var ser = new XmlRpcSerializer();
object obj = ser.ParseValue(node, valueType, parseStack, action,
out parsedType, out parsedArrayType);
return obj;
}
public static object Parse(
string xml,
Type valueType,
MappingAction action,
XmlRpcSerializer serializer,
out Type parsedType,
out Type parsedArrayType) {
var sr = new StringReader(xml);
var xdoc = new XmlDocument();
xdoc.PreserveWhitespace = true;
xdoc.Load(sr);
return Parse(xdoc, valueType, action, serializer,
out parsedType, out parsedArrayType);
}
public static object Parse(
XmlDocument xdoc,
Type valueType,
MappingAction action,
XmlRpcSerializer serializer,
out Type parsedType,
out Type parsedArrayType) {
XmlNode node = SelectValueNode(xdoc.SelectSingleNode("value"));
var parseStack
= new XmlRpcSerializer.ParseStack("request");
object obj = serializer.ParseValue(node, valueType, parseStack, action,
out parsedType, out parsedArrayType);
return obj;
}
private static XmlNode SelectValueNode(XmlNode valueNode) {
// an XML-RPC value is either held as the child node of a <value> element
// or is just the text of the value node as an implicit string value
XmlNode vvNode = valueNode.SelectSingleNode("*");
if (vvNode == null)
vvNode = valueNode.FirstChild;
return vvNode;
}
public static string[] GetLocales() {
return new[] {
"af-ZA",
"sq-AL",
"ar-DZ",
"ar-BH",
"ar-EG",
"ar-IQ",
"ar-JO",
"ar-KW",
"ar-LB",
"ar-LY",
"ar-MA",
"ar-OM",
"ar-QA",
"ar-SA",
"ar-SY",
"ar-TN",
"ar-AE",
"ar-YE",
"hy-AM",
"az-Cyrl-AZ",
"az-Latn-AZ",
"eu-ES",
"be-BY",
"bg-BG",
"ca-ES",
"zh-HK",
"zh-MO",
"zh-CN",
"zh-SG",
"zh-TW",
"hr-HR",
"cs-CZ",
"da-DK",
"dv-MV",
"nl-BE",
"nl-NL",
"en-AU",
"en-BZ",
"en-CA",
"en-029",
"en-IE",
"en-JM",
"en-NZ",
"en-PH",
"en-ZA",
"en-TT",
"en-GB",
"en-US",
"en-ZW",
"et-EE",
"fo-FO",
"fa-IR",
"fi-FI",
"fr-BE",
"fr-CA",
"fr-FR",
"fr-LU",
"fr-MC",
"fr-CH",
"gl-ES",
"ka-GE",
"de-AT",
"de-DE",
"de-LI",
"de-LU",
"de-CH",
"el-GR",
"gu-IN",
"he-IL",
"hi-IN",
"hu-HU",
"is-IS",
"id-ID",
"it-IT",
"it-CH",
"ja-JP",
"kn-IN",
"kk-KZ",
"kok-IN",
"ko-KR",
"lv-LV",
"lt-LT",
"mk-MK",
"ms-BN",
"ms-MY",
"mr-IN",
"mn-MN",
"nb-NO",
"nn-NO",
"pl-PL",
"pt-BR",
"pt-PT",
"pa-IN",
"ro-RO",
"ru-RU",
"sa-IN",
"sr-Cyrl-CS",
"sr-Latn-CS",
"sk-SK",
"sl-SI",
"es-AR",
"es-BO",
"es-CL",
"es-CO",
"es-CR",
"es-DO",
"es-EC",
"es-SV",
"es-GT",
"es-HN",
"es-MX",
"es-NI",
"es-PA",
"es-PY",
"es-PE",
"es-PR",
"es-ES",
"es-UY",
"es-VE",
"sw-KE",
"sv-FI",
"sv-SE",
"syr-SY",
"ta-IN",
"tt-RU",
"te-IN",
"th-TH",
"tr-TR",
"uk-UA",
"ur-PK",
"uz-Cyrl-UZ",
"uz-Latn-UZ",
"vi-VN"
};
}
}
}
| |
// 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.Security;
using System;
using System.Runtime.InteropServices;
[SecuritySafeCritical]
/// <summary>
/// Target
/// </summary>
public class GCHandleTarget
{
#region Private Fields
private const int c_SIZE_OF_ARRAY = 256;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Target should return correct object value passed to handle for blittable types");
try
{
retVal = VerificationHelper(TestLibrary.Generator.GetByte(-55), "001.1") && retVal;
retVal = VerificationHelper(TestLibrary.Generator.GetDouble(-55), "001.2") && retVal;
retVal = VerificationHelper(TestLibrary.Generator.GetInt16(-55), "001.3") && retVal;
retVal = VerificationHelper(TestLibrary.Generator.GetInt32(-55), "001.4") && retVal;
retVal = VerificationHelper(TestLibrary.Generator.GetInt64(-55), "001.5") && retVal;
retVal = VerificationHelper(TestLibrary.Generator.GetSingle(-55), "001.6") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Target should return correct object value passed to handle for blittable types");
try
{
retVal = VerificationHelper(TestLibrary.Generator.GetChar(-55), "002.1") && retVal;
retVal = VerificationHelper(TestLibrary.Generator.GetString(-55, false, 1, c_SIZE_OF_ARRAY), "002.2") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Target should return correct object value passed to handle for blittable types");
try
{
byte[] bytes = new byte[c_SIZE_OF_ARRAY];
double[] doubles = new double[c_SIZE_OF_ARRAY];
short[] shorts = new short[c_SIZE_OF_ARRAY];
int[] ints = new int[c_SIZE_OF_ARRAY];
long[] longs = new long[c_SIZE_OF_ARRAY];
float[] floats = new float[c_SIZE_OF_ARRAY];
TestLibrary.Generator.GetBytes(-55, bytes);
for (int i = 0; i < doubles.Length; ++i)
{
doubles[i] = TestLibrary.Generator.GetDouble(-55);
}
for (int i = 0; i < shorts.Length; ++i)
{
shorts[i] = TestLibrary.Generator.GetInt16(-55);
}
for (int i = 0; i < ints.Length; ++i)
{
ints[i] = TestLibrary.Generator.GetInt32(-55);
}
for (int i = 0; i < longs.Length; ++i)
{
longs[i] = TestLibrary.Generator.GetInt64(-55);
}
for (int i = 0; i < floats.Length; ++i)
{
floats[i] = TestLibrary.Generator.GetSingle(-55);
}
retVal = VerificationHelper<byte>(bytes, "003.1") && retVal;
retVal = VerificationHelper<double>(doubles, "003.2") && retVal;
retVal = VerificationHelper<short>(shorts, "003.3") && retVal;
retVal = VerificationHelper<int>(ints, "003.4") && retVal;
retVal = VerificationHelper<long>(longs, "003.5") && retVal;
retVal = VerificationHelper<float>(floats, "003.6") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: InvalidOperationException should be thrown when The handle was freed.");
try
{
GCHandle handle = GCHandle.Alloc(TestLibrary.Generator.GetInt32(-55));
handle.Free();
object target = handle.Target;
TestLibrary.TestFramework.LogError("101.1", "InvalidOperationException is not thrown when The handle was freed.");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: InvalidOperationException should be thrown when The handle was never initialized.");
try
{
GCHandle handle = (GCHandle)IntPtr.Zero;
object target = handle.Target;
TestLibrary.TestFramework.LogError("102.1", "InvalidOperationException is not thrown when The handle was never initialized.");
retVal = false;
}
catch (InvalidOperationException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
GCHandleTarget test = new GCHandleTarget();
TestLibrary.TestFramework.BeginTestCase("GCHandleTarget");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Method
private bool VerificationHelper(object obj, string errorNo)
{
bool retVal = true;
GCHandle handle = GCHandle.Alloc(obj);
if (handle.Target == null)
{
TestLibrary.TestFramework.LogError(errorNo, "Target returns null for valid GCHandle");
retVal = false;
}
else
{
if (!obj.Equals(handle.Target))
{
TestLibrary.TestFramework.LogError(errorNo, "Target returns from valid GCHandle is wrong");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] obj = " + obj + ", handle.Target = " + handle.Target);
retVal = false;
}
}
handle.Free();
return retVal;
}
private bool VerificationHelper<T>(T[] obj, string errorNo)
{
bool retVal = true;
GCHandle handle = GCHandle.Alloc(obj);
T[] actual = handle.Target as T[];
if (actual == null)
{
TestLibrary.TestFramework.LogError(errorNo, "Target returns null for valid GCHandle");
retVal = false;
}
else if (actual.Length != obj.Length)
{
TestLibrary.TestFramework.LogError(errorNo, "Target returns wrong array for valid GCHandle for object array");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] obj.Length = " + obj.Length + ", actual.Length = " + actual.Length);
retVal = false;
}
else
{
for (int i = 0; i < obj.Length; ++i)
{
if (!obj[i].Equals(actual[i]))
{
TestLibrary.TestFramework.LogError(errorNo, "Target returns from valid GCHandle is wrong");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] obj[i] = " + obj[i] + ", actual[i] = " + actual[i] + ", i = " + i);
retVal = false;
}
}
}
handle.Free();
return retVal;
}
#endregion
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime;
using System.Threading;
sealed class UdpSocketReceiveManager
{
BufferManager bufferManager;
Action<object> continueReceivingCallback;
int maxPendingReceivesPerSocket;
AsyncCallback onReceiveFrom;
Action<object> onStartReceiving;
int openCount;
IUdpReceiveHandler receiveHandler;
UdpSocket[] receiveSockets;
Action onMessageDequeued;
object thisLock;
int messageBufferSize;
ConnectionBufferPool receiveBufferPool;
internal UdpSocketReceiveManager(UdpSocket[] receiveSockets, int maxPendingReceivesPerSocket, BufferManager bufferManager, IUdpReceiveHandler receiveHandler)
{
Fx.Assert(receiveSockets != null, "receiveSockets parameter is null");
Fx.Assert(receiveSockets.Length > 0, "receiveSockets parameter is empty");
Fx.Assert(maxPendingReceivesPerSocket > 0, "maxPendingReceivesPerSocket can't be <= 0");
Fx.Assert(receiveHandler.MaxReceivedMessageSize > 0, "maxReceivedMessageSize must be > 0");
Fx.Assert(bufferManager != null, "bufferManager argument should not be null");
Fx.Assert(receiveHandler != null, "receiveHandler should not be null");
this.receiveHandler = receiveHandler;
this.thisLock = new object();
this.bufferManager = bufferManager;
this.receiveSockets = receiveSockets;
this.maxPendingReceivesPerSocket = maxPendingReceivesPerSocket;
this.messageBufferSize = UdpUtility.ComputeMessageBufferSize(receiveHandler.MaxReceivedMessageSize);
int maxPendingReceives = maxPendingReceivesPerSocket * receiveSockets.Length;
this.receiveBufferPool = new ConnectionBufferPool(this.messageBufferSize, maxPendingReceives);
}
bool IsDisposed
{
get
{
return this.openCount < 0;
}
}
public void SetReceiveHandler(IUdpReceiveHandler handler)
{
Fx.Assert(handler != null, "IUdpReceiveHandler can't be null");
Fx.Assert(handler.MaxReceivedMessageSize == this.receiveHandler.MaxReceivedMessageSize, "new receive handler's max message size doesn't match");
Fx.Assert(this.openCount > 0, "SetReceiveHandler called on a closed UdpSocketReceiveManager");
this.receiveHandler = handler;
}
public void Close()
{
lock (this.thisLock)
{
if (this.IsDisposed)
{
return;
}
this.openCount--;
if (this.openCount == 0)
{
this.openCount = -1;
this.receiveBufferPool.Close();
this.bufferManager.Clear();
for (int i = 0; i < this.receiveSockets.Length; i++)
{
this.receiveSockets[i].Close();
}
}
}
}
public void Open()
{
lock (this.thisLock)
{
ThrowIfDisposed();
this.openCount++;
if (this.openCount == 1)
{
for (int i = 0; i < this.receiveSockets.Length; i++)
{
this.receiveSockets[i].Open();
}
this.onMessageDequeued = new Action(OnMessageDequeued);
this.onReceiveFrom = Fx.ThunkCallback(new AsyncCallback(OnReceiveFrom));
this.continueReceivingCallback = new Action<object>(ContinueReceiving);
}
}
try
{
if (Thread.CurrentThread.IsThreadPoolThread)
{
EnsureReceiving();
}
else
{
if (this.onStartReceiving == null)
{
this.onStartReceiving = new Action<object>(OnStartReceiving);
}
ActionItem.Schedule(this.onStartReceiving, this);
}
}
catch (Exception ex)
{
if (!TryHandleException(ex))
{
throw;
}
}
}
static void OnStartReceiving(object state)
{
UdpSocketReceiveManager thisPtr = (UdpSocketReceiveManager)state;
try
{
if (thisPtr.IsDisposed)
{
return;
}
thisPtr.EnsureReceiving();
}
catch (Exception ex)
{
if (!thisPtr.TryHandleException(ex))
{
throw;
}
}
}
void OnMessageDequeued()
{
try
{
EnsureReceiving();
}
catch (Exception ex)
{
if (!TryHandleException(ex))
{
throw;
}
}
}
void ContinueReceiving(object socket)
{
try
{
while (StartAsyncReceive(socket as UdpSocket))
{
Fx.Assert(Thread.CurrentThread.IsThreadPoolThread, "Receive loop is running on a non-threadpool thread. If this thread disappears while a completion port operation is outstanding, then the operation will get canceled.");
}
}
catch (Exception ex)
{
if (!TryHandleException(ex))
{
throw;
}
}
}
void OnReceiveFrom(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
UdpSocketReceiveState state = (UdpSocketReceiveState)result.AsyncState;
ArraySegment<byte> messageBytes;
bool continueReceiving = true;
try
{
lock (this.thisLock)
{
if (this.IsDisposed)
{
return;
}
messageBytes = EndReceiveFrom(result, state);
}
messageBytes = this.CopyMessageIntoBufferManager(messageBytes);
//when receiveHandler.HandleDataReceived is called, it will return the buffer to the buffer manager.
continueReceiving = this.receiveHandler.HandleDataReceived(messageBytes, state.RemoteEndPoint, state.Socket.InterfaceIndex, this.onMessageDequeued);
}
catch (Exception ex)
{
if (!TryHandleException(ex))
{
throw;
}
}
finally
{
if (!this.IsDisposed && continueReceiving)
{
ContinueReceiving(state.Socket);
}
}
}
//returns true if receive completed synchronously, false otherwise
bool StartAsyncReceive(UdpSocket socket)
{
Fx.Assert(socket != null, "UdpSocketReceiveManager.StartAsyncReceive: Socket should never be null");
bool completedSync = false;
ArraySegment<byte> messageBytes = default(ArraySegment<byte>);
UdpSocketReceiveState state = null;
lock (this.thisLock)
{
if (!this.IsDisposed && socket.PendingReceiveCount < this.maxPendingReceivesPerSocket)
{
IAsyncResult result = null;
byte[] receiveBuffer = this.receiveBufferPool.Take();
try
{
state = new UdpSocketReceiveState(socket, receiveBuffer);
EndPoint remoteEndpoint = socket.CreateIPAnyEndPoint();
result = socket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, ref remoteEndpoint, onReceiveFrom, state);
}
catch (Exception e)
{
if (!Fx.IsFatal(e))
{
this.receiveBufferPool.Return(receiveBuffer);
}
throw;
}
if (result.CompletedSynchronously)
{
completedSync = true;
messageBytes = EndReceiveFrom(result, state);
}
}
}
if (completedSync)
{
messageBytes = this.CopyMessageIntoBufferManager(messageBytes);
//if HandleDataReceived returns false, it means that the max pending message count was hit.
//when receiveHandler.HandleDataReceived is called (whether now or later), it will return the buffer to the buffer manager.
return this.receiveHandler.HandleDataReceived(messageBytes, state.RemoteEndPoint, state.Socket.InterfaceIndex, this.onMessageDequeued);
}
return false;
}
ArraySegment<byte> CopyMessageIntoBufferManager(ArraySegment<byte> receiveBuffer)
{
int dataLength = receiveBuffer.Count;
byte[] dataBuffer = this.bufferManager.TakeBuffer(dataLength);
Array.Copy(receiveBuffer.Array, receiveBuffer.Offset, dataBuffer, 0, dataLength);
this.receiveBufferPool.Return(receiveBuffer.Array);
return new ArraySegment<byte>(dataBuffer, 0, dataLength);
}
void EnsureReceiving()
{
for (int i = 0; i < this.receiveSockets.Length; i++)
{
UdpSocket socket = this.receiveSockets[i];
while (!this.IsDisposed && socket.PendingReceiveCount < this.maxPendingReceivesPerSocket)
{
bool jumpThreads = false;
try
{
if (StartAsyncReceive(socket) && !Thread.CurrentThread.IsThreadPoolThread)
{
jumpThreads = true;
}
}
catch (CommunicationException ex)
{
//message too big, ICMP errors, etc, are translated by the socket into a CommunicationException derived exception.
//These should not be fatal to the receive loop, so we need to continue receiving.
this.receiveHandler.HandleAsyncException(ex);
jumpThreads = !Thread.CurrentThread.IsThreadPoolThread;
}
if (jumpThreads)
{
ActionItem.Schedule(this.continueReceivingCallback, socket);
break; //while loop.
}
}
}
}
void ThrowIfDisposed()
{
if (this.IsDisposed)
{
throw FxTrace.Exception.AsError(new ObjectDisposedException("SocketReceiveManager"));
}
}
bool TryHandleException(Exception ex)
{
if (Fx.IsFatal(ex))
{
return false;
}
this.receiveHandler.HandleAsyncException(ex);
return true;
}
//call under a lock
ArraySegment<byte> EndReceiveFrom(IAsyncResult result, UdpSocketReceiveState state)
{
try
{
EndPoint remoteEndpoint = null;
ArraySegment<byte> messageBytes = state.Socket.EndReceiveFrom(result, ref remoteEndpoint);
state.RemoteEndPoint = remoteEndpoint;
Fx.Assert(messageBytes.Array == state.ReceiveBuffer, "Array returned by Socket.EndReceiveFrom must match the array passed in through the UdpSocketReceiveState");
return messageBytes;
}
catch (Exception e)
{
if (!Fx.IsFatal(e))
{
this.receiveBufferPool.Return(state.ReceiveBuffer);
}
throw;
}
}
internal class UdpSocketReceiveState
{
public UdpSocketReceiveState(UdpSocket socket, byte[] receiveBuffer)
{
Fx.Assert(socket != null, "UdpSocketReceiveState.ctor: socket should not be null");
this.Socket = socket;
this.ReceiveBuffer = receiveBuffer;
}
public EndPoint RemoteEndPoint
{
get;
set;
}
internal UdpSocket Socket
{
get;
private set;
}
internal byte[] ReceiveBuffer
{
get;
private set;
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.CloudFormation.Model;
namespace Amazon.CloudFormation
{
/// <summary>
/// Interface for accessing CloudFormation
///
/// AWS CloudFormation
/// <para>
/// AWS CloudFormation enables you to create and manage AWS infrastructure deployments
/// predictably and repeatedly. AWS CloudFormation helps you leverage AWS products such
/// as Amazon EC2, EBS, Amazon SNS, ELB, and Auto Scaling to build highly-reliable, highly
/// scalable, cost effective applications without worrying about creating and configuring
/// the underlying AWS infrastructure.
/// </para>
///
/// <para>
/// With AWS CloudFormation, you declare all of your resources and dependencies in a template
/// file. The template defines a collection of resources as a single unit called a stack.
/// AWS CloudFormation creates and deletes all member resources of the stack together
/// and manages all dependencies between the resources for you.
/// </para>
///
/// <para>
/// For more information about this product, go to the <a href="http://aws.amazon.com/cloudformation/">CloudFormation
/// Product Page</a>.
/// </para>
///
/// <para>
/// Amazon CloudFormation makes use of other AWS products. If you need additional technical
/// information about a specific AWS product, you can find the product's technical documentation
/// at <a href="http://aws.amazon.com/documentation/">http://aws.amazon.com/documentation/</a>.
/// </para>
/// </summary>
public partial interface IAmazonCloudFormation : IDisposable
{
#region CancelUpdateStack
/// <summary>
/// Cancels an update on the specified stack. If the call completes successfully, the
/// stack rolls back the update and reverts to the previous stack configuration.
///
/// <note>You can cancel only stacks that are in the UPDATE_IN_PROGRESS state.</note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CancelUpdateStack service method.</param>
///
/// <returns>The response from the CancelUpdateStack service method, as returned by CloudFormation.</returns>
CancelUpdateStackResponse CancelUpdateStack(CancelUpdateStackRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CancelUpdateStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CancelUpdateStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CancelUpdateStackResponse> CancelUpdateStackAsync(CancelUpdateStackRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateStack
/// <summary>
/// Creates a stack as specified in the template. After the call completes successfully,
/// the stack creation starts. You can check the status of the stack via the <a>DescribeStacks</a>
/// API.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateStack service method.</param>
///
/// <returns>The response from the CreateStack service method, as returned by CloudFormation.</returns>
/// <exception cref="Amazon.CloudFormation.Model.AlreadyExistsException">
/// Resource with the name requested already exists.
/// </exception>
/// <exception cref="Amazon.CloudFormation.Model.InsufficientCapabilitiesException">
/// The template contains resources with capabilities that were not specified in the Capabilities
/// parameter.
/// </exception>
/// <exception cref="Amazon.CloudFormation.Model.LimitExceededException">
/// Quota for the resource has already been reached.
/// </exception>
CreateStackResponse CreateStack(CreateStackRequest request);
/// <summary>
/// Initiates the asynchronous execution of the CreateStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateStackResponse> CreateStackAsync(CreateStackRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DeleteStack
/// <summary>
/// Deletes a specified stack. Once the call completes successfully, stack deletion starts.
/// Deleted stacks do not show up in the <a>DescribeStacks</a> API if the deletion has
/// been completed successfully.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteStack service method.</param>
///
/// <returns>The response from the DeleteStack service method, as returned by CloudFormation.</returns>
DeleteStackResponse DeleteStack(DeleteStackRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DeleteStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DeleteStackResponse> DeleteStackAsync(DeleteStackRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeAccountLimits
/// <summary>
/// Retrieves your account's AWS CloudFormation limits, such as the maximum number of
/// stacks that you can create in your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountLimits service method.</param>
///
/// <returns>The response from the DescribeAccountLimits service method, as returned by CloudFormation.</returns>
DescribeAccountLimitsResponse DescribeAccountLimits(DescribeAccountLimitsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeAccountLimits operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeAccountLimits operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeAccountLimitsResponse> DescribeAccountLimitsAsync(DescribeAccountLimitsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeStackEvents
/// <summary>
/// Returns all stack related events for a specified stack. For more information about
/// a stack's event history, go to <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/concept-stack.html">Stacks</a>
/// in the AWS CloudFormation User Guide.
///
/// <note>You can list events for stacks that have failed to create or have been deleted
/// by specifying the unique stack identifier (stack ID).</note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeStackEvents service method.</param>
///
/// <returns>The response from the DescribeStackEvents service method, as returned by CloudFormation.</returns>
DescribeStackEventsResponse DescribeStackEvents(DescribeStackEventsRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeStackEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStackEvents operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeStackEventsResponse> DescribeStackEventsAsync(DescribeStackEventsRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeStackResource
/// <summary>
/// Returns a description of the specified resource in the specified stack.
///
///
/// <para>
/// For deleted stacks, DescribeStackResource returns resource information for up to 90
/// days after the stack has been deleted.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeStackResource service method.</param>
///
/// <returns>The response from the DescribeStackResource service method, as returned by CloudFormation.</returns>
DescribeStackResourceResponse DescribeStackResource(DescribeStackResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeStackResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStackResource operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeStackResourceResponse> DescribeStackResourceAsync(DescribeStackResourceRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeStackResources
/// <summary>
/// Returns AWS resource descriptions for running and deleted stacks. If <code>StackName</code>
/// is specified, all the associated resources that are part of the stack are returned.
/// If <code>PhysicalResourceId</code> is specified, the associated resources of the stack
/// that the resource belongs to are returned.
///
/// <note>Only the first 100 resources will be returned. If your stack has more resources
/// than this, you should use <code>ListStackResources</code> instead.</note>
/// <para>
/// For deleted stacks, <code>DescribeStackResources</code> returns resource information
/// for up to 90 days after the stack has been deleted.
/// </para>
///
/// <para>
/// You must specify either <code>StackName</code> or <code>PhysicalResourceId</code>,
/// but not both. In addition, you can specify <code>LogicalResourceId</code> to filter
/// the returned result. For more information about resources, the <code>LogicalResourceId</code>
/// and <code>PhysicalResourceId</code>, go to the <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide">AWS
/// CloudFormation User Guide</a>.
/// </para>
/// <note>A <code>ValidationError</code> is returned if you specify both <code>StackName</code>
/// and <code>PhysicalResourceId</code> in the same request.</note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeStackResources service method.</param>
///
/// <returns>The response from the DescribeStackResources service method, as returned by CloudFormation.</returns>
DescribeStackResourcesResponse DescribeStackResources(DescribeStackResourcesRequest request);
/// <summary>
/// Initiates the asynchronous execution of the DescribeStackResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStackResources operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeStackResourcesResponse> DescribeStackResourcesAsync(DescribeStackResourcesRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeStacks
/// <summary>
/// Returns the description for the specified stack; if no stack name was specified, then
/// it returns the description for all the stacks created.
/// </summary>
///
/// <returns>The response from the DescribeStacks service method, as returned by CloudFormation.</returns>
DescribeStacksResponse DescribeStacks();
/// <summary>
/// Returns the description for the specified stack; if no stack name was specified, then
/// it returns the description for all the stacks created.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeStacks service method.</param>
///
/// <returns>The response from the DescribeStacks service method, as returned by CloudFormation.</returns>
DescribeStacksResponse DescribeStacks(DescribeStacksRequest request);
/// <summary>
/// Returns the description for the specified stack; if no stack name was specified, then
/// it returns the description for all the stacks created.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeStacks service method, as returned by CloudFormation.</returns>
Task<DescribeStacksResponse> DescribeStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the DescribeStacks operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeStacks operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeStacksResponse> DescribeStacksAsync(DescribeStacksRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region EstimateTemplateCost
/// <summary>
/// Returns the estimated monthly cost of a template. The return value is an AWS Simple
/// Monthly Calculator URL with a query string that describes the resources required to
/// run the template.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the EstimateTemplateCost service method.</param>
///
/// <returns>The response from the EstimateTemplateCost service method, as returned by CloudFormation.</returns>
EstimateTemplateCostResponse EstimateTemplateCost(EstimateTemplateCostRequest request);
/// <summary>
/// Initiates the asynchronous execution of the EstimateTemplateCost operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the EstimateTemplateCost operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<EstimateTemplateCostResponse> EstimateTemplateCostAsync(EstimateTemplateCostRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetStackPolicy
/// <summary>
/// Returns the stack policy for a specified stack. If a stack doesn't have a policy,
/// a null value is returned.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetStackPolicy service method.</param>
///
/// <returns>The response from the GetStackPolicy service method, as returned by CloudFormation.</returns>
GetStackPolicyResponse GetStackPolicy(GetStackPolicyRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetStackPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetStackPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetStackPolicyResponse> GetStackPolicyAsync(GetStackPolicyRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetTemplate
/// <summary>
/// Returns the template body for a specified stack. You can get the template for running
/// or deleted stacks.
///
///
/// <para>
/// For deleted stacks, GetTemplate returns the template for up to 90 days after the stack
/// has been deleted.
/// </para>
/// <note> If the template does not exist, a <code>ValidationError</code> is returned.
/// </note>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetTemplate service method.</param>
///
/// <returns>The response from the GetTemplate service method, as returned by CloudFormation.</returns>
GetTemplateResponse GetTemplate(GetTemplateRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetTemplate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTemplate operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetTemplateResponse> GetTemplateAsync(GetTemplateRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetTemplateSummary
/// <summary>
/// Returns information about a new or existing template. The <code>GetTemplateSummary</code>
/// action is useful for viewing parameter information, such as default parameter values
/// and parameter types, before you create or update a stack.
///
///
/// <para>
/// You can use the <code>GetTemplateSummary</code> action when you submit a template,
/// or you can get template information for a running or deleted stack.
/// </para>
///
/// <para>
/// For deleted stacks, <code>GetTemplateSummary</code> returns the template information
/// for up to 90 days after the stack has been deleted. If the template does not exist,
/// a <code>ValidationError</code> is returned.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetTemplateSummary service method.</param>
///
/// <returns>The response from the GetTemplateSummary service method, as returned by CloudFormation.</returns>
GetTemplateSummaryResponse GetTemplateSummary(GetTemplateSummaryRequest request);
/// <summary>
/// Initiates the asynchronous execution of the GetTemplateSummary operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTemplateSummary operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetTemplateSummaryResponse> GetTemplateSummaryAsync(GetTemplateSummaryRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListStackResources
/// <summary>
/// Returns descriptions of all resources of the specified stack.
///
///
/// <para>
/// For deleted stacks, ListStackResources returns resource information for up to 90 days
/// after the stack has been deleted.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListStackResources service method.</param>
///
/// <returns>The response from the ListStackResources service method, as returned by CloudFormation.</returns>
ListStackResourcesResponse ListStackResources(ListStackResourcesRequest request);
/// <summary>
/// Initiates the asynchronous execution of the ListStackResources operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListStackResources operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListStackResourcesResponse> ListStackResourcesAsync(ListStackResourcesRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListStacks
/// <summary>
/// Returns the summary information for stacks whose status matches the specified StackStatusFilter.
/// Summary information for stacks that have been deleted is kept for 90 days after the
/// stack is deleted. If no StackStatusFilter is specified, summary information for all
/// stacks is returned (including existing stacks and stacks that have been deleted).
/// </summary>
///
/// <returns>The response from the ListStacks service method, as returned by CloudFormation.</returns>
ListStacksResponse ListStacks();
/// <summary>
/// Returns the summary information for stacks whose status matches the specified StackStatusFilter.
/// Summary information for stacks that have been deleted is kept for 90 days after the
/// stack is deleted. If no StackStatusFilter is specified, summary information for all
/// stacks is returned (including existing stacks and stacks that have been deleted).
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ListStacks service method.</param>
///
/// <returns>The response from the ListStacks service method, as returned by CloudFormation.</returns>
ListStacksResponse ListStacks(ListStacksRequest request);
/// <summary>
/// Returns the summary information for stacks whose status matches the specified StackStatusFilter.
/// Summary information for stacks that have been deleted is kept for 90 days after the
/// stack is deleted. If no StackStatusFilter is specified, summary information for all
/// stacks is returned (including existing stacks and stacks that have been deleted).
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ListStacks service method, as returned by CloudFormation.</returns>
Task<ListStacksResponse> ListStacksAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the ListStacks operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListStacks operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListStacksResponse> ListStacksAsync(ListStacksRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SetStackPolicy
/// <summary>
/// Sets a stack policy for a specified stack.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SetStackPolicy service method.</param>
///
/// <returns>The response from the SetStackPolicy service method, as returned by CloudFormation.</returns>
SetStackPolicyResponse SetStackPolicy(SetStackPolicyRequest request);
/// <summary>
/// Initiates the asynchronous execution of the SetStackPolicy operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SetStackPolicy operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SetStackPolicyResponse> SetStackPolicyAsync(SetStackPolicyRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region SignalResource
/// <summary>
/// Sends a signal to the specified resource with a success or failure status. You can
/// use the SignalResource API in conjunction with a creation policy or update policy.
/// AWS CloudFormation doesn't proceed with a stack creation or update until resources
/// receive the required number of signals or the timeout period is exceeded. The SignalResource
/// API is useful in cases where you want to send signals from anywhere other than an
/// Amazon EC2 instance.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the SignalResource service method.</param>
///
/// <returns>The response from the SignalResource service method, as returned by CloudFormation.</returns>
SignalResourceResponse SignalResource(SignalResourceRequest request);
/// <summary>
/// Initiates the asynchronous execution of the SignalResource operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the SignalResource operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<SignalResourceResponse> SignalResourceAsync(SignalResourceRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region UpdateStack
/// <summary>
/// Updates a stack as specified in the template. After the call completes successfully,
/// the stack update starts. You can check the status of the stack via the <a>DescribeStacks</a>
/// action.
///
///
/// <para>
/// To get a copy of the template for an existing stack, you can use the <a>GetTemplate</a>
/// action.
/// </para>
///
/// <para>
/// Tags that were associated with this stack during creation time will still be associated
/// with the stack after an <code>UpdateStack</code> operation.
/// </para>
///
/// <para>
/// For more information about creating an update template, updating a stack, and monitoring
/// the progress of the update, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks.html">Updating
/// a Stack</a>.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateStack service method.</param>
///
/// <returns>The response from the UpdateStack service method, as returned by CloudFormation.</returns>
/// <exception cref="Amazon.CloudFormation.Model.InsufficientCapabilitiesException">
/// The template contains resources with capabilities that were not specified in the Capabilities
/// parameter.
/// </exception>
UpdateStackResponse UpdateStack(UpdateStackRequest request);
/// <summary>
/// Initiates the asynchronous execution of the UpdateStack operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateStack operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<UpdateStackResponse> UpdateStackAsync(UpdateStackRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ValidateTemplate
/// <summary>
/// Validates a specified template.
/// </summary>
///
/// <returns>The response from the ValidateTemplate service method, as returned by CloudFormation.</returns>
ValidateTemplateResponse ValidateTemplate();
/// <summary>
/// Validates a specified template.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the ValidateTemplate service method.</param>
///
/// <returns>The response from the ValidateTemplate service method, as returned by CloudFormation.</returns>
ValidateTemplateResponse ValidateTemplate(ValidateTemplateRequest request);
/// <summary>
/// Validates a specified template.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the ValidateTemplate service method, as returned by CloudFormation.</returns>
Task<ValidateTemplateResponse> ValidateTemplateAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the ValidateTemplate operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ValidateTemplate operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ValidateTemplateResponse> ValidateTemplateAsync(ValidateTemplateRequest request, CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmEmergencyProcedures.
/// </summary>
public partial class frmInventory : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Label Label2;
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Load_Procedures();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand);
}
#endregion
private void Load_Procedures()
{
if (Session["CInv"].ToString() == "frmProcRReq")
{
btnOK.Visible = false;btnAdd.Text = "Cancel";
DataGrid1.Columns[1].Visible = true;//ItemName
DataGrid1.Columns[2].Visible = true;//OrgName
DataGrid1.Columns[3].Visible = true;//LocName
DataGrid1.Columns[4].Visible = true;//SubLocation
DataGrid1.Columns[5].Visible = true;//Status
DataGrid1.Columns[6].Visible = true;//btnSelect
DataGrid1.Columns[7].Visible = false;//btnUpdate; btnDelete
DataGrid1.Columns[8].Visible = false;//cbxSel
DataGrid1.Columns[9].Visible = false;//OrgId
}
else if (Session["CInv"].ToString() == "frmMainMgr")
{
DataGrid1.Columns[1].Visible = true;//ItemName
DataGrid1.Columns[2].Visible = false;//OrgName
DataGrid1.Columns[3].Visible = true;//LocName
DataGrid1.Columns[4].Visible = true;//SubLocation
DataGrid1.Columns[5].Visible = true;//Status
DataGrid1.Columns[6].Visible = false;//btnSelect
DataGrid1.Columns[7].Visible = true;//btnUpdate; btnDelete
DataGrid1.Columns[8].Visible = false;//cbxSel
DataGrid1.Columns[9].Visible = false;//OrgId
}
if (!IsPostBack)
{
lblOrg.Text=Session["OrgName"].ToString();
lblContents1.Text="";
loadData();
}
}
private void loadData ()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_RetrieveInventory";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
cmd.Parameters.Add("@Caller", SqlDbType.Int);
cmd.Parameters["@Caller"].Value = 1;
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"Inventory");
if (ds.Tables["Inventory"].Rows.Count != 0)
{
Session["ds"] = ds;
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
else if (Session["CInv"].ToString() == "frmProcRReq")// i.e. if no inventory item and requestor is planner
{
Session["CPPR"] = "frmInventory";
Session["btnAction"] = "Add";
Response.Redirect(strURL + "frmUpdProcPReq.aspx?");
}
}
private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
Button btu = (Button)(i.Cells[7].FindControl("btnUpdate"));
Button btd = (Button)(i.Cells[7].FindControl("btnDelete"));
if (Session["OrgId"].ToString() != i.Cells[9].Text)
{
btu.Visible=false;
btd.Visible=false;
i.Cells[7].Text = "Externally Maintained";
}
}
}
private void updateGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[10].FindControl("cbxSel"));
if (cb.Checked)
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_AddProcureInventory";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@ProcurementsId", SqlDbType.Int);
cmd.Parameters ["@ProcurementsId"].Value=Session["ProcurementsId"].ToString();
cmd.Parameters.Add("@InventoryId", SqlDbType.Int);
cmd.Parameters ["@InventoryId"].Value=i.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Select")
{
//if (Session["CallerPeople"].ToString() == "frmProcSReq")
Session["InventoryId"] = e.Item.Cells[0].Text;
Exit();
}
else if (e.CommandName == "Update")
{
Session["CallerUpdInv"]="frmInventory";
Response.Redirect (strURL + "frmUpdInventory.aspx?"
+ "&btnAction=Update"
+ "&Id=" + e.Item.Cells[0].Text);
}
else if (e.CommandName == "Delete")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="eps_DeleteInventory";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
protected void btnAdd_Click(object sender, System.EventArgs e)
{
if (btnAdd.Text=="Add")
{
Session["CallerUpdInv"]="frmInventory";
Response.Redirect (strURL + "frmUpdInventory.aspx?"
+ "&btnAction=" + "Add");
}
else
{
Exit();
}
}
private void Exit()
{
Response.Redirect (strURL + Session["CInv"].ToString() + ".aspx?");
}
protected void btnOK_Click(object sender, EventArgs e)
{
//updateGrid();
Exit();
}
}
}
| |
using UnityEngine;
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
public enum RuleResult { Done, Working }
namespace Casanova.Prelude
{
public class Tuple<T,E> {
public T Item1 { get; set;}
public E Item2 { get; set;}
public Tuple(T item1, E item2)
{
Item1 = item1;
Item2 = item2;
}
}
public static class MyExtensions
{
//public T this[List<T> list]
//{
// get { return list.ElementAt(0); }
//}
public static T Head<T>(this List<T> list) { return list.ElementAt(0); }
public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); }
public static int Length<T>(this List<T> list) { return list.Count; }
public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; }
}
public class Cons<T> : IEnumerable<T>
{
public class Enumerator : IEnumerator<T>
{
public Enumerator(Cons<T> parent)
{
firstEnumerated = 0;
this.parent = parent;
tailEnumerator = parent.tail.GetEnumerator();
}
byte firstEnumerated;
Cons<T> parent;
IEnumerator<T> tailEnumerator;
public T Current
{
get
{
if (firstEnumerated == 0) return default(T);
if (firstEnumerated == 1) return parent.head;
else return tailEnumerator.Current;
}
}
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext()
{
if (firstEnumerated == 0)
{
if (parent.head == null) return false;
firstEnumerated++;
return true;
}
if (firstEnumerated == 1) firstEnumerated++;
return tailEnumerator.MoveNext();
}
public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); }
public void Dispose() { }
}
T head;
IEnumerable<T> tail;
public Cons(T head, IEnumerable<T> tail)
{
this.head = head;
this.tail = tail;
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
}
public class Empty<T> : IEnumerable<T>
{
public Empty() { }
public class Enumerator : IEnumerator<T>
{
public T Current { get { throw new Exception("Empty sequence has no elements"); } }
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext() { return false; }
public void Reset() { }
public void Dispose() { }
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator();
}
}
public abstract class Option<T> : IComparable, IEquatable<Option<T>>
{
public bool IsSome;
public bool IsNone { get { return !IsSome; } }
protected abstract Just<T> Some { get; }
public U Match<U>(Func<T,U> f, Func<U> g) {
if (this.IsSome)
return f(this.Some.Value);
else
return g();
}
public bool Equals(Option<T> b)
{
return this.Match(
x => b.Match(
y => x.Equals(y),
() => false),
() => b.Match(
y => false,
() => true));
}
public override bool Equals(System.Object other)
{
if (other == null) return false;
if (other is Option<T>)
{
var other1 = other as Option<T>;
return this.Equals(other1);
}
return false;
}
public override int GetHashCode() { return this.GetHashCode(); }
public static bool operator ==(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return a.Equals(b);
}
public static bool operator !=(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return !(a.Equals(b));
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (obj is Option<T>)
{
var obj1 = obj as Option<T>;
if (this.Equals(obj1)) return 0;
}
return -1;
}
abstract public T Value { get; }
public override string ToString()
{
return "Option<" + typeof(T).ToString() + ">";
}
}
public class Just<T> : Option<T>
{
T elem;
public Just(T elem) { this.elem = elem; this.IsSome = true; }
protected override Just<T> Some { get { return this; } }
public override T Value { get { return elem; } }
}
public class Nothing<T> : Option<T>
{
public Nothing() { this.IsSome = false; }
protected override Just<T> Some { get { return null; } }
public override T Value { get { throw new Exception("Cant get a value from a None object"); } }
}
public class Utils
{
public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e)
{
if (c())
return t();
else
return e();
}
}
}
public class FastStack
{
public int[] Elements;
public int Top;
public FastStack(int elems)
{
Top = 0;
Elements = new int[elems];
}
public void Clear() { Top = 0; }
public void Push(int x) { Elements[Top++] = x; }
}
public class RuleTable
{
public RuleTable(int elems)
{
ActiveIndices = new FastStack(elems);
SupportStack = new FastStack(elems);
ActiveSlots = new bool[elems];
}
public FastStack ActiveIndices;
public FastStack SupportStack;
public bool[] ActiveSlots;
public void Add(int i)
{
if (!ActiveSlots[i])
{
ActiveSlots[i] = true;
ActiveIndices.Push(i);
}
}
}
public class World : MonoBehaviour{
void Update () { Update(Time.deltaTime, this); }
public void Start()
{ UnityCube = UnityCube.Find();
}
public UnityCube UnityCube;
public void Update(float dt, World world) {
this.Rule0(dt, world);
}
public void Rule0(float dt, World world)
{
UnityCube.Position = (UnityCube.Position) + (new UnityEngine.Vector3((1f) * (dt),0f,0f));
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: ContainerParagraph.cs
//
// Description: Text line formatter.
//
// History:
// 05/05/2003 : [....] - moving from Avalon branch.
//
//---------------------------------------------------------------------------
#pragma warning disable 1634, 1691 // avoid generating warnings about unknown
// message numbers and unknown pragmas for PRESharp contol
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security; // SecurityCritical
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using MS.Internal.Text;
using MS.Internal.Documents;
using MS.Internal.PtsHost.UnsafeNativeMethods;
namespace MS.Internal.PtsHost
{
/// <summary>
/// Text line formatter.
/// </summary>
/// <remarks>
/// NOTE: All DCPs used during line formatting are related to cpPara.
/// To get abosolute CP, add cpPara to a dcp value.
/// </remarks>
internal sealed class OptimalTextSource : LineBase
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="host">
/// TextFormatter host
/// </param>
/// <param name="cpPara">
/// Character position of paragraph
/// </param>
/// <param name="durTrack">
/// Track width
/// </param>
/// <param name="paraClient">
/// Owner of the line
/// </param>
/// <param name="runCache">
/// Text run cache
/// </param>
internal OptimalTextSource(TextFormatterHost host, int cpPara, int durTrack, TextParaClient paraClient, TextRunCache runCache) : base(paraClient)
{
_host = host;
_durTrack = durTrack;
_runCache = runCache;
_cpPara = cpPara;
}
/// <summary>
/// Free all resources associated with the line. Prepare it for reuse.
/// </summary>
public override void Dispose()
{
base.Dispose();
}
#endregion Constructors
// ------------------------------------------------------------------
//
// TextSource Implementation
//
// ------------------------------------------------------------------
#region TextSource Implementation
/// <summary>
/// Get a text run at specified text source position and return it.
/// </summary>
/// <param name="dcp">
/// dcp of position relative to start of line
/// </param>
internal override TextRun GetTextRun(int dcp)
{
TextRun run = null;
ITextContainer textContainer = _paraClient.Paragraph.StructuralCache.TextContainer;
StaticTextPointer position = textContainer.CreateStaticPointerAtOffset(_cpPara + dcp);
switch (position.GetPointerContext(LogicalDirection.Forward))
{
case TextPointerContext.Text:
run = HandleText(position);
break;
case TextPointerContext.ElementStart:
run = HandleElementStartEdge(position);
break;
case TextPointerContext.ElementEnd:
run = HandleElementEndEdge(position);
break;
case TextPointerContext.EmbeddedElement:
run = HandleEmbeddedObject(dcp, position);
break;
case TextPointerContext.None:
run = new ParagraphBreakRun(_syntheticCharacterLength, PTS.FSFLRES.fsflrEndOfParagraph);
break;
}
Invariant.Assert(run != null, "TextRun has not been created.");
Invariant.Assert(run.Length > 0, "TextRun has to have positive length.");
return run;
}
/// <summary>
/// Get text immediately before specified text source position. Return CharacterBufferRange
/// containing this text.
/// </summary>
/// <param name="dcp">
/// dcp of position relative to start of line
/// </param>
internal override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int dcp)
{
// Parameter validation
Invariant.Assert(dcp >= 0);
int nonTextLength = 0;
CharacterBufferRange precedingText = CharacterBufferRange.Empty;
CultureInfo culture = null;
if (dcp > 0)
{
// Create TextPointer at dcp, and pointer at paragraph start to compare
ITextPointer startPosition = TextContainerHelper.GetTextPointerFromCP(_paraClient.Paragraph.StructuralCache.TextContainer, _cpPara, LogicalDirection.Forward);
ITextPointer position = TextContainerHelper.GetTextPointerFromCP(_paraClient.Paragraph.StructuralCache.TextContainer, _cpPara + dcp, LogicalDirection.Forward);
// Move backward until we find a position at the end of a text run, or reach start of TextContainer
while (position.GetPointerContext(LogicalDirection.Backward) != TextPointerContext.Text &&
position.CompareTo(startPosition) != 0)
{
position.MoveByOffset(-1);
nonTextLength++;
}
// Return text in run. If it is at start of TextContainer this will return an empty string
string precedingTextString = position.GetTextInRun(LogicalDirection.Backward);
precedingText = new CharacterBufferRange(precedingTextString, 0, precedingTextString.Length);
StaticTextPointer pointer = position.CreateStaticPointer();
DependencyObject element = (pointer.Parent != null) ? pointer.Parent : _paraClient.Paragraph.Element;
culture = DynamicPropertyReader.GetCultureInfo(element);
}
return new TextSpan<CultureSpecificCharacterBufferRange>(
nonTextLength + precedingText.Length,
new CultureSpecificCharacterBufferRange(culture, precedingText)
);
}
/// <summary>
/// Get Text effect index from text source character index. Return int value of Text effect index.
/// </summary>
/// <param name="dcp">
/// dcp of CharacterHit relative to start of line
/// </param>
internal override int GetTextEffectCharacterIndexFromTextSourceCharacterIndex(int dcp)
{
// Text effect index is an index relative to the start of the Text Container.
// To convert a text source index to text effect index, we first convert the dcp into text pointer
// and call GetDistance() from the start of the text container.
ITextPointer position = TextContainerHelper.GetTextPointerFromCP(_paraClient.Paragraph.StructuralCache.TextContainer, _cpPara + dcp, LogicalDirection.Forward);
return position.TextContainer.Start.GetOffsetToPosition(position);
}
#endregion TextSource Implementation
internal PTS.FSFLRES GetFormatResultForBreakpoint(int dcp, TextBreakpoint textBreakpoint)
{
int dcpRun = 0;
PTS.FSFLRES formatResult = PTS.FSFLRES.fsflrOutOfSpace;
foreach (TextSpan<TextRun> textSpan in _runCache.GetTextRunSpans())
{
TextRun run = textSpan.Value;
if (run != null && ((dcpRun + run.Length) >= (dcp + textBreakpoint.Length)))
{
if (run is ParagraphBreakRun)
{
formatResult = ((ParagraphBreakRun)run).BreakReason;
}
else if (run is LineBreakRun)
{
formatResult = ((LineBreakRun)run).BreakReason;
}
break;
}
dcpRun += textSpan.Length;
}
return formatResult;
}
/// <summary>
/// Measure child UIElement.
/// </summary>
/// <param name="inlineObject">
/// Element whose size we are measuring
/// </param>
/// <returns>
/// Size of the child UIElement
/// </returns>
internal Size MeasureChild(InlineObjectRun inlineObject)
{
// Always measure at infinity for bottomless, consistent constraint.
double pageHeight = _paraClient.Paragraph.StructuralCache.CurrentFormatContext.DocumentPageSize.Height;
if (!_paraClient.Paragraph.StructuralCache.CurrentFormatContext.FinitePage)
{
pageHeight = Double.PositiveInfinity;
}
return inlineObject.UIElementIsland.DoLayout(new Size(TextDpi.FromTextDpi(_durTrack), pageHeight), true, true);
}
/// <summary>
/// TextFormatter host
/// </summary>
private readonly TextFormatterHost _host;
private TextRunCache _runCache;
private int _durTrack;
private int _cpPara;
}
}
#pragma warning enable 1634, 1691
| |
//-----------------------------------------------------------------------
// <copyright file="InputStreamSinkStage.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.IO;
using Akka.IO;
using Akka.Pattern;
using Akka.Streams.Implementation.Stages;
using Akka.Streams.Stage;
using static Akka.Streams.Implementation.IO.InputStreamSinkStage;
namespace Akka.Streams.Implementation.IO
{
/// <summary>
/// INTERNAL API
/// </summary>
internal class InputStreamSinkStage : GraphStageWithMaterializedValue<SinkShape<ByteString>, Stream>
{
#region internal classes
/// <summary>
/// TBD
/// </summary>
internal interface IAdapterToStageMessage
{
}
/// <summary>
/// TBD
/// </summary>
internal class ReadElementAcknowledgement : IAdapterToStageMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly ReadElementAcknowledgement Instance = new ReadElementAcknowledgement();
private ReadElementAcknowledgement()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal class Close : IAdapterToStageMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly Close Instance = new Close();
private Close()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal interface IStreamToAdapterMessage
{
}
/// <summary>
/// TBD
/// </summary>
internal struct Data : IStreamToAdapterMessage
{
/// <summary>
/// TBD
/// </summary>
public readonly ByteString Bytes;
/// <summary>
/// TBD
/// </summary>
/// <param name="bytes">TBD</param>
public Data(ByteString bytes)
{
Bytes = bytes;
}
}
/// <summary>
/// TBD
/// </summary>
internal class Finished : IStreamToAdapterMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly Finished Instance = new Finished();
private Finished()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal class Initialized : IStreamToAdapterMessage
{
/// <summary>
/// TBD
/// </summary>
public static readonly Initialized Instance = new Initialized();
private Initialized()
{
}
}
/// <summary>
/// TBD
/// </summary>
internal struct Failed : IStreamToAdapterMessage
{
/// <summary>
/// TBD
/// </summary>
public readonly Exception Cause;
/// <summary>
/// TBD
/// </summary>
/// <param name="cause">TBD</param>
public Failed(Exception cause)
{
Cause = cause;
}
}
/// <summary>
/// TBD
/// </summary>
internal interface IStageWithCallback
{
/// <summary>
/// TBD
/// </summary>
/// <param name="msg">TBD</param>
void WakeUp(IAdapterToStageMessage msg);
}
private sealed class Logic : InGraphStageLogic, IStageWithCallback
{
private readonly InputStreamSinkStage _stage;
private readonly Action<IAdapterToStageMessage> _callback;
public Logic(InputStreamSinkStage stage) : base(stage.Shape)
{
_stage = stage;
_callback = GetAsyncCallback((IAdapterToStageMessage message) =>
{
if (message is ReadElementAcknowledgement)
SendPullIfAllowed();
else if (message is Close)
CompleteStage();
});
SetHandler(stage._in, this);
}
public override void OnPush()
{
//1 is buffer for Finished or Failed callback
if (_stage._dataQueue.Count + 1 == _stage._dataQueue.BoundedCapacity)
throw new BufferOverflowException("Queue is full");
_stage._dataQueue.Add(new Data(Grab(_stage._in)));
if (_stage._dataQueue.BoundedCapacity - _stage._dataQueue.Count > 1)
SendPullIfAllowed();
}
public override void OnUpstreamFinish()
{
_stage._dataQueue.Add(Finished.Instance);
CompleteStage();
}
public override void OnUpstreamFailure(Exception ex)
{
_stage._dataQueue.Add(new Failed(ex));
FailStage(ex);
}
public override void PreStart()
{
_stage._dataQueue.Add(Initialized.Instance);
Pull(_stage._in);
}
public void WakeUp(IAdapterToStageMessage msg) => _callback(msg);
private void SendPullIfAllowed()
{
if (_stage._dataQueue.BoundedCapacity - _stage._dataQueue.Count > 1 && !HasBeenPulled(_stage._in))
Pull(_stage._in);
}
}
#endregion
private readonly Inlet<ByteString> _in = new Inlet<ByteString>("InputStreamSink.in");
private readonly TimeSpan _readTimeout;
private BlockingCollection<IStreamToAdapterMessage> _dataQueue;
/// <summary>
/// TBD
/// </summary>
/// <param name="readTimeout">TBD</param>
public InputStreamSinkStage(TimeSpan readTimeout)
{
_readTimeout = readTimeout;
Shape = new SinkShape<ByteString>(_in);
}
/// <summary>
/// TBD
/// </summary>
protected override Attributes InitialAttributes => DefaultAttributes.InputStreamSink;
/// <summary>
/// TBD
/// </summary>
public override SinkShape<ByteString> Shape { get; }
/// <summary>
/// TBD
/// </summary>
/// <param name="inheritedAttributes">TBD</param>
/// <exception cref="ArgumentException">
/// This exception is thrown when the maximum size of the input buffer is less than or equal to zero.
/// </exception>
/// <returns>TBD</returns>
public override ILogicAndMaterializedValue<Stream> CreateLogicAndMaterializedValue(
Attributes inheritedAttributes)
{
var maxBuffer = inheritedAttributes.GetAttribute(new Attributes.InputBuffer(16, 16)).Max;
if (maxBuffer <= 0)
throw new ArgumentException("Buffer size must be greater than 0");
_dataQueue = new BlockingCollection<IStreamToAdapterMessage>(maxBuffer + 2);
var logic = new Logic(this);
return new LogicAndMaterializedValue<Stream>(logic,
new InputStreamAdapter(_dataQueue, logic, _readTimeout));
}
}
/// <summary>
/// INTERNAL API
/// InputStreamAdapter that interacts with InputStreamSinkStage
/// </summary>
internal class InputStreamAdapter : Stream
{
#region not supported
/// <summary>
/// TBD
/// </summary>
/// <exception cref="NotSupportedException">TBD</exception>
public override void Flush() => throw new NotSupportedException("This stream can only read");
/// <summary>
/// TBD
/// </summary>
/// <param name="offset">TBD</param>
/// <param name="origin">TBD</param>
/// <exception cref="NotSupportedException">TBD</exception>
/// <returns>TBD</returns>
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(
"This stream can only read");
/// <summary>
/// TBD
/// </summary>
/// <param name="value">TBD</param>
/// <exception cref="NotSupportedException">TBD</exception>
/// <returns>TBD</returns>
public override void SetLength(long value) => throw new NotSupportedException("This stream can only read");
/// <summary>
/// TBD
/// </summary>
/// <param name="buffer">TBD</param>
/// <param name="offset">TBD</param>
/// <param name="count">TBD</param>
/// <exception cref="NotSupportedException">TBD</exception>
/// <returns>TBD</returns>
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(
"This stream can only read");
/// <summary>
/// TBD
/// </summary>
/// <exception cref="NotSupportedException">TBD</exception>
public override long Length => throw new NotSupportedException("This stream can only read");
/// <summary>
/// TBD
/// </summary>
/// <exception cref="NotSupportedException">TBD</exception>
public override long Position
{
get => throw new NotSupportedException("This stream can only read");
set => throw new NotSupportedException("This stream can only read");
}
#endregion
private static readonly Exception SubscriberClosedException =
new IOException("Reactive stream is terminated, no reads are possible");
private readonly BlockingCollection<IStreamToAdapterMessage> _sharedBuffer;
private readonly IStageWithCallback _sendToStage;
private readonly TimeSpan _readTimeout;
private bool _isActive = true;
private bool _isStageAlive = true;
private bool _isInitialized;
private ByteString _detachedChunk;
/// <summary>
/// TBD
/// </summary>
/// <param name="sharedBuffer">TBD</param>
/// <param name="sendToStage">TBD</param>
/// <param name="readTimeout">TBD</param>
public InputStreamAdapter(BlockingCollection<IStreamToAdapterMessage> sharedBuffer,
IStageWithCallback sendToStage, TimeSpan readTimeout)
{
_sharedBuffer = sharedBuffer;
_sendToStage = sendToStage;
_readTimeout = readTimeout;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="disposing">TBD</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
ExecuteIfNotClosed(() =>
{
// at this point Subscriber may be already terminated
if (_isStageAlive)
_sendToStage.WakeUp(InputStreamSinkStage.Close.Instance);
_isActive = false;
return NotUsed.Instance;
});
}
/// <summary>
/// TBD
/// </summary>
/// <exception cref="IllegalStateException">
/// This exception is thrown when an <see cref="Initialized"/> message is not the first message.
/// </exception>
/// <exception cref="IOException">
/// This exception is thrown when a timeout occurs waiting on new data.
/// </exception>
/// <returns>TBD</returns>
public sealed override int ReadByte()
{
var a = new byte[1];
return Read(a, 0, 1) != 0 ? a[0] & 0xff : -1;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="buffer">TBD</param>
/// <param name="offset">TBD</param>
/// <param name="count">TBD</param>
/// <exception cref="ArgumentException">TBD
/// This exception is thrown for a number of reasons. These include:
/// <ul>
/// <li>the specified <paramref name="buffer"/> size is less than or equal to zero</li>
/// <li>the specified <paramref name="buffer"/> size is less than the combination of <paramref name="offset"/> and <paramref name="count"/></li>
/// <li>the specified <paramref name="offset"/> is less than zero</li>
/// <li>the specified <paramref name="count"/> is less than or equal to zero</li>
/// </ul>
/// </exception>
/// <exception cref="IllegalStateException">
/// This exception is thrown when an <see cref="Initialized"/> message is not the first message.
/// </exception>
/// <exception cref="IOException">
/// This exception is thrown when a timeout occurs waiting on new data.
/// </exception>
/// <returns>TBD</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer.Length <= 0) throw new ArgumentException("array size must be > 0", nameof(buffer));
if (offset < 0) throw new ArgumentException("offset must be >= 0", nameof(offset));
if (count <= 0) throw new ArgumentException("count must be > 0", nameof(count));
if (offset + count > buffer.Length)
throw new ArgumentException("offset + count must be smaller or equal to the array length");
return ExecuteIfNotClosed(() =>
{
if (!_isStageAlive)
return 0;
if (_detachedChunk != null)
return ReadBytes(buffer, offset, count);
var success = _sharedBuffer.TryTake(out var msg, _readTimeout);
if (!success)
throw new IOException("Timeout on waiting for new data");
if (msg is Data data)
{
_detachedChunk = data.Bytes;
return ReadBytes(buffer, offset, count);
}
if (msg is Finished)
{
_isStageAlive = false;
return 0;
}
if (msg is Failed failed)
{
_isStageAlive = false;
throw failed.Cause;
}
throw new IllegalStateException("message 'Initialized' must come first");
});
}
private T ExecuteIfNotClosed<T>(Func<T> f)
{
if (_isActive)
{
WaitIfNotInitialized();
return f();
}
throw SubscriberClosedException;
}
private void WaitIfNotInitialized()
{
if (_isInitialized)
return;
if (_sharedBuffer.TryTake(out var message, _readTimeout))
{
if (message is Initialized)
_isInitialized = true;
else
throw new IllegalStateException("First message must be Initialized notification");
}
else
throw new IOException($"Timeout after {_readTimeout} waiting Initialized message from stage");
}
private int ReadBytes(byte[] buffer, int offset, int count)
{
if (_detachedChunk == null || _detachedChunk.IsEmpty)
throw new InvalidOperationException("Chunk must be pulled from shared buffer");
var availableInChunk = _detachedChunk.Count;
var readBytes = GetData(buffer, offset, count, 0);
if (readBytes >= availableInChunk)
_sendToStage.WakeUp(ReadElementAcknowledgement.Instance);
return readBytes;
}
private int GetData(byte[] buffer, int offset, int count, int gotBytes)
{
var chunk = GrabDataChunk();
if (chunk == null)
return gotBytes;
var size = chunk.Count;
if (size <= count)
{
Array.Copy(chunk.ToArray(), 0, buffer, offset, size);
_detachedChunk = null;
if (size == count)
return gotBytes + size;
return GetData(buffer, offset + size, count - size, gotBytes + size);
}
Array.Copy(chunk.ToArray(), 0, buffer, offset, count);
_detachedChunk = chunk.Slice(count);
return gotBytes + count;
}
private ByteString GrabDataChunk()
{
if (_detachedChunk != null)
return _detachedChunk;
var chunk = _sharedBuffer.Take();
if (chunk is Data data)
{
_detachedChunk = data.Bytes;
return _detachedChunk;
}
if (chunk is Finished)
_isStageAlive = false;
return null;
}
/// <summary>
/// TBD
/// </summary>
public override bool CanRead => true;
/// <summary>
/// TBD
/// </summary>
public override bool CanSeek => false;
/// <summary>
/// TBD
/// </summary>
public override bool CanWrite => false;
}
}
| |
// MIT License
//
// Copyright (c) 2017 Maarten van Sambeek.
//
// 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 ConnectQl.AsyncEnumerables.Enumerators
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using JetBrains.Annotations;
/// <summary>
/// Enumerator used by the <see cref="AsyncEnumerableExtensions.GroupBy{TSource,TKey}"/> method.
/// </summary>
/// <typeparam name="TSource">
/// The type of the source elements.
/// </typeparam>
/// <typeparam name="TKey">
/// The type of the keys.
/// </typeparam>
internal class GroupByEnumerator<TSource, TKey> : AsyncEnumeratorBase<IAsyncGrouping<TSource, TKey>>
{
/// <summary>
/// The comparer.
/// </summary>
private IComparer<TKey> comparer;
/// <summary>
/// The enumerator.
/// </summary>
private IAsyncEnumerator<SourceKey<TSource, TKey>> enumerator;
/// <summary>
/// The key selector.
/// </summary>
private Func<TSource, TKey> keySelector;
/// <summary>
/// The last key.
/// </summary>
private TKey lastKey;
/// <summary>
/// The last offset.
/// </summary>
private long lastOffset;
/// <summary>
/// The offset.
/// </summary>
private long offset;
/// <summary>
/// The sorted.
/// </summary>
private IAsyncReadOnlyCollection<SourceKey<TSource, TKey>> sorted;
/// <summary>
/// The source.
/// </summary>
private IAsyncEnumerable<SourceKey<TSource, TKey>> source;
/// <summary>
/// The state.
/// </summary>
private byte state;
/// <summary>
/// Initializes a new instance of the <see cref="GroupByEnumerator{TSource,TKey}"/> class.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="keySelector">
/// The key selector.
/// </param>
/// <param name="comparer">
/// The comparer.
/// </param>
public GroupByEnumerator(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
this.source = source.Select(s => new SourceKey<TSource, TKey>(s, keySelector(s)));
this.keySelector = keySelector;
this.comparer = comparer;
}
/// <summary>
/// Gets a value indicating whether the enumerator is synchronous.
/// When <c>false</c>, <see cref="IAsyncEnumerator{T}.NextBatchAsync"/> must be called when
/// <see cref="IAsyncEnumerator{T}.MoveNext"/> returns <c>false</c>.
/// </summary>
public override bool IsSynchronous => false;
/// <summary>
/// Resets all fields to null, and sets the state to 'disposed'.
/// </summary>
/// <param name="disposing">
/// The disposing.
/// </param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this.state = 3;
this.enumerator?.Dispose();
this.source = null;
this.keySelector = null;
this.comparer = null;
this.sorted = null;
this.enumerator = null;
this.lastKey = default(TKey);
}
/// <summary>
/// Gets the initial batch.
/// </summary>
/// <returns>
/// The enumerator.
/// </returns>
[CanBeNull]
protected override IEnumerator<IAsyncGrouping<TSource, TKey>> InitialBatch()
{
return null;
}
/// <summary>
/// Moves to the next batch. Implemented as a state machine.
/// </summary>
/// <returns>
/// <c>true</c> if another batch is available, <c>false</c> otherwise.
/// </returns>
protected override async Task<IEnumerator<IAsyncGrouping<TSource, TKey>>> OnNextBatchAsync()
{
switch (this.state)
{
case 0: // Initial, sort the source, and return the first groupings.
Comparison<SourceKey<TSource, TKey>> comparison = (first, second) => this.comparer.Compare(first.Key, second.Key);
this.sorted = await this.source.Policy.SortAsync(this.source, comparison).ConfigureAwait(false);
this.enumerator = this.sorted.GetAsyncEnumerator();
this.state = 1;
return this.EnumerateGroupings();
case 1: // Continue, return the next groupings.
if (!await this.enumerator.NextBatchAsync().ConfigureAwait(false))
{
this.state = 2;
return this.offset == this.lastOffset
? null
: GroupByEnumerator<TSource, TKey>.EnumerateItem(new AsyncGrouping<TSource, TKey>(this.lastKey, this.sorted, this.lastOffset, this.offset - this.lastOffset));
}
return this.EnumerateGroupings();
case 2: // Done, no more groupings available.
return null;
case 3: // Disposed, throw error.
throw new ObjectDisposedException(this.GetType().ToString());
default: // Shouldn't happen.
throw new InvalidOperationException($"Invalid state: {this.state}.");
}
}
/// <summary>
/// Enumerates the item.
/// </summary>
/// <param name="asyncGrouping">
/// The async grouping.
/// </param>
/// <returns>
/// The <see cref="IEnumerator{T}"/>.
/// </returns>
private static IEnumerator<IAsyncGrouping<TSource, TKey>> EnumerateItem(IAsyncGrouping<TSource, TKey> asyncGrouping)
{
yield return asyncGrouping;
}
/// <summary>
/// Enumerates the groupings in a batch.
/// </summary>
/// <returns>
/// The groupings.
/// </returns>
private IEnumerator<AsyncGrouping<TSource, TKey>> EnumerateGroupings()
{
while (this.enumerator.MoveNext())
{
var key = this.enumerator.Current.Key;
if (this.comparer.Compare(key, this.lastKey) != 0)
{
if (this.offset != 0)
{
yield return new AsyncGrouping<TSource, TKey>(key, this.sorted, this.lastOffset, this.offset - this.lastOffset);
this.lastOffset = this.offset;
}
this.lastKey = key;
}
this.offset++;
}
if (!this.enumerator.IsSynchronous)
{
yield break;
}
if (this.offset != this.lastOffset)
{
yield return new AsyncGrouping<TSource, TKey>(this.lastKey, this.sorted, this.lastOffset, this.offset - this.lastOffset);
}
this.state = 2;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Datastore.V1.Snippets
{
using Google.Protobuf;
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedDatastoreClientSnippets
{
/// <summary>Snippet for Lookup</summary>
public void LookupRequestObject()
{
// Snippet: Lookup(LookupRequest, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "",
};
// Make the request
LookupResponse response = datastoreClient.Lookup(request);
// End snippet
}
/// <summary>Snippet for LookupAsync</summary>
public async Task LookupRequestObjectAsync()
{
// Snippet: LookupAsync(LookupRequest, CallSettings)
// Additional: LookupAsync(LookupRequest, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
LookupRequest request = new LookupRequest
{
ReadOptions = new ReadOptions(),
Keys = { new Key(), },
ProjectId = "",
};
// Make the request
LookupResponse response = await datastoreClient.LookupAsync(request);
// End snippet
}
/// <summary>Snippet for Lookup</summary>
public void Lookup()
{
// Snippet: Lookup(string, ReadOptions, IEnumerable<Key>, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
string projectId = "";
ReadOptions readOptions = new ReadOptions();
IEnumerable<Key> keys = new Key[] { new Key(), };
// Make the request
LookupResponse response = datastoreClient.Lookup(projectId, readOptions, keys);
// End snippet
}
/// <summary>Snippet for LookupAsync</summary>
public async Task LookupAsync()
{
// Snippet: LookupAsync(string, ReadOptions, IEnumerable<Key>, CallSettings)
// Additional: LookupAsync(string, ReadOptions, IEnumerable<Key>, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
ReadOptions readOptions = new ReadOptions();
IEnumerable<Key> keys = new Key[] { new Key(), };
// Make the request
LookupResponse response = await datastoreClient.LookupAsync(projectId, readOptions, keys);
// End snippet
}
/// <summary>Snippet for RunQuery</summary>
public void RunQueryRequestObject()
{
// Snippet: RunQuery(RunQueryRequest, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
RunQueryRequest request = new RunQueryRequest
{
ReadOptions = new ReadOptions(),
PartitionId = new PartitionId(),
Query = new Query(),
ProjectId = "",
};
// Make the request
RunQueryResponse response = datastoreClient.RunQuery(request);
// End snippet
}
/// <summary>Snippet for RunQueryAsync</summary>
public async Task RunQueryRequestObjectAsync()
{
// Snippet: RunQueryAsync(RunQueryRequest, CallSettings)
// Additional: RunQueryAsync(RunQueryRequest, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
RunQueryRequest request = new RunQueryRequest
{
ReadOptions = new ReadOptions(),
PartitionId = new PartitionId(),
Query = new Query(),
ProjectId = "",
};
// Make the request
RunQueryResponse response = await datastoreClient.RunQueryAsync(request);
// End snippet
}
/// <summary>Snippet for BeginTransaction</summary>
public void BeginTransactionRequestObject()
{
// Snippet: BeginTransaction(BeginTransactionRequest, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "",
TransactionOptions = new TransactionOptions(),
};
// Make the request
BeginTransactionResponse response = datastoreClient.BeginTransaction(request);
// End snippet
}
/// <summary>Snippet for BeginTransactionAsync</summary>
public async Task BeginTransactionRequestObjectAsync()
{
// Snippet: BeginTransactionAsync(BeginTransactionRequest, CallSettings)
// Additional: BeginTransactionAsync(BeginTransactionRequest, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
ProjectId = "",
TransactionOptions = new TransactionOptions(),
};
// Make the request
BeginTransactionResponse response = await datastoreClient.BeginTransactionAsync(request);
// End snippet
}
/// <summary>Snippet for BeginTransaction</summary>
public void BeginTransaction()
{
// Snippet: BeginTransaction(string, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
string projectId = "";
// Make the request
BeginTransactionResponse response = datastoreClient.BeginTransaction(projectId);
// End snippet
}
/// <summary>Snippet for BeginTransactionAsync</summary>
public async Task BeginTransactionAsync()
{
// Snippet: BeginTransactionAsync(string, CallSettings)
// Additional: BeginTransactionAsync(string, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
// Make the request
BeginTransactionResponse response = await datastoreClient.BeginTransactionAsync(projectId);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void CommitRequestObject()
{
// Snippet: Commit(CommitRequest, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
Transaction = ByteString.Empty,
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "",
};
// Make the request
CommitResponse response = datastoreClient.Commit(request);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task CommitRequestObjectAsync()
{
// Snippet: CommitAsync(CommitRequest, CallSettings)
// Additional: CommitAsync(CommitRequest, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
Transaction = ByteString.Empty,
Mode = CommitRequest.Types.Mode.Unspecified,
Mutations = { new Mutation(), },
ProjectId = "",
};
// Make the request
CommitResponse response = await datastoreClient.CommitAsync(request);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void Commit1()
{
// Snippet: Commit(string, CommitRequest.Types.Mode, ByteString, IEnumerable<Mutation>, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
string projectId = "";
CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified;
ByteString transaction = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = datastoreClient.Commit(projectId, mode, transaction, mutations);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task Commit1Async()
{
// Snippet: CommitAsync(string, CommitRequest.Types.Mode, ByteString, IEnumerable<Mutation>, CallSettings)
// Additional: CommitAsync(string, CommitRequest.Types.Mode, ByteString, IEnumerable<Mutation>, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified;
ByteString transaction = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, transaction, mutations);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void Commit2()
{
// Snippet: Commit(string, CommitRequest.Types.Mode, IEnumerable<Mutation>, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
string projectId = "";
CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = datastoreClient.Commit(projectId, mode, mutations);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task Commit2Async()
{
// Snippet: CommitAsync(string, CommitRequest.Types.Mode, IEnumerable<Mutation>, CallSettings)
// Additional: CommitAsync(string, CommitRequest.Types.Mode, IEnumerable<Mutation>, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, mutations);
// End snippet
}
/// <summary>Snippet for Rollback</summary>
public void RollbackRequestObject()
{
// Snippet: Rollback(RollbackRequest, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
Transaction = ByteString.Empty,
ProjectId = "",
};
// Make the request
RollbackResponse response = datastoreClient.Rollback(request);
// End snippet
}
/// <summary>Snippet for RollbackAsync</summary>
public async Task RollbackRequestObjectAsync()
{
// Snippet: RollbackAsync(RollbackRequest, CallSettings)
// Additional: RollbackAsync(RollbackRequest, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
Transaction = ByteString.Empty,
ProjectId = "",
};
// Make the request
RollbackResponse response = await datastoreClient.RollbackAsync(request);
// End snippet
}
/// <summary>Snippet for Rollback</summary>
public void Rollback()
{
// Snippet: Rollback(string, ByteString, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
string projectId = "";
ByteString transaction = ByteString.Empty;
// Make the request
RollbackResponse response = datastoreClient.Rollback(projectId, transaction);
// End snippet
}
/// <summary>Snippet for RollbackAsync</summary>
public async Task RollbackAsync()
{
// Snippet: RollbackAsync(string, ByteString, CallSettings)
// Additional: RollbackAsync(string, ByteString, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
ByteString transaction = ByteString.Empty;
// Make the request
RollbackResponse response = await datastoreClient.RollbackAsync(projectId, transaction);
// End snippet
}
/// <summary>Snippet for AllocateIds</summary>
public void AllocateIdsRequestObject()
{
// Snippet: AllocateIds(AllocateIdsRequest, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "",
};
// Make the request
AllocateIdsResponse response = datastoreClient.AllocateIds(request);
// End snippet
}
/// <summary>Snippet for AllocateIdsAsync</summary>
public async Task AllocateIdsRequestObjectAsync()
{
// Snippet: AllocateIdsAsync(AllocateIdsRequest, CallSettings)
// Additional: AllocateIdsAsync(AllocateIdsRequest, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
AllocateIdsRequest request = new AllocateIdsRequest
{
Keys = { new Key(), },
ProjectId = "",
};
// Make the request
AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(request);
// End snippet
}
/// <summary>Snippet for AllocateIds</summary>
public void AllocateIds()
{
// Snippet: AllocateIds(string, IEnumerable<Key>, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
string projectId = "";
IEnumerable<Key> keys = new Key[] { new Key(), };
// Make the request
AllocateIdsResponse response = datastoreClient.AllocateIds(projectId, keys);
// End snippet
}
/// <summary>Snippet for AllocateIdsAsync</summary>
public async Task AllocateIdsAsync()
{
// Snippet: AllocateIdsAsync(string, IEnumerable<Key>, CallSettings)
// Additional: AllocateIdsAsync(string, IEnumerable<Key>, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
IEnumerable<Key> keys = new Key[] { new Key(), };
// Make the request
AllocateIdsResponse response = await datastoreClient.AllocateIdsAsync(projectId, keys);
// End snippet
}
/// <summary>Snippet for ReserveIds</summary>
public void ReserveIdsRequestObject()
{
// Snippet: ReserveIds(ReserveIdsRequest, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "",
DatabaseId = "",
};
// Make the request
ReserveIdsResponse response = datastoreClient.ReserveIds(request);
// End snippet
}
/// <summary>Snippet for ReserveIdsAsync</summary>
public async Task ReserveIdsRequestObjectAsync()
{
// Snippet: ReserveIdsAsync(ReserveIdsRequest, CallSettings)
// Additional: ReserveIdsAsync(ReserveIdsRequest, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
ReserveIdsRequest request = new ReserveIdsRequest
{
Keys = { new Key(), },
ProjectId = "",
DatabaseId = "",
};
// Make the request
ReserveIdsResponse response = await datastoreClient.ReserveIdsAsync(request);
// End snippet
}
/// <summary>Snippet for ReserveIds</summary>
public void ReserveIds()
{
// Snippet: ReserveIds(string, IEnumerable<Key>, CallSettings)
// Create client
DatastoreClient datastoreClient = DatastoreClient.Create();
// Initialize request argument(s)
string projectId = "";
IEnumerable<Key> keys = new Key[] { new Key(), };
// Make the request
ReserveIdsResponse response = datastoreClient.ReserveIds(projectId, keys);
// End snippet
}
/// <summary>Snippet for ReserveIdsAsync</summary>
public async Task ReserveIdsAsync()
{
// Snippet: ReserveIdsAsync(string, IEnumerable<Key>, CallSettings)
// Additional: ReserveIdsAsync(string, IEnumerable<Key>, CancellationToken)
// Create client
DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
// Initialize request argument(s)
string projectId = "";
IEnumerable<Key> keys = new Key[] { new Key(), };
// Make the request
ReserveIdsResponse response = await datastoreClient.ReserveIdsAsync(projectId, keys);
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using MonoBrickFirmware.Extensions;
namespace MonoBrickFirmware.Sensors
{
public class SensorFactory
{
public static ISensor[] GetSensorArray()
{
SensorPort[] ports = new SensorPort[]{ SensorPort.In1, SensorPort.In2, SensorPort.In3, SensorPort.In4 };
ISensor[] sensors = new ISensor[ports.Length];
for(int i = 0; i < ports.Length; i++)
{
sensors[i] = GetSensor(ports[i]);
}
return sensors;
}
public static ISensor GetSensor (SensorPort port)
{
ISensor sensor = null;
SensorType sensorType = SensorManager.Instance.GetSensorType (port);
ConnectionType connectionType = SensorManager.Instance.GetConnectionType (port);
switch (sensorType) {
case SensorType.Color:
sensor = new EV3ColorSensor (port);
break;
case SensorType.Gyro:
sensor = new EV3GyroSensor (port);
break;
case SensorType.IR:
sensor = new EV3IRSensor (port);
break;
case SensorType.NXTColor:
sensor = new NXTColorSensor (port);
break;
case SensorType.NXTLight:
sensor = new NXTLightSensor (port);
break;
case SensorType.NXTSound:
sensor = new NXTSoundSensor (port);
break;
case SensorType.NXTTouch:
sensor = new NXTTouchSensor (port);
break;
case SensorType.NXTUltraSonic:
sensor = new NXTUltraSonicSensor (port);
break;
case SensorType.Touch:
sensor = new EV3TouchSensor (port);
break;
case SensorType.UltraSonic:
sensor = new EV3UltrasonicSensor (port);
break;
case SensorType.NXTI2c:
var helper = new I2CHelper (port);
sensor = helper.GetSensor ();
break;
case SensorType.Unknown:
if (connectionType == ConnectionType.UART) {
var uartHelper = new UARTHelper (port);
sensor = uartHelper.GetSensor ();
}
if (connectionType == ConnectionType.InputResistor) {
sensor = new EV3TouchSensor (port);
}
break;
case SensorType.I2CUnknown:
break;
case SensorType.NXTTemperature:
break;
case SensorType.LMotor:
break;
case SensorType.MMotor:
break;
case SensorType.NXTTest:
break;
case SensorType.Terminal:
break;
case SensorType.Test:
break;
case SensorType.Error:
break;
case SensorType.None:
sensor = new NoSensor (port);
break;
}
if (sensor == null)
{
sensor = new UnknownSensor(port);
}
return sensor;
}
}
internal class UARTHelper : UartSensor{
private const UInt32 SensorNameLength = 12;
private static byte[] IRName = {0x49, 0x52, 0x2d, 0x50, 0x52, 0x4f, 0x58, 0x00, 0x00, 0x00, 0x00, 0x00};
private static byte[] ColorName = {0x43, 0x4f, 0x4c, 0x2d, 0x52, 0x45, 0x46, 0x4c, 0x45, 0x43, 0x54, 0x00};
private static byte[] GyroName = {0x47, 0x59, 0x52, 0x4f, 0x2d, 0x41, 0x4e, 0x47, 0x00, 0x00, 0x00, 0x00};
private static byte[] UltrasonicName = {0x55, 0x53, 0x2d, 0x44, 0x49, 0x53, 0x54, 0x2d, 0x43, 0x4d, 0x00, 0x00};
private Dictionary<byte[], ISensor> sensorDictionary = null;
public UARTHelper (SensorPort port) : base (port)
{
base.Initialise(base.uartMode);
base.SetMode(UARTMode.Mode0);
sensorDictionary = new Dictionary<byte[], ISensor>();
sensorDictionary.Add(IRName, new EV3IRSensor(port));
sensorDictionary.Add(GyroName, new EV3GyroSensor(port));
sensorDictionary.Add(ColorName, new EV3ColorSensor(port));
sensorDictionary.Add(UltrasonicName, new EV3UltrasonicSensor(port));
System.Threading.Thread.Sleep(100);
}
private bool ByteArrayCompare(byte[] a1, byte[] a2)
{
for(int i=0; i<a1.Length; i++)
if(a1[i]!=a2[i])
return false;
return true;
}
public ISensor GetSensor ()
{
byte[] data = new byte[SensorNameLength];
data[0] = 0;
while(data[0] == 0){
data = this.GetSensorInfo ();
}
byte[] name = new byte[SensorNameLength];
Array.Copy(data, name, SensorNameLength);
foreach (KeyValuePair<byte[], ISensor> pair in sensorDictionary) {
if (ByteArrayCompare (pair.Key, name)) {
return pair.Value;
}
}
return null;
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>
/// The value as a string
/// </returns>
public override string ReadAsString ()
{
return "";
}
/// <summary>
/// Gets the name of the sensor.
/// </summary>
/// <returns>The sensor name.</returns>
public override string GetSensorName ()
{
return "";
}
/// <summary>
/// Selects the next mode.
/// </summary>
public override void SelectNextMode ()
{
return;
}
/// <summary>
/// Selects the previous mode.
/// </summary>
public override void SelectPreviousMode ()
{
return;
}
/// <summary>
/// Numbers the of modes.
/// </summary>
/// <returns>The number of modes</returns>
public override int NumberOfModes()
{
return 0;
}
/// <summary>
/// .m.-,
/// </summary>
/// <returns>The mode.</returns>
public override string SelectedMode ()
{
return "";
}
}
internal class I2CHelper : I2CSensor
{
private Dictionary<Tuple<string,string>, ISensor> sensorDictionary = null;
public I2CHelper (SensorPort port) : base (port, 0x02, I2CMode.LowSpeed9V)
{
base.Initialise();
sensorDictionary = new Dictionary<Tuple<string,string>, ISensor>();
sensorDictionary.Add(new Tuple<string, string>("LEGO", "Sonar"), new NXTUltraSonicSensor(port));
sensorDictionary.Add(new Tuple<string, string>("HiTechnc", "Color"), new HiTecColorSensor(port));
sensorDictionary.Add(new Tuple<string, string>("HiTechnc", "Compass"), new HiTecCompassSensor(port));
sensorDictionary.Add(new Tuple<string, string>("HITECHNC", "Accel"), new HiTecTiltSensor(port));
sensorDictionary.Add(new Tuple<string, string>("mndsnsrs", "AngSens"), new MSAngleSensor(port));
sensorDictionary.Add(new Tuple<string, string>("mndsnsrs", "DIST-S"), new MSDistanceSensor(port));
sensorDictionary.Add(new Tuple<string, string>("mndsnsrs", "DIST-M"), new MSDistanceSensor(port));
sensorDictionary.Add(new Tuple<string, string>("mndsnsrs", "DIST-L"), new MSDistanceSensor(port));
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>
/// The value as a string
/// </returns>
public override string ReadAsString ()
{
return "";
}
public ISensor GetSensor ()
{
string vendorId = GetVendorId ();
string deviceId = GetDeviceId ();
foreach (KeyValuePair<Tuple<string,string>, ISensor> pair in sensorDictionary) {
if (pair.Key.Item1 == vendorId && pair.Key.Item2 == deviceId)
{
return pair.Value;
}
}
return null;
}
/// <summary>
/// Gets the name of the sensor.
/// </summary>
/// <returns>The sensor name.</returns>
public override string GetSensorName ()
{
return "";
}
/// <summary>
/// Selects the next mode.
/// </summary>
public override void SelectNextMode ()
{
return;
}
/// <summary>
/// Selects the previous mode.
/// </summary>
public override void SelectPreviousMode ()
{
return;
}
/// <summary>
/// Numbers the of modes.
/// </summary>
/// <returns>The number of modes</returns>
public override int NumberOfModes()
{
return 0;
}
/// <summary>
/// .m.-,
/// </summary>
/// <returns>The mode.</returns>
public override string SelectedMode ()
{
return "";
}
}
internal class DummySensor : ISensor
{
private SensorPort port;
private enum DummyMode{Raw = 1, Digital = 2};
private DummyMode mode = DummyMode.Raw;
Random rnd = new Random();
public DummySensor(SensorPort port)
{
this.port = port;
System.Threading.Thread.Sleep(500);
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>
/// The value as a string
/// </returns>
public string ReadAsString ()
{
if (mode == DummyMode.Digital)
return rnd.Next(1).ToString();
return rnd.Next(1024) + " A/D value";
}
/// <summary>
/// Gets the name of the sensor.
/// </summary>
/// <returns>The sensor name.</returns>
public string GetSensorName ()
{
return "Dummy Sensor";
}
/// <summary>
/// Selects the next mode.
/// </summary>
public void SelectNextMode ()
{
mode = mode.Next();
}
/// <summary>
/// Selects the previous mode.
/// </summary>
public void SelectPreviousMode ()
{
mode = mode.Previous();
}
/// <summary>
/// Numbers the of modes.
/// </summary>
/// <returns>The number of modes</returns>
public int NumberOfModes()
{
return Enum.GetNames(typeof(DummyMode)).Length;
}
/// <summary>
/// .m.-,
/// </summary>
/// <returns>The mode.</returns>
public string SelectedMode ()
{
return mode.ToString();
}
public SensorPort Port{ get {return port;}}
}
}
| |
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="Networking.IPsecManualSecurityAssociationBinding", Namespace="urn:iControl")]
public partial class NetworkingIPsecManualSecurityAssociation : iControlInterface {
public NetworkingIPsecManualSecurityAssociation() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void create(
string [] associations,
string [] addresses
) {
this.Invoke("create", new object [] {
associations,
addresses});
}
public System.IAsyncResult Begincreate(string [] associations,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
associations,
addresses}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_manual_security_associations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void delete_all_manual_security_associations(
) {
this.Invoke("delete_all_manual_security_associations", new object [0]);
}
public System.IAsyncResult Begindelete_all_manual_security_associations(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_manual_security_associations", new object[0], callback, asyncState);
}
public void Enddelete_all_manual_security_associations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_manual_security_association
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void delete_manual_security_association(
string [] associations
) {
this.Invoke("delete_manual_security_association", new object [] {
associations});
}
public System.IAsyncResult Begindelete_manual_security_association(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_manual_security_association", new object[] {
associations}, callback, asyncState);
}
public void Enddelete_manual_security_association(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_auth_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecSaManAlgorithm [] get_auth_algorithm(
string [] associations
) {
object [] results = this.Invoke("get_auth_algorithm", new object [] {
associations});
return ((NetworkingIPsecSaManAlgorithm [])(results[0]));
}
public System.IAsyncResult Beginget_auth_algorithm(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auth_algorithm", new object[] {
associations}, callback, asyncState);
}
public NetworkingIPsecSaManAlgorithm [] Endget_auth_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecSaManAlgorithm [])(results[0]));
}
//-----------------------------------------------------------------------
// get_auth_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_auth_key(
string [] associations
) {
object [] results = this.Invoke("get_auth_key", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_auth_key(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auth_key", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_auth_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_auth_key_encrypted
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_auth_key_encrypted(
string [] associations
) {
object [] results = this.Invoke("get_auth_key_encrypted", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_auth_key_encrypted(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_auth_key_encrypted", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_auth_key_encrypted(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] associations
) {
object [] results = this.Invoke("get_description", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_destination_address(
string [] associations
) {
object [] results = this.Invoke("get_destination_address", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_destination_address(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination_address", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_destination_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_encrypt_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecManSaEncrAlgorithm [] get_encrypt_algorithm(
string [] associations
) {
object [] results = this.Invoke("get_encrypt_algorithm", new object [] {
associations});
return ((NetworkingIPsecManSaEncrAlgorithm [])(results[0]));
}
public System.IAsyncResult Beginget_encrypt_algorithm(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_encrypt_algorithm", new object[] {
associations}, callback, asyncState);
}
public NetworkingIPsecManSaEncrAlgorithm [] Endget_encrypt_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecManSaEncrAlgorithm [])(results[0]));
}
//-----------------------------------------------------------------------
// get_encrypt_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_encrypt_key(
string [] associations
) {
object [] results = this.Invoke("get_encrypt_key", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_encrypt_key(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_encrypt_key", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_encrypt_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_encrypt_key_encrypted
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_encrypt_key_encrypted(
string [] associations
) {
object [] results = this.Invoke("get_encrypt_key_encrypted", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_encrypt_key_encrypted(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_encrypt_key_encrypted", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_encrypt_key_encrypted(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[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_policy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_policy(
string [] associations
) {
object [] results = this.Invoke("get_policy", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_policy(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_policy", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_policy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_protocol
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public NetworkingIPsecProtocol [] get_protocol(
string [] associations
) {
object [] results = this.Invoke("get_protocol", new object [] {
associations});
return ((NetworkingIPsecProtocol [])(results[0]));
}
public System.IAsyncResult Beginget_protocol(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_protocol", new object[] {
associations}, callback, asyncState);
}
public NetworkingIPsecProtocol [] Endget_protocol(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((NetworkingIPsecProtocol [])(results[0]));
}
//-----------------------------------------------------------------------
// get_source_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_source_address(
string [] associations
) {
object [] results = this.Invoke("get_source_address", new object [] {
associations});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_source_address(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_source_address", new object[] {
associations}, callback, asyncState);
}
public string [] Endget_source_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_spi
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_spi(
string [] associations
) {
object [] results = this.Invoke("get_spi", new object [] {
associations});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_spi(string [] associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_spi", new object[] {
associations}, callback, asyncState);
}
public long [] Endget_spi(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
[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]));
}
//-----------------------------------------------------------------------
// set_auth_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_auth_algorithm(
string [] associations,
NetworkingIPsecSaManAlgorithm [] algorithms
) {
this.Invoke("set_auth_algorithm", new object [] {
associations,
algorithms});
}
public System.IAsyncResult Beginset_auth_algorithm(string [] associations,NetworkingIPsecSaManAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auth_algorithm", new object[] {
associations,
algorithms}, callback, asyncState);
}
public void Endset_auth_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auth_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_auth_key(
string [] associations,
string [] keys
) {
this.Invoke("set_auth_key", new object [] {
associations,
keys});
}
public System.IAsyncResult Beginset_auth_key(string [] associations,string [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auth_key", new object[] {
associations,
keys}, callback, asyncState);
}
public void Endset_auth_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_auth_key_encrypted
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_auth_key_encrypted(
string [] associations,
string [] keys
) {
this.Invoke("set_auth_key_encrypted", new object [] {
associations,
keys});
}
public System.IAsyncResult Beginset_auth_key_encrypted(string [] associations,string [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_auth_key_encrypted", new object[] {
associations,
keys}, callback, asyncState);
}
public void Endset_auth_key_encrypted(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_description(
string [] associations,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
associations,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] associations,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
associations,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_destination_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_destination_address(
string [] associations,
string [] addresses
) {
this.Invoke("set_destination_address", new object [] {
associations,
addresses});
}
public System.IAsyncResult Beginset_destination_address(string [] associations,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_destination_address", new object[] {
associations,
addresses}, callback, asyncState);
}
public void Endset_destination_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_encrypt_algorithm
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_encrypt_algorithm(
string [] associations,
NetworkingIPsecManSaEncrAlgorithm [] algorithms
) {
this.Invoke("set_encrypt_algorithm", new object [] {
associations,
algorithms});
}
public System.IAsyncResult Beginset_encrypt_algorithm(string [] associations,NetworkingIPsecManSaEncrAlgorithm [] algorithms, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_encrypt_algorithm", new object[] {
associations,
algorithms}, callback, asyncState);
}
public void Endset_encrypt_algorithm(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_encrypt_key
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_encrypt_key(
string [] associations,
string [] keys
) {
this.Invoke("set_encrypt_key", new object [] {
associations,
keys});
}
public System.IAsyncResult Beginset_encrypt_key(string [] associations,string [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_encrypt_key", new object[] {
associations,
keys}, callback, asyncState);
}
public void Endset_encrypt_key(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_encrypt_key_encrypted
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_encrypt_key_encrypted(
string [] associations,
string [] keys
) {
this.Invoke("set_encrypt_key_encrypted", new object [] {
associations,
keys});
}
public System.IAsyncResult Beginset_encrypt_key_encrypted(string [] associations,string [] keys, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_encrypt_key_encrypted", new object[] {
associations,
keys}, callback, asyncState);
}
public void Endset_encrypt_key_encrypted(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_policy
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_policy(
string [] associations,
string [] policies
) {
this.Invoke("set_policy", new object [] {
associations,
policies});
}
public System.IAsyncResult Beginset_policy(string [] associations,string [] policies, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_policy", new object[] {
associations,
policies}, callback, asyncState);
}
public void Endset_policy(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_protocol
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_protocol(
string [] associations,
NetworkingIPsecProtocol [] protocols
) {
this.Invoke("set_protocol", new object [] {
associations,
protocols});
}
public System.IAsyncResult Beginset_protocol(string [] associations,NetworkingIPsecProtocol [] protocols, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_protocol", new object[] {
associations,
protocols}, callback, asyncState);
}
public void Endset_protocol(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_source_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_source_address(
string [] associations,
string [] addresses
) {
this.Invoke("set_source_address", new object [] {
associations,
addresses});
}
public System.IAsyncResult Beginset_source_address(string [] associations,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_source_address", new object[] {
associations,
addresses}, callback, asyncState);
}
public void Endset_source_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_spi
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/IPsecManualSecurityAssociation",
RequestNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation", ResponseNamespace="urn:iControl:Networking/IPsecManualSecurityAssociation")]
public void set_spi(
string [] associations,
long [] spis
) {
this.Invoke("set_spi", new object [] {
associations,
spis});
}
public System.IAsyncResult Beginset_spi(string [] associations,long [] spis, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_spi", new object[] {
associations,
spis}, callback, asyncState);
}
public void Endset_spi(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
namespace IdentityBase.IntegrationTests
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using AngleSharp.Dom.Html;
using FluentAssertions;
using ServiceBase.Tests;
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> ConstentPostFormAsync(
this HttpClient client,
bool rememberMe,
HttpResponseMessage formGetResponse)
{
formGetResponse.StatusCode.Should().Be(HttpStatusCode.Found);
HttpResponseMessage authorizeResponse = await client
.FollowRedirect(formGetResponse);
authorizeResponse.StatusCode.Should().Be(HttpStatusCode.Found);
HttpResponseMessage constentGetResponse = await client
.FollowRedirect(authorizeResponse);
// just submit form as is
IHtmlDocument doc = await constentGetResponse.Content
.ReadAsHtmlDocumentAsync();
Dictionary<string, string> form = doc.GetFormInputs();
//form["RememberLogin"] = rememberMe ? "true" : "false";
HttpResponseMessage constentPostResponse = await client
.PostAsync(doc.GetFormAction(), form, constentGetResponse);
constentPostResponse.EnsureSuccessStatusCode();
return constentPostResponse;
}
public static async Task<HttpResponseMessage> LoginGetAndPostFormAsync(
this HttpClient client,
string emailAddress,
string password,
bool rememberMe = false,
HttpResponseMessage prevResponse = null)
{
HttpResponseMessage getResponse = await client.GetAsync(
$"/login?returnUrl={Constants.ReturnUrl}",
prevResponse
);
getResponse.EnsureSuccessStatusCode();
string html = await getResponse.Content.ReadAsStringAsync();
// 5. Fill out the login form and submit
IHtmlDocument doc = await getResponse.Content
.ReadAsHtmlDocumentAsync();
Dictionary<string, string> form = doc.GetFormInputs();
form["Email"] = emailAddress;
form["Password"] = password;
form["RememberLogin"] = rememberMe ? "true" : "false";
HttpResponseMessage postResponse = await client
.PostAsync(doc.GetFormAction(), form, getResponse);
return postResponse;
}
public static async Task<HttpResponseMessage> RecoveryConfirmGetAndPostFormAsync(
this HttpClient client,
string confirmUrl,
string newPassword,
HttpResponseMessage prevResponse = null)
{
HttpResponseMessage getResponse = client.GetAsync(confirmUrl).Result;
getResponse.EnsureSuccessStatusCode();
IHtmlDocument doc = await getResponse.Content
.ReadAsHtmlDocumentAsync();
Dictionary<string, string> form = doc.GetFormInputs();
form["Password"] = newPassword;
form["PasswordConfirm"] = newPassword;
HttpResponseMessage postResponse = await client
.PostAsync(doc.GetFormAction(), form, getResponse);
postResponse.StatusCode.Should().Be(HttpStatusCode.Found);
postResponse.Headers.Location.ToString().Should()
.StartWith("/connect/authorize/callback");
return postResponse;
}
public static async Task<HttpResponseMessage> RecoveryGetFormAsync(
this HttpClient client,
HttpResponseMessage prevResponse = null)
{
HttpResponseMessage response = await client.GetAsync(
$"/recover?returnUrl={Constants.ReturnUrl}",
prevResponse
);
response.EnsureSuccessStatusCode();
return response;
}
public static async Task<HttpResponseMessage> RecoveryPostFormAsync(
this HttpClient client,
string emailAddress,
HttpResponseMessage formGetResponse)
{
IHtmlDocument doc = await formGetResponse.Content
.ReadAsHtmlDocumentAsync();
Dictionary<string, string> form = doc.GetFormInputs();
form["Email"] = emailAddress;
string uri = doc.GetFormAction();
HttpResponseMessage response = await client
.PostAsync(uri, form, formGetResponse);
response.EnsureSuccessStatusCode();
return response;
}
public static async Task<HttpResponseMessage> RecoveryGetAndPostFormAsync(
this HttpClient client,
string emailAddress,
HttpResponseMessage prevResponse = null)
{
HttpResponseMessage response = await client
.RecoveryGetFormAsync(prevResponse);
return await client.RecoveryPostFormAsync(emailAddress, response);
}
public static async Task<HttpResponseMessage> RecoveryCancelGetValidAsync(
this HttpClient client,
string cancelUrl)
{
HttpResponseMessage response = client
.GetAsync(cancelUrl).Result;
response.EnsureSuccessStatusCode();
return response;
}
public static async Task<HttpResponseMessage> RecoveryCancelGetInvalidAsync(
this HttpClient client,
string cancelUrl)
{
HttpResponseMessage response = await client
.RecoveryCancelGetValidAsync(cancelUrl);
response.EnsureSuccessStatusCode();
return response;
}
public static async Task<HttpResponseMessage> RecoveryConfirmGetValidAsync(
this HttpClient client,
string confirmUrl)
{
HttpResponseMessage response = client
.GetAsync(confirmUrl).Result;
response.EnsureSuccessStatusCode();
return response;
}
public static async Task<HttpResponseMessage> RecoveryConfirmGetInvalidAsync(
this HttpClient client,
string confirmUrl)
{
HttpResponseMessage response = await client
.RecoveryConfirmGetValidAsync(confirmUrl);
response.EnsureSuccessStatusCode();
return response;
}
public static async Task<HttpResponseMessage> RegisterConfirmGetAndPostFormAsync(
this HttpClient client,
string confirmUrl,
string password = null,
HttpResponseMessage prevResponse = null)
{
HttpResponseMessage getResponse = client.GetAsync(confirmUrl).Result;
getResponse.EnsureSuccessStatusCode();
IHtmlDocument doc = await getResponse.Content
.ReadAsHtmlDocumentAsync();
Dictionary<string, string> form = doc.GetFormInputs();
if (!String.IsNullOrWhiteSpace(password))
{
form["Password"] = password;
form["PasswordConfirm"] = password;
}
HttpResponseMessage postResponse = await client
.PostAsync(doc.GetFormAction(), form, getResponse);
return postResponse;
}
public static void ShouldBeRedirectedToAuthorizeEndpoint(
this HttpResponseMessage response)
{
response.StatusCode.Should().Be(HttpStatusCode.Found);
response.Headers.Location.ToString().Should()
.StartWith("/connect/authorize/callback");
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace storage
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// The Storage Management Client.
/// </summary>
public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IStorageAccountsOperations.
/// </summary>
public virtual IStorageAccountsOperations StorageAccounts { get; private set; }
/// <summary>
/// Gets the IUsageOperations.
/// </summary>
public virtual IUsageOperations Usage { get; private set; }
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected StorageManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected StorageManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
StorageAccounts = new StorageAccountsOperations(this);
Usage = new UsageOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2015-06-15";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Copyright 2012 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.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using JetBrains.Annotations;
using NodaTime.Annotations;
using NodaTime.Text;
using NodaTime.Utility;
namespace NodaTime
{
/// <summary>
/// A mutable builder class for <see cref="Period"/> values. Each property can
/// be set independently, and then a Period can be created from the result
/// using the <see cref="Build"/> method.
/// </summary>
/// <threadsafety>
/// This type is not thread-safe without extra synchronization, but has no
/// thread affinity.
/// </threadsafety>
[Mutable]
public sealed class PeriodBuilder : IXmlSerializable
{
#region Properties
/// <summary>
/// Gets or sets the number of years within the period.
/// </summary>
/// <value>The number of years within the period.</value>
public int Years { get; set; }
/// <summary>
/// Gets or sets the number of months within the period.
/// </summary>
/// <value>The number of months within the period.</value>
public int Months { get; set; }
/// <summary>
/// Gets or sets the number of weeks within the period.
/// </summary>
/// <value>The number of weeks within the period.</value>
public int Weeks { get; set; }
/// <summary>
/// Gets or sets the number of days within the period.
/// </summary>
/// <value>The number of days within the period.</value>
public int Days { get; set; }
/// <summary>
/// Gets or sets the number of hours within the period.
/// </summary>
/// <value>The number of hours within the period.</value>
public long Hours { get; set; }
/// <summary>
/// Gets or sets the number of minutes within the period.
/// </summary>
/// <value>The number of minutes within the period.</value>
public long Minutes { get; set; }
/// <summary>
/// Gets or sets the number of seconds within the period.
/// </summary>
/// <value>The number of seconds within the period.</value>
public long Seconds { get; set; }
/// <summary>
/// Gets or sets the number of milliseconds within the period.
/// </summary>
/// <value>The number of milliseconds within the period.</value>
public long Milliseconds { get; set; }
/// <summary>
/// Gets or sets the number of ticks within the period.
/// </summary>
/// <value>The number of ticks within the period.</value>
public long Ticks { get; set; }
/// <summary>
/// Gets or sets the number of nanoseconds within the period.
/// </summary>
/// <value>The number of nanoseconds within the period.</value>
public long Nanoseconds { get; set; }
#endregion
/// <summary>
/// Creates a new period builder with an initially zero period.
/// </summary>
public PeriodBuilder()
{
}
/// <summary>
/// Creates a new period builder with the values from an existing
/// period. Calling this constructor instead of <see cref="Period.ToBuilder"/>
/// allows object initializers to be used.
/// </summary>
/// <param name="period">An existing period to copy values from.</param>
public PeriodBuilder([NotNull] Period period)
{
Preconditions.CheckNotNull(period, nameof(period));
Years = period.Years;
Months = period.Months;
Weeks = period.Weeks;
Days = period.Days;
Hours = period.Hours;
Minutes = period.Minutes;
Seconds = period.Seconds;
Milliseconds = period.Milliseconds;
Ticks = period.Ticks;
Nanoseconds = period.Nanoseconds;
}
/// <summary>
/// Gets or sets the value of a single unit.
/// </summary>
/// <remarks>
/// <para>
/// The type of this indexer is <see cref="System.Int64"/> for uniformity, but any date unit (year, month, week, day) will only ever have a value
/// in the range of <see cref="System.Int32"/>.
/// </para>
/// <para>
/// For the <see cref="PeriodUnits.Nanoseconds"/> unit, the value is converted to <c>Int64</c> when reading from the indexer, causing it to
/// fail if the value is out of range (around 250 years). To access the values of very large numbers of nanoseconds, use the <see cref="Nanoseconds"/>
/// property directly.
/// </para>
/// </remarks>
/// <param name="unit">A single value within the <see cref="PeriodUnits"/> enumeration.</param>
/// <value>The value of the given unit within this period builder, or zero if the unit is unset.</value>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="unit"/> is not a single unit, or a value is provided for a date unit which is outside the range of <see cref="System.Int32"/>.</exception>
public long this[PeriodUnits unit]
{
get
{
switch (unit)
{
case PeriodUnits.Years: return Years;
case PeriodUnits.Months: return Months;
case PeriodUnits.Weeks: return Weeks;
case PeriodUnits.Days: return Days;
case PeriodUnits.Hours: return Hours;
case PeriodUnits.Minutes: return Minutes;
case PeriodUnits.Seconds: return Seconds;
case PeriodUnits.Milliseconds: return Milliseconds;
case PeriodUnits.Ticks: return Ticks;
case PeriodUnits.Nanoseconds: return Nanoseconds;
default: throw new ArgumentOutOfRangeException(nameof(unit), "Indexer for PeriodBuilder only takes a single unit");
}
}
set
{
if ((unit & PeriodUnits.AllDateUnits) != 0)
{
Preconditions.CheckArgumentRange(nameof(value), value, int.MinValue, int.MaxValue);
}
switch (unit)
{
case PeriodUnits.Years: Years = (int) value; return;
case PeriodUnits.Months: Months = (int) value; return;
case PeriodUnits.Weeks: Weeks = (int) value; return;
case PeriodUnits.Days: Days = (int) value; return;
case PeriodUnits.Hours: Hours = value; return;
case PeriodUnits.Minutes: Minutes = value; return;
case PeriodUnits.Seconds: Seconds = value; return;
case PeriodUnits.Milliseconds: Milliseconds = value; return;
case PeriodUnits.Ticks: Ticks = value; return;
case PeriodUnits.Nanoseconds: Nanoseconds = value; return;
default: throw new ArgumentOutOfRangeException(nameof(unit), "Indexer for PeriodBuilder only takes a single unit");
}
}
}
/// <summary>
/// Builds a period from the properties in this builder.
/// </summary>
/// <returns>A period containing the values from this builder.</returns>
public Period Build() =>
new Period(Years, Months, Weeks, Days, Hours, Minutes, Seconds, Milliseconds, Ticks, Nanoseconds);
/// <inheritdoc />
XmlSchema IXmlSerializable.GetSchema() => null;
/// <inheritdoc />
void IXmlSerializable.ReadXml(XmlReader reader)
{
string text = reader.ReadElementContentAsString();
Period period = PeriodPattern.RoundtripPattern.Parse(text).Value;
Years = period.Years;
Months = period.Months;
Weeks = period.Weeks;
Days = period.Days;
Hours = period.Hours;
Minutes = period.Minutes;
Seconds = period.Seconds;
Milliseconds = period.Milliseconds;
Ticks = period.Ticks;
Nanoseconds = period.Nanoseconds;
}
/// <inheritdoc />
void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteString(PeriodPattern.RoundtripPattern.Format(Build()));
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Deprecated/GUI/tk2dButton")]
public class tk2dButton : MonoBehaviour
{
/// <summary>
/// The camera this button is meant to be viewed from.
/// Set this explicitly for best performance.\n
/// The system will automatically traverse up the hierarchy to find a camera if this is not set.\n
/// If nothing is found, it will fall back to the active <see cref="tk2dCamera"/>.\n
/// Failing that, it will use Camera.main.
/// </summary>
public Camera viewCamera;
// Button Up = normal state
// Button Down = held down
// Button Pressed = after it is pressed and activated
/// <summary>
/// The button down sprite. This is resolved by name from the sprite collection of the sprite component.
/// </summary>
public string buttonDownSprite = "button_down";
/// <summary>
/// The button up sprite. This is resolved by name from the sprite collection of the sprite component.
/// </summary>
public string buttonUpSprite = "button_up";
/// <summary>
/// The button pressed sprite. This is resolved by name from the sprite collection of the sprite component.
/// </summary>
public string buttonPressedSprite = "button_up";
int buttonDownSpriteId = -1, buttonUpSpriteId = -1, buttonPressedSpriteId = -1;
/// <summary>
/// Audio clip to play when the button transitions from up to down state. Requires an AudioSource component to be attached to work.
/// </summary>
public AudioClip buttonDownSound = null;
/// <summary>
/// Audio clip to play when the button transitions from down to up state. Requires an AudioSource component to be attached to work.
/// </summary>
public AudioClip buttonUpSound = null;
/// <summary>
/// Audio clip to play when the button is pressed. Requires an AudioSource component to be attached to work.
/// </summary>
public AudioClip buttonPressedSound = null;
// Delegates
/// <summary>
/// Button event handler delegate.
/// </summary>
public delegate void ButtonHandlerDelegate(tk2dButton source);
// Messaging
/// <summary>
/// Target object to send the message to. The event methods below are significantly more efficient.
/// </summary>
public GameObject targetObject = null;
/// <summary>
/// The message to send to the object. This should be the name of the method which needs to be called.
/// </summary>
public string messageName = "";
/// <summary>
/// Occurs when button is pressed (tapped, and finger lifted while inside the button)
/// </summary>
public event ButtonHandlerDelegate ButtonPressedEvent;
/// <summary>
/// Occurs every frame for as long as the button is held down.
/// </summary>
public event ButtonHandlerDelegate ButtonAutoFireEvent;
/// <summary>
/// Occurs when button transition from up to down state
/// </summary>
public event ButtonHandlerDelegate ButtonDownEvent;
/// <summary>
/// Occurs when button transitions from down to up state
/// </summary>
public event ButtonHandlerDelegate ButtonUpEvent;
tk2dBaseSprite sprite;
bool buttonDown = false;
/// <summary>
/// How much to scale the sprite when the button is in the down state
/// </summary>
public float targetScale = 1.1f;
/// <summary>
/// The length of time the scale operation takes
/// </summary>
public float scaleTime = 0.05f;
/// <summary>
/// How long to wait before allowing the button to be pressed again, in seconds.
/// </summary>
public float pressedWaitTime = 0.3f;
void OnEnable()
{
buttonDown = false;
}
// Use this for initialization
void Start ()
{
if (viewCamera == null)
{
// Find a camera parent
Transform node = transform;
while (node && node.camera == null)
{
node = node.parent;
}
if (node && node.camera != null)
{
viewCamera = node.camera;
}
// See if a tk2dCamera exists
if (viewCamera == null && tk2dCamera.Instance)
{
viewCamera = tk2dCamera.Instance.camera;
}
// ...otherwise, use the main camera
if (viewCamera == null)
{
viewCamera = Camera.main;
}
}
sprite = GetComponent<tk2dBaseSprite>();
// Further tests for sprite not being null aren't necessary, as the IDs will default to -1 in that case. Testing them will be sufficient
if (sprite)
{
// Change this to use animated sprites if necessary
// Same concept here, lookup Ids and call Play(xxx) instead of .spriteId = xxx
UpdateSpriteIds();
}
if (collider == null)
{
BoxCollider newCollider = gameObject.AddComponent<BoxCollider>();
Vector3 colliderSize = newCollider.size;
colliderSize.z = 0.2f;
newCollider.size = colliderSize;
}
if ((buttonDownSound != null || buttonPressedSound != null || buttonUpSound != null) &&
audio == null)
{
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
}
}
/// <summary>
/// Call this when the sprite names have changed
/// </summary>
public void UpdateSpriteIds()
{
buttonDownSpriteId = (buttonDownSprite.Length > 0)?sprite.GetSpriteIdByName(buttonDownSprite):-1;
buttonUpSpriteId = (buttonUpSprite.Length > 0)?sprite.GetSpriteIdByName(buttonUpSprite):-1;
buttonPressedSpriteId = (buttonPressedSprite.Length > 0)?sprite.GetSpriteIdByName(buttonPressedSprite):-1;
}
// Modify this to suit your audio solution
// In our case, we have a global audio manager to play one shot sounds and pool them
void PlaySound(AudioClip source)
{
if (audio && source)
{
audio.PlayOneShot(source);
}
}
IEnumerator coScale(Vector3 defaultScale, float startScale, float endScale)
{
float t0 = Time.realtimeSinceStartup;
Vector3 scale = defaultScale;
float s = 0.0f;
while (s < scaleTime)
{
float t = Mathf.Clamp01(s / scaleTime);
float scl = Mathf.Lerp(startScale, endScale, t);
scale = defaultScale * scl;
transform.localScale = scale;
yield return 0;
s = (Time.realtimeSinceStartup - t0);
}
transform.localScale = defaultScale * endScale;
}
IEnumerator LocalWaitForSeconds(float seconds)
{
float t0 = Time.realtimeSinceStartup;
float s = 0.0f;
while (s < seconds)
{
yield return 0;
s = (Time.realtimeSinceStartup - t0);
}
}
IEnumerator coHandleButtonPress(int fingerId)
{
buttonDown = true; // inhibit processing in Update()
bool buttonPressed = true; // the button is currently being pressed
Vector3 defaultScale = transform.localScale;
// Button has been pressed for the first time, cursor/finger is still on it
if (targetScale != 1.0f)
{
// Only do this when the scale is actually enabled, to save one frame of latency when not needed
yield return StartCoroutine( coScale(defaultScale, 1.0f, targetScale) );
}
PlaySound(buttonDownSound);
if (buttonDownSpriteId != -1)
sprite.spriteId = buttonDownSpriteId;
if (ButtonDownEvent != null)
ButtonDownEvent(this);
while (true)
{
Vector3 cursorPosition = Vector3.zero;
bool cursorActive = true;
// slightly akward arrangement to keep exact backwards compatibility
#if !UNITY_FLASH
if (fingerId != -1)
{
bool found = false;
for (int i = 0; i < Input.touchCount; ++i)
{
Touch touch = Input.GetTouch(i);
if (touch.fingerId == fingerId)
{
if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
break; // treat as not found
cursorPosition = touch.position;
found = true;
}
}
if (!found) cursorActive = false;
}
else
#endif
{
if (!Input.GetMouseButton(0))
cursorActive = false;
cursorPosition = Input.mousePosition;
}
// user is no longer pressing mouse or no longer touching button
if (!cursorActive)
break;
Ray ray = viewCamera.ScreenPointToRay(cursorPosition);
RaycastHit hitInfo;
bool colliderHit = collider.Raycast(ray, out hitInfo, Mathf.Infinity);
if (buttonPressed && !colliderHit)
{
if (targetScale != 1.0f)
{
// Finger is still on screen / button is still down, but the cursor has left the bounds of the button
yield return StartCoroutine( coScale(defaultScale, targetScale, 1.0f) );
}
PlaySound(buttonUpSound);
if (buttonUpSpriteId != -1)
sprite.spriteId = buttonUpSpriteId;
if (ButtonUpEvent != null)
ButtonUpEvent(this);
buttonPressed = false;
}
else if (!buttonPressed & colliderHit)
{
if (targetScale != 1.0f)
{
// Cursor had left the bounds before, but now has come back in
yield return StartCoroutine( coScale(defaultScale, 1.0f, targetScale) );
}
PlaySound(buttonDownSound);
if (buttonDownSpriteId != -1)
sprite.spriteId = buttonDownSpriteId;
if (ButtonDownEvent != null)
ButtonDownEvent(this);
buttonPressed = true;
}
if (buttonPressed && ButtonAutoFireEvent != null)
{
ButtonAutoFireEvent(this);
}
yield return 0;
}
if (buttonPressed)
{
if (targetScale != 1.0f)
{
// Handle case when cursor was in bounds when the button was released / finger lifted
yield return StartCoroutine( coScale(defaultScale, targetScale, 1.0f) );
}
PlaySound(buttonPressedSound);
if (buttonPressedSpriteId != -1)
sprite.spriteId = buttonPressedSpriteId;
if (targetObject)
{
targetObject.SendMessage(messageName);
}
if (ButtonUpEvent != null)
ButtonUpEvent(this);
if (ButtonPressedEvent != null)
ButtonPressedEvent(this);
// Button may have been deactivated in ButtonPressed / Up event
// Don't wait in that case
#if UNITY_3_5
if (gameObject.active)
#else
if (gameObject.activeInHierarchy)
#endif
{
yield return StartCoroutine(LocalWaitForSeconds(pressedWaitTime));
}
if (buttonUpSpriteId != -1)
sprite.spriteId = buttonUpSpriteId;
}
buttonDown = false;
}
// Update is called once per frame
void Update ()
{
if (buttonDown) // only need to process if button isn't down
return;
#if !UNITY_FLASH
bool detected = false;
if (Input.multiTouchEnabled)
{
for (int i = 0; i < Input.touchCount; ++i)
{
Touch touch = Input.GetTouch(i);
if (touch.phase != TouchPhase.Began) continue;
Ray ray = viewCamera.ScreenPointToRay(touch.position);
RaycastHit hitInfo;
if (collider.Raycast(ray, out hitInfo, 1.0e8f))
{
if (!Physics.Raycast(ray, hitInfo.distance - 0.01f))
{
StartCoroutine(coHandleButtonPress(touch.fingerId));
detected = true;
break; // only one finger on a buton, please.
}
}
}
}
if (!detected)
#endif
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (collider.Raycast(ray, out hitInfo, 1.0e8f))
{
if (!Physics.Raycast(ray, hitInfo.distance - 0.01f))
StartCoroutine(coHandleButtonPress(-1));
}
}
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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 Alphaleonis.Win32.Filesystem;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security;
namespace Alphaleonis.Win32.Network
{
partial class Host
{
#region EnumerateOpenConnections
/// <summary>Enumerates open connections from the local host.</summary>
/// <returns><see cref="OpenConnectionInfo"/> connection information from the local host.</returns>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="NetworkInformationException"/>
[SecurityCritical]
public static IEnumerable<OpenConnectionInfo> EnumerateOpenConnections()
{
return EnumerateOpenConnectionsCore(null, null, false);
}
/// <summary>Enumerates open connections from the specified host.</summary>
/// <returns><see cref="OpenConnectionInfo"/> connection information from the specified <paramref name="host"/>.</returns>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="NetworkInformationException"/>
/// <param name="host">The DNS or NetBIOS name of the remote server. <see langword="null"/> refers to the local host.</param>
/// <param name="share">The name of the Server Message Block (SMB) share.</param>
/// <param name="continueOnException">
/// <para><see langword="true"/> suppress any Exception that might be thrown a result from a failure,</para>
/// <para>such as unavailable resources.</para>
/// </param>
[SecurityCritical]
public static IEnumerable<OpenConnectionInfo> EnumerateOpenConnections(string host, string share, bool continueOnException)
{
return EnumerateOpenConnectionsCore(host, share, continueOnException);
}
#endregion // EnumerateOpenConnections
#region EnumerateShares
/// <summary>Enumerates Server Message Block (SMB) shares from the local host.</summary>
/// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
/// <remarks>This method also enumerates hidden shares.</remarks>
[SecurityCritical]
public static IEnumerable<ShareInfo> EnumerateShares()
{
return EnumerateSharesCore(null, ShareType.All, false);
}
/// <summary>Enumerates Server Message Block (SMB) shares from the local host.</summary>
/// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
/// <remarks>This method also enumerates hidden shares.</remarks>
/// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static IEnumerable<ShareInfo> EnumerateShares(bool continueOnException)
{
return EnumerateSharesCore(null, ShareType.All, continueOnException);
}
/// <summary>Enumerates Server Message Block (SMB) shares from the local host.</summary>
/// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
/// <remarks>This method also enumerates hidden shares.</remarks>
/// <param name="shareType">The type of the shared resource to retrieve.</param>
/// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static IEnumerable<ShareInfo> EnumerateShares(ShareType shareType, bool continueOnException)
{
return EnumerateSharesCore(null, shareType, continueOnException);
}
/// <summary>Enumerates Server Message Block (SMB) shares from the specified <paramref name="host"/>.</summary>
/// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
/// <remarks>This method also enumerates hidden shares.</remarks>
/// <param name="host">The DNS or NetBIOS name of the specified host.</param>
[SecurityCritical]
public static IEnumerable<ShareInfo> EnumerateShares(string host)
{
return EnumerateSharesCore(host, ShareType.All, false);
}
/// <summary>Enumerates Server Message Block (SMB) shares from the specified <paramref name="host"/>.</summary>
/// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
/// <remarks>This method also enumerates hidden shares.</remarks>
/// <param name="host">The DNS or NetBIOS name of the specified host.</param>
/// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static IEnumerable<ShareInfo> EnumerateShares(string host, bool continueOnException)
{
return EnumerateSharesCore(host, ShareType.All, continueOnException);
}
/// <summary>Enumerates Server Message Block (SMB) shares from the specified <paramref name="host"/>.</summary>
/// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
/// <remarks>This method also enumerates hidden shares.</remarks>
/// <param name="host">The DNS or NetBIOS name of the specified host.</param>
/// <param name="shareType">The type of the shared resource to retrieve.</param>
/// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static IEnumerable<ShareInfo> EnumerateShares(string host, ShareType shareType, bool continueOnException)
{
return EnumerateSharesCore(host, shareType, continueOnException);
}
#endregion // EnumerateShares
#region GetHostShareFromPath
/// <summary>Gets the host and share path name for the given <paramref name="uncPath"/>.</summary>
/// <param name="uncPath">The share in the format: \\host\share.</param>
/// <returns>The host and share path. For example, if <paramref name="uncPath"/> is: "\\SERVER001\C$\WINDOWS\System32",
/// its is returned as string[0] = "SERVER001" and string[1] = "\C$\WINDOWS\System32".
/// <para>If the conversion from local path to UNC path fails, <see langword="null"/> is returned.</para>
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")]
[SecurityCritical]
public static string[] GetHostShareFromPath(string uncPath)
{
if (Utils.IsNullOrWhiteSpace(uncPath))
return null;
Uri uri;
if (Uri.TryCreate(Path.GetRegularPathCore(uncPath, GetFullPathOptions.None), UriKind.Absolute, out uri) && uri.IsUnc)
{
return new[]
{
uri.Host,
uri.AbsolutePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
};
}
return null;
}
#endregion // GetHostShareFromPath
#region GetShareInfo
/// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
/// <returns>A <see cref="ShareInfo"/> class, or <see langword="null"/> on failure or when not available, and <paramref name="continueOnException"/> is <see langword="true"/>.</returns>
/// <param name="uncPath">The share in the format: \\host\share.</param>
/// <param name="continueOnException"><see langword="true"/> to suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static ShareInfo GetShareInfo(string uncPath, bool continueOnException)
{
string[] unc = GetHostShareFromPath(uncPath);
return GetShareInfoCore(ShareInfoLevel.Info503, unc[0], unc[1], continueOnException);
}
/// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
/// <returns>A <see cref="ShareInfo"/> class, or <see langword="null"/> on failure or when not available, and <paramref name="continueOnException"/> is <see langword="true"/>.</returns>
/// <param name="shareLevel">One of the <see cref="ShareInfoLevel"/> options.</param>
/// <param name="uncPath">The share in the format: \\host\share.</param>
/// <param name="continueOnException"><see langword="true"/> to suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static ShareInfo GetShareInfo(ShareInfoLevel shareLevel, string uncPath, bool continueOnException)
{
string[] unc = GetHostShareFromPath(uncPath);
return GetShareInfoCore(shareLevel, unc[0], unc[1], continueOnException);
}
/// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
/// <returns>A <see cref="ShareInfo"/> class, or <see langword="null"/> on failure or when not available, and <paramref name="continueOnException"/> is <see langword="true"/>.</returns>
/// <param name="host">The DNS or NetBIOS name of the specified host.</param>
/// <param name="share">The name of the Server Message Block (SMB) share.</param>
/// <param name="continueOnException"><see langword="true"/> to suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static ShareInfo GetShareInfo(string host, string share, bool continueOnException)
{
return GetShareInfoCore(ShareInfoLevel.Info503, host, share, continueOnException);
}
/// <summary>Retrieves information about the Server Message Block (SMB) share as defined on the specified host.</summary>
/// <returns>A <see cref="ShareInfo"/> class, or <see langword="null"/> on failure or when not available, and <paramref name="continueOnException"/> is <see langword="true"/>.</returns>
/// <param name="shareLevel">One of the <see cref="ShareInfoLevel"/> options.</param>
/// <param name="host">A string that specifies the DNS or NetBIOS name of the specified <paramref name="host"/>.</param>
/// <param name="share">A string that specifies the name of the Server Message Block (SMB) share.</param>
/// <param name="continueOnException"><see langword="true"/> to suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
public static ShareInfo GetShareInfo(ShareInfoLevel shareLevel, string host, string share, bool continueOnException)
{
return GetShareInfoCore(shareLevel, host, share, continueOnException);
}
#endregion // GetShareInfo
#region Internal Methods
#region EnumerateOpenConnectionsCore
/// <summary>Enumerates open connections from the specified host.</summary>
/// <returns><see cref="OpenConnectionInfo"/> connection information from the specified <paramref name="host"/>.</returns>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="NetworkInformationException"/>
/// <param name="host">The DNS or NetBIOS name of the remote server. <see langword="null"/> refers to the local host.</param>
/// <param name="share">The name of the Server Message Block (SMB) share.</param>
/// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
private static IEnumerable<OpenConnectionInfo> EnumerateOpenConnectionsCore(string host, string share, bool continueOnException)
{
if (Utils.IsNullOrWhiteSpace(share))
throw new ArgumentNullException("share");
return EnumerateNetworkObjectCore(new FunctionData { ExtraData1 = share }, (NativeMethods.CONNECTION_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) =>
new OpenConnectionInfo(host, structure),
(FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>
{
// When host == null, the local computer is used.
// However, the resulting OpenResourceInfo.Host property will be empty.
// So, explicitly state Environment.MachineName to prevent this.
// Furthermore, the UNC prefix: \\ is not required and always removed.
string stripUnc = Utils.IsNullOrWhiteSpace(host) ? Environment.MachineName : Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars).Replace(Path.UncPrefix, string.Empty);
return NativeMethods.NetConnectionEnum(stripUnc, functionData.ExtraData1, 1, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle);
},
continueOnException);
}
#endregion // EnumerateOpenConnectionsCore
#region EnumerateSharesCore
/// <summary>Enumerates Server Message Block (SMB) shares from a local or remote host.</summary>
/// <returns><see cref="IEnumerable{ShareInfo}"/> shares from the specified host.</returns>
/// <remarks>This method also enumerates hidden shares.</remarks>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="NetworkInformationException"/>
/// <param name="host">The DNS or NetBIOS name of the specified host.</param>
/// <param name="shareType">The type of the shared resource to retrieve.</param>
/// <param name="continueOnException"><see langword="true"/> suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
internal static IEnumerable<ShareInfo> EnumerateSharesCore(string host, ShareType shareType, bool continueOnException)
{
// When host == null, the local computer is used.
// However, the resulting OpenResourceInfo.Host property will be empty.
// So, explicitly state Environment.MachineName to prevent this.
// Furthermore, the UNC prefix: \\ is not required and always removed.
string stripUnc = Utils.IsNullOrWhiteSpace(host)
? Environment.MachineName
: Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars).Replace(Path.UncPrefix, string.Empty);
var fd = new FunctionData();
bool hasItems = false;
bool yieldAll = shareType == ShareType.All;
// Try SHARE_INFO_503 structure.
foreach (var si in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_503 structure, SafeGlobalMemoryBufferHandle buffer) =>
new ShareInfo(stripUnc, ShareInfoLevel.Info503, structure),
(FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>
NativeMethods.NetShareEnum(stripUnc, 503, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType))
{
yield return si;
hasItems = true;
}
// SHARE_INFO_503 is requested, but not supported/possible.
// Try again with SHARE_INFO_2 structure.
if (!hasItems)
foreach (var si in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_2 structure, SafeGlobalMemoryBufferHandle buffer) =>
new ShareInfo(stripUnc, ShareInfoLevel.Info2, structure),
(FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>
NativeMethods.NetShareEnum(stripUnc, 2, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType))
{
yield return si;
hasItems = true;
}
// SHARE_INFO_2 is requested, but not supported/possible.
// Try again with SHARE_INFO_1 structure.
if (!hasItems)
foreach (var si in EnumerateNetworkObjectCore(fd, (NativeMethods.SHARE_INFO_1 structure, SafeGlobalMemoryBufferHandle buffer) =>
new ShareInfo(stripUnc, ShareInfoLevel.Info1, structure),
(FunctionData functionData, out SafeGlobalMemoryBufferHandle buffer, int prefMaxLen, out uint entriesRead, out uint totalEntries, out uint resumeHandle) =>
NativeMethods.NetShareEnum(stripUnc, 1, out buffer, NativeMethods.MaxPreferredLength, out entriesRead, out totalEntries, out resumeHandle), continueOnException).Where(si => yieldAll || si.ShareType == shareType))
{
yield return si;
}
}
#endregion // EnumerateSharesCore
#region GetShareInfoCore
/// <summary>Gets the <see cref="ShareInfo"/> structure of a Server Message Block (SMB) share.</summary>
/// <returns>A <see cref="ShareInfo"/> class, or <see langword="null"/> on failure or when not available, and <paramref name="continueOnException"/> is <see langword="true"/>.</returns>
/// <exception cref="NetworkInformationException"/>
/// <param name="shareLevel">One of the <see cref="ShareInfoLevel"/> options.</param>
/// <param name="host">A string that specifies the DNS or NetBIOS name of the specified <paramref name="host"/>.</param>
/// <param name="share">A string that specifies the name of the Server Message Block (SMB) share.</param>
/// <param name="continueOnException"><see langword="true"/> to suppress any Exception that might be thrown a result from a failure, such as unavailable resources.</param>
[SecurityCritical]
internal static ShareInfo GetShareInfoCore(ShareInfoLevel shareLevel, string host, string share, bool continueOnException)
{
if (Utils.IsNullOrWhiteSpace(share))
return null;
// When host == null, the local computer is used.
// However, the resulting OpenResourceInfo.Host property will be empty.
// So, explicitly state Environment.MachineName to prevent this.
// Furthermore, the UNC prefix: \\ is not required and always removed.
string stripUnc = Utils.IsNullOrWhiteSpace(host)
? Environment.MachineName
: Path.GetRegularPathCore(host, GetFullPathOptions.CheckInvalidPathChars).Replace(Path.UncPrefix, string.Empty);
bool fallback = false;
startNetShareGetInfo:
SafeGlobalMemoryBufferHandle safeBuffer;
uint structureLevel = Convert.ToUInt16(shareLevel, CultureInfo.InvariantCulture);
uint lastError = NativeMethods.NetShareGetInfo(stripUnc, share, structureLevel, out safeBuffer);
using (safeBuffer)
{
switch (lastError)
{
case Win32Errors.NERR_Success:
switch (shareLevel)
{
case ShareInfoLevel.Info1005:
return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_1005>(0))
{
NetFullPath = Path.CombineCore(false, Path.UncPrefix + stripUnc, share)
};
case ShareInfoLevel.Info503:
return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_503>(0));
case ShareInfoLevel.Info2:
return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_2>(0));
case ShareInfoLevel.Info1:
return new ShareInfo(stripUnc, shareLevel, safeBuffer.PtrToStructure<NativeMethods.SHARE_INFO_1>(0));
}
break;
// Observed when SHARE_INFO_503 is requested, but not supported/possible.
// Fall back on SHARE_INFO_2 structure and try again.
case Win32Errors.RPC_X_BAD_STUB_DATA:
case Win32Errors.ERROR_ACCESS_DENIED:
if (!fallback && shareLevel != ShareInfoLevel.Info2)
{
shareLevel = ShareInfoLevel.Info2;
fallback = true;
goto startNetShareGetInfo;
}
break;
default:
if (!continueOnException)
throw new NetworkInformationException((int) lastError);
break;
}
return null;
}
}
#endregion // GetShareInfoCore
#endregion // Internal Methods
}
}
| |
namespace PokerTell.PokerHandParsers.Base
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Interfaces.Parsers;
using PokerTell.Infrastructure.Enumerations.PokerHand;
using PokerTell.Infrastructure.Interfaces;
using PokerTell.Infrastructure.Interfaces.PokerHand;
public abstract class PlayerActionsParser : IPlayerActionsParser
{
public IDictionary<ActionTypes, string> ActionStrings;
protected readonly IConstructor<IAquiredPokerAction> _aquiredPokerActionMake;
protected string _playerName;
protected string _streetHistory;
protected PlayerActionsParser(IConstructor<IAquiredPokerAction> aquiredPokerActionMake)
{
_aquiredPokerActionMake = aquiredPokerActionMake;
CreateActionStrings();
}
public IList<IAquiredPokerAction> PlayerActions { get; protected set; }
protected abstract string ActionPattern { get; }
protected abstract string AllinBetPattern { get; }
protected abstract string UncalledBetPattern { get; }
protected abstract string WinningPattern { get; }
public virtual IPlayerActionsParser Parse(string streetHistory, string playerName)
{
_streetHistory = streetHistory;
_playerName = Regex.Escape(playerName);
PlayerActions = new List<IAquiredPokerAction>();
MatchCollection actions = MatchAllPlayerActions();
ExtractAllActions(actions);
ExtractUncalledBetActionIfItExists();
ExtractAllinBetActionIfItExists();
ExtractWinningActionIfItExists();
return this;
}
/// <summary>
/// Converts a human readable action to an Action What type and is called by the Hand Parser
/// </summary>
/// <param name="actionString">Human readable action as found in Hand History</param>
/// <returns>An ActionTypes type defining the action</returns>
protected static ActionTypes ConvertActionString(string actionString)
{
actionString = actionString.ToLower();
if (actionString.Contains("post") || actionString.Contains("antes"))
{
return ActionTypes.P;
}
if (actionString.Contains("fold"))
{
return ActionTypes.F;
}
if (actionString.Contains("check"))
{
return ActionTypes.X;
}
if (actionString.Contains("call"))
{
return ActionTypes.C;
}
if (actionString.Contains("bet"))
{
return ActionTypes.B;
}
if (actionString.Contains("raise"))
{
return ActionTypes.R;
}
if (actionString.Contains("collect") || actionString.Contains("won"))
{
return ActionTypes.W;
}
throw new FormatException("Invalid Action string " + actionString);
}
void CreateActionStrings()
{
ActionStrings = new Dictionary<ActionTypes, string>
{
{ ActionTypes.B, "bets" },
{ ActionTypes.C, "calls" },
{ ActionTypes.F, "folds" },
{ ActionTypes.P, "posts" },
{ ActionTypes.R, "raises" },
{ ActionTypes.X, "checks" },
};
}
void ExtractAction(Match action)
{
string actionString = action.Groups["What"].Value;
double ratio = action.Groups["Ratio"].Success
? Convert.ToDouble(action.Groups["Ratio"].Value.Replace(",", string.Empty))
: 1.0;
ActionTypes actionType = ConvertActionString(actionString);
IAquiredPokerAction aquiredAction = _aquiredPokerActionMake.New.InitializeWith(actionType, ratio);
PlayerActions.Add(aquiredAction);
}
void ExtractAllActions(MatchCollection actions)
{
foreach (Match action in actions)
{
ExtractAction(action);
}
}
void ExtractAllinBetAction(Match allinBet)
{
double ratio = Convert.ToDouble(allinBet.Groups["Ratio"].Value.Replace(",", string.Empty));
IAquiredPokerAction allinBetAction = _aquiredPokerActionMake.New.InitializeWith(ActionTypes.A, ratio);
PlayerActions.Add(allinBetAction);
}
void ExtractAllinBetActionIfItExists()
{
Match allinBet = MatchAllinBet();
if (allinBet.Success)
{
ExtractAllinBetAction(allinBet);
}
}
void ExtractUncalledBetAction(Match uncalledBet)
{
double ratio = Convert.ToDouble(uncalledBet.Groups["Ratio"].Value.Replace(",", string.Empty));
IAquiredPokerAction uncalledBetAction = _aquiredPokerActionMake.New.InitializeWith(ActionTypes.U, ratio);
PlayerActions.Add(uncalledBetAction);
}
void ExtractUncalledBetActionIfItExists()
{
Match uncalledBet = MatchUncalledBet();
if (uncalledBet.Success)
{
ExtractUncalledBetAction(uncalledBet);
}
}
void ExtractWinningAction(Match winning)
{
double ratio = Convert.ToDouble(winning.Groups["Ratio"].Value.Replace(",", string.Empty));
IAquiredPokerAction winningAction = _aquiredPokerActionMake.New.InitializeWith(ActionTypes.W, ratio);
PlayerActions.Add(winningAction);
}
void ExtractWinningActionIfItExists()
{
Match winning = MatchWinning();
if (winning.Success)
{
ExtractWinningAction(winning);
}
}
Match MatchAllinBet()
{
return Regex.Match(_streetHistory, AllinBetPattern, RegexOptions.IgnoreCase);
}
MatchCollection MatchAllPlayerActions()
{
return Regex.Matches(_streetHistory, ActionPattern, RegexOptions.IgnoreCase);
}
Match MatchUncalledBet()
{
return Regex.Match(_streetHistory, UncalledBetPattern, RegexOptions.IgnoreCase);
}
Match MatchWinning()
{
return Regex.Match(_streetHistory, WinningPattern, RegexOptions.IgnoreCase);
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
function WorldEditor::onSelect( %this, %obj )
{
EditorTree.addSelection( %obj );
_setShadowVizLight( %obj );
//Inspector.inspect( %obj );
if ( isObject( %obj ) && %obj.isMethod( "onEditorSelect" ) )
%obj.onEditorSelect( %this.getSelectionSize() );
EditorGui.currentEditor.onObjectSelected( %obj );
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the materialEditorList
$Tools::materialEditorList = %obj.getId();
// Used to help the Material Editor( the M.E doesn't utilize its own TS control )
// so this dirty extension is used to fake it
if ( MaterialEditorPreviewWindow.isVisible() )
MaterialEditorGui.prepareActiveObject();
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onMultiSelect( %this, %set )
{
// This is called when completing a drag selection ( on3DMouseUp )
// so we can avoid calling onSelect for every object. We can only
// do most of this stuff, like inspecting, on one object at a time anyway.
%count = %set.getCount();
%i = 0;
foreach( %obj in %set )
{
if ( %obj.isMethod( "onEditorSelect" ) )
%obj.onEditorSelect( %count );
%i ++;
EditorTree.addSelection( %obj, %i == %count );
EditorGui.currentEditor.onObjectSelected( %obj );
}
// Inform the camera
commandToServer( 'EditorOrbitCameraSelectChange', %count, %this.getSelectionCentroid() );
EditorGuiStatusBar.setSelectionObjectsByCount( EWorldEditor.getSelectionSize() );
// Update the Transform Selection window, if it is
// visible.
if( ETransformSelection.isVisible() )
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onUnSelect( %this, %obj )
{
if ( isObject( %obj ) && %obj.isMethod( "onEditorUnselect" ) )
%obj.onEditorUnselect();
EditorGui.currentEditor.onObjectDeselected( %obj );
Inspector.removeInspect( %obj );
EditorTree.removeSelection(%obj);
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onClearSelection( %this )
{
EditorGui.currentEditor.onSelectionCleared();
EditorTree.clearSelection();
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onSelectionCentroidChanged( %this )
{
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
}
//////////////////////////////////////////////////////////////////////////
function WorldEditor::init(%this)
{
// add objclasses which we do not want to collide with
%this.ignoreObjClass(Sky, AIObjective);
// editing modes
%this.numEditModes = 3;
%this.editMode[0] = "move";
%this.editMode[1] = "rotate";
%this.editMode[2] = "scale";
// context menu
new GuiControl(WEContextPopupDlg, EditorGuiGroup)
{
profile = "GuiModelessDialogProfile";
horizSizing = "width";
vertSizing = "height";
position = "0 0";
extent = "640 480";
minExtent = "8 8";
visible = "1";
setFirstResponder = "0";
modal = "1";
new GuiPopUpMenuCtrl(WEContextPopup)
{
profile = "GuiScrollProfile";
position = "0 0";
extent = "0 0";
minExtent = "0 0";
maxPopupHeight = "200";
command = "canvas.popDialog(WEContextPopupDlg);";
};
};
WEContextPopup.setVisible(false);
// Make sure we have an active selection set.
if( !%this.getActiveSelection() )
%this.setActiveSelection( new WorldEditorSelection( EWorldEditorSelection ) );
}
//------------------------------------------------------------------------------
function WorldEditor::onDblClick(%this, %obj)
{
// Commented out because making someone double click to do this is stupid
// and has the possibility of moving hte object
//Inspector.inspect(%obj);
//InspectorNameEdit.setValue(%obj.getName());
}
function WorldEditor::onClick( %this, %obj )
{
Inspector.inspect( %obj );
}
function WorldEditor::onEndDrag( %this, %obj )
{
Inspector.inspect( %obj );
Inspector.apply();
}
//------------------------------------------------------------------------------
function WorldEditor::export(%this)
{
getSaveFilename("~/editor/*.mac|mac file", %this @ ".doExport", "selection.mac");
}
function WorldEditor::doExport(%this, %file)
{
missionGroup.save("~/editor/" @ %file, true);
}
function WorldEditor::import(%this)
{
getLoadFilename("~/editor/*.mac|mac file", %this @ ".doImport");
}
function WorldEditor::doImport(%this, %file)
{
exec("~/editor/" @ %file);
}
function WorldEditor::onGuiUpdate(%this, %text)
{
}
function WorldEditor::getSelectionLockCount(%this)
{
%ret = 0;
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
if(%obj.locked)
%ret++;
}
return %ret;
}
function WorldEditor::getSelectionHiddenCount(%this)
{
%ret = 0;
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
if(%obj.hidden)
%ret++;
}
return %ret;
}
function WorldEditor::dropCameraToSelection(%this)
{
if(%this.getSelectionSize() == 0)
return;
%pos = %this.getSelectionCentroid();
%cam = LocalClientConnection.camera.getTransform();
// set the pnt
%cam = setWord(%cam, 0, getWord(%pos, 0));
%cam = setWord(%cam, 1, getWord(%pos, 1));
%cam = setWord(%cam, 2, getWord(%pos, 2));
LocalClientConnection.camera.setTransform(%cam);
}
/// Pastes the selection at the same place (used to move obj from a group to another)
function WorldEditor::moveSelectionInPlace(%this)
{
%saveDropType = %this.dropType;
%this.dropType = "atCentroid";
%this.copySelection();
%this.deleteSelection();
%this.pasteSelection();
%this.dropType = %saveDropType;
}
function WorldEditor::addSelectionToAddGroup(%this)
{
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
$InstantGroup.add(%obj);
}
}
// resets the scale and rotation on the selection set
function WorldEditor::resetTransforms(%this)
{
%this.addUndoState();
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
%transform = %obj.getTransform();
%transform = setWord(%transform, 3, "0");
%transform = setWord(%transform, 4, "0");
%transform = setWord(%transform, 5, "1");
%transform = setWord(%transform, 6, "0");
//
%obj.setTransform(%transform);
%obj.setScale("1 1 1");
}
}
function WorldEditorToolbarDlg::init(%this)
{
WorldEditorInspectorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolInspectorGui" ) );
WorldEditorMissionAreaCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolMissionAreaGui" ) );
WorldEditorTreeCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolTreeViewGui" ) );
WorldEditorCreatorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolCreatorGui" ) );
}
function WorldEditor::onAddSelected(%this,%obj)
{
EditorTree.addSelection(%obj);
}
function WorldEditor::onWorldEditorUndo( %this )
{
Inspector.refresh();
}
function Inspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )
{
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %oldValue;
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
// If it's a datablock, initiate a retransmit. Don't do so
// immediately so as the actual field value will only be set
// by the inspector code after this method has returned.
if( %object.isMemberOfClass( "SimDataBlock" ) )
%object.schedule( 1, "reloadOnLocalClient" );
// Restore the instant group.
popInstantGroup();
%action.addToManager( Editor.getUndoManager() );
EWorldEditor.isDirty = true;
// Update the selection
if(EWorldEditor.getSelectionSize() > 0 && (%fieldName $= "position" || %fieldName $= "rotation" || %fieldName $= "scale"))
{
EWorldEditor.invalidateSelectionCentroid();
}
}
function Inspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )
{
FieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
// The following three methods are for fields that edit field value live and thus cannot record
// undo information during edits. For these fields, undo information is recorded in advance and
// then either queued or disarded when the field edit is finished.
function Inspector::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex )
{
pushInstantGroup();
%undoManager = Editor.getUndoManager();
%numObjects = %this.getNumInspectObjects();
if( %numObjects > 1 )
%action = %undoManager.pushCompound( "Multiple Field Edit" );
for( %i = 0; %i < %numObjects; %i ++ )
{
%object = %this.getInspectObject( %i );
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%undo = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %object.getFieldValue( %fieldName, %arrayIndex );
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
if( %numObjects > 1 )
%undo.addToManager( %undoManager );
else
{
%action = %undo;
break;
}
}
%this.currentFieldEditAction = %action;
popInstantGroup();
}
function Inspector::onInspectorPostFieldModification( %this )
{
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) )
{
// Finish multiple field edit.
Editor.getUndoManager().popCompound();
}
else
{
// Queue single field undo.
%this.currentFieldEditAction.addToManager( Editor.getUndoManager() );
}
%this.currentFieldEditAction = "";
EWorldEditor.isDirty = true;
}
function Inspector::onInspectorDiscardFieldModification( %this )
{
%this.currentFieldEditAction.undo();
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) )
{
// Multiple field editor. Pop and discard.
Editor.getUndoManager().popCompound( true );
}
else
{
// Single field edit. Just kill undo action.
%this.currentFieldEditAction.delete();
}
%this.currentFieldEditAction = "";
}
function Inspector::inspect( %this, %obj )
{
//echo( "inspecting: " @ %obj );
%name = "";
if ( isObject( %obj ) )
%name = %obj.getName();
else
FieldInfoControl.setText( "" );
//InspectorNameEdit.setValue( %name );
Parent::inspect( %this, %obj );
}
function Inspector::onBeginCompoundEdit( %this )
{
Editor.getUndoManager().pushCompound( "Multiple Field Edit" );
}
function Inspector::onEndCompoundEdit( %this )
{
Editor.getUndoManager().popCompound();
}
function Inspector::onCancelCompoundEdit( %this )
{
Editor.getUndoManager().popCompound( true );
}
function foCollaps (%this, %tab){
switch$ (%tab){
case "container0":
%tab.visible = "0";
buttxon1.position = getWord(buttxon0.position, 0)+32 SPC getWord(buttxon1.position, 1);
buttxon2.position = getWord(buttxon1.position, 0)+32 SPC getWord(buttxon2.position, 1);
case "container1":
%tab.visible = "0";
case "container2":
%tab.visible = "0";
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
namespace Lucene.Net.Store
{
/// <summary> <p/>Implements {@link LockFactory} using {@link
/// File#createNewFile()}.<p/>
///
/// <p/><b>NOTE:</b> the <a target="_top"
/// href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#createNewFile()">javadocs
/// for <code>File.createNewFile</code></a> contain a vague
/// yet spooky warning about not using the API for file
/// locking. This warning was added due to <a target="_top"
/// href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4676183">this
/// bug</a>, and in fact the only known problem with using
/// this API for locking is that the Lucene write lock may
/// not be released when the JVM exits abnormally.<p/>
/// <p/>When this happens, a {@link LockObtainFailedException}
/// is hit when trying to create a writer, in which case you
/// need to explicitly clear the lock file first. You can
/// either manually remove the file, or use the {@link
/// org.apache.lucene.index.IndexReader#unlock(Directory)}
/// API. But, first be certain that no writer is in fact
/// writing to the index otherwise you can easily corrupt
/// your index.<p/>
///
/// <p/>If you suspect that this or any other LockFactory is
/// not working properly in your environment, you can easily
/// test it by using {@link VerifyingLockFactory}, {@link
/// LockVerifyServer} and {@link LockStressTest}.<p/>
///
/// </summary>
/// <seealso cref="LockFactory">
/// </seealso>
public class SimpleFSLockFactory:FSLockFactory
{
/// <summary> Create a SimpleFSLockFactory instance, with null (unset)
/// lock directory. When you pass this factory to a {@link FSDirectory}
/// subclass, the lock directory is automatically set to the
/// directory itsself. Be sure to create one instance for each directory
/// your create!
/// </summary>
public SimpleFSLockFactory():this((System.IO.DirectoryInfo) null)
{
}
/// <summary> Instantiate using the provided directory (as a File instance).</summary>
/// <param name="lockDir">where lock files should be created.
/// </param>
[System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public SimpleFSLockFactory(System.IO.FileInfo lockDir)
{
SetLockDir(new System.IO.DirectoryInfo(lockDir.FullName));
}
/// <summary> Instantiate using the provided directory (as a File instance).</summary>
/// <param name="lockDir">where lock files should be created.
/// </param>
public SimpleFSLockFactory(System.IO.DirectoryInfo lockDir)
{
SetLockDir(lockDir);
}
/// <summary> Instantiate using the provided directory name (String).</summary>
/// <param name="lockDirName">where lock files should be created.
/// </param>
public SimpleFSLockFactory(System.String lockDirName)
{
lockDir = new System.IO.DirectoryInfo(lockDirName);
SetLockDir(lockDir);
}
public override Lock MakeLock(System.String lockName)
{
if (lockPrefix != null)
{
lockName = lockPrefix + "-" + lockName;
}
return new SimpleFSLock(lockDir, lockName);
}
public override void ClearLock(System.String lockName)
{
bool tmpBool;
if (System.IO.File.Exists(lockDir.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockDir.FullName);
if (tmpBool)
{
if (lockPrefix != null)
{
lockName = lockPrefix + "-" + lockName;
}
System.IO.FileInfo lockFile = new System.IO.FileInfo(System.IO.Path.Combine(lockDir.FullName, lockName));
bool tmpBool2;
if (System.IO.File.Exists(lockFile.FullName))
tmpBool2 = true;
else
tmpBool2 = System.IO.Directory.Exists(lockFile.FullName);
bool tmpBool3;
if (System.IO.File.Exists(lockFile.FullName))
{
System.IO.File.Delete(lockFile.FullName);
tmpBool3 = true;
}
else if (System.IO.Directory.Exists(lockFile.FullName))
{
System.IO.Directory.Delete(lockFile.FullName);
tmpBool3 = true;
}
else
tmpBool3 = false;
if (tmpBool2 && !tmpBool3)
{
throw new System.IO.IOException("Cannot delete " + lockFile);
}
}
}
}
class SimpleFSLock:Lock
{
internal System.IO.FileInfo lockFile;
internal System.IO.DirectoryInfo lockDir;
[System.Obsolete("Use the constructor that takes a DirectoryInfo, this will be removed in the 3.0 release")]
public SimpleFSLock(System.IO.FileInfo lockDir, System.String lockFileName) : this(new System.IO.DirectoryInfo(lockDir.FullName), lockFileName)
{
}
public SimpleFSLock(System.IO.DirectoryInfo lockDir, System.String lockFileName)
{
this.lockDir = new System.IO.DirectoryInfo(lockDir.FullName);
lockFile = new System.IO.FileInfo(System.IO.Path.Combine(lockDir.FullName, lockFileName));
}
public override bool Obtain()
{
// Ensure that lockDir exists and is a directory:
bool tmpBool;
if (System.IO.File.Exists(lockDir.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockDir.FullName);
if (!tmpBool)
{
try
{
System.IO.Directory.CreateDirectory(lockDir.FullName);
}
catch
{
throw new System.IO.IOException("Cannot create directory: " + lockDir.FullName);
}
}
else
{
try
{
System.IO.Directory.Exists(lockDir.FullName);
}
catch
{
throw new System.IO.IOException("Found regular file where directory expected: " + lockDir.FullName);
}
}
if (lockFile.Exists)
{
return false;
}
else
{
System.IO.FileStream createdFile = lockFile.Create();
createdFile.Close();
return true;
}
}
public override void Release()
{
bool tmpBool;
if (System.IO.File.Exists(lockFile.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockFile.FullName);
bool tmpBool2;
if (System.IO.File.Exists(lockFile.FullName))
{
System.IO.File.Delete(lockFile.FullName);
tmpBool2 = true;
}
else if (System.IO.Directory.Exists(lockFile.FullName))
{
System.IO.Directory.Delete(lockFile.FullName);
tmpBool2 = true;
}
else
tmpBool2 = false;
if (tmpBool && !tmpBool2)
throw new LockReleaseFailedException("failed to delete " + lockFile);
}
public override bool IsLocked()
{
bool tmpBool;
if (System.IO.File.Exists(lockFile.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(lockFile.FullName);
return tmpBool;
}
public override System.String ToString()
{
return "SimpleFSLock@" + lockFile;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using HappyGB.Core.Graphics;
using HappyGB.Core.Memory;
namespace HappyGB.Core.Cpu
{
/// <summary>
/// Gameboy Z80 CPU.
/// </summary>
public partial class GBZ80
{
private RegisterGroup R;
private MemoryMap M;
private bool cpuInterruptEnable;
private bool halted;
private ulong localTickCount;
/// <summary>
/// The frequency count of instructions.
/// Used for debugging, to get which instructions are executed less / more frequently, so that we know
/// which ones are potentially problematic (executed a few times, when the emulator is relatively stable)
/// or potentially performance bottlenecks (executed millions of times a frame).
/// </summary>
public long[] InstructionFrequencyCount
{
get; private set;
}
private HashSet<ushort> breakpoints = new HashSet<ushort>();
private Stack<ushort> stackTrace = new Stack<ushort>();
//private void dumpstate()...
public RegisterGroup Registers
{
get { return R; }
}
public GBZ80(MemoryMap memoryMap)
{
R = new RegisterGroup();
M = memoryMap;
localTickCount = 0;
AddBreakpoints();
InstructionFrequencyCount = new long[512];
}
public void Reset()
{
R.af = 0x01B0;
R.UpdateFlagsFromAF();
R.bc = 0x0013;
R.de = 0x00D8;
R.hl = 0x014D;
R.sp = 0xFFFE;
if (M.BiosEnabled == false)
R.pc = 0x0100;
else R.pc = 0x0000;
cpuInterruptEnable = false;
//Timers.
M[0xFF05] = M[0xFF06] = M[0xFF07] = 0x00;
//TODO: Sound
//Graphics.
M[0xFF40] = 0x91; //LCDC
M[0xFF42] = M[0xFF43] = M[0xFF45] = 0x00; //scx scy lyc
M[0xFF47] = 0xFC; //Palettes.
M[0xFF48] = 0xFF;
M[0xFF49] = 0xFF;
M[0xFF4A] = M[0xFF4B] = 0x00; //wx wy
M[0xFFFF] = 0x00; //IE
}
public bool Run(GraphicsController graphics, TimerController interrupts)
{
//Run until an interrupt is hit.
//Then handle that interrupt.
ulong startTicks;
ulong ticksSinceLastYield = localTickCount;
var lcdInterrupt = InterruptType.None;
halted = false;
bool shouldYield = false;
while (true) {
var pcOld = R.pc;
///Hack: Breakpoints will be implemented actually sometime.
if (IsAtBreakpoint())
{
System.Diagnostics.Debug.WriteLine("Breakpoint at 0x{0:x4} triggered.", R.pc);
}
//Handle interrupts.
if (cpuInterruptEnable && ((M.IE & M.IF) != 0))
{
halted = false;
var mf = (InterruptType)M.IF;
if (mf.HasFlag(InterruptType.VBlank))
{
//Handle VBlank
HandleInterrupt(InterruptType.VBlank);
}
if (mf.HasFlag(InterruptType.LCDController))
{
//Handle LCDC stat
HandleInterrupt(InterruptType.LCDController);
}
if (mf.HasFlag(InterruptType.TimerOverflow))
{
//Handle timer
HandleInterrupt(InterruptType.TimerOverflow);
}
if (mf.HasFlag(InterruptType.SerialComplete))
{
HandleInterrupt(InterruptType.SerialComplete);
}
if (mf.HasFlag(InterruptType.ButtonPress))
{
//Handle bpress
HandleInterrupt(InterruptType.ButtonPress);
}
}
startTicks = localTickCount;
if (halted)
Tick(4);
else
Execute(); //Run one instruction.
//Update the lcd controller.
int instructionTicks = (int)(localTickCount - startTicks);
lcdInterrupt = graphics.Update(instructionTicks);
if (lcdInterrupt.HasFlag(InterruptType.VBlank)) //Yield on vblank so we can draw the next frame.
shouldYield = true;
M.IF |= (byte)lcdInterrupt;
//Handle interrupts in priority order.
M.IF |= (byte)interrupts.Tick(instructionTicks);
if (shouldYield)
return true;
}
throw new InvalidOperationException("This shouldn't have gotten here.");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Tick(ulong ticks)
{
localTickCount += ticks;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte Fetch8()
{
byte ret = M[R.pc];
R.pc++;
return ret;
}
public ushort Fetch16()
{
ushort ret = M.Read16(R.pc);
R.pc += 2;
return ret;
}
public void HandleInterrupt(InterruptType interrupt)
{
M.IF &= (byte)(0xFF - (byte)interrupt); //Unset in IF.
cpuInterruptEnable = false; //Unset master interrupt.
switch (interrupt)
{
case InterruptType.VBlank:
RST(0x40);
break;
case InterruptType.LCDController:
RST(0x48);
break;
case InterruptType.TimerOverflow:
RST(0x50);
break;
case InterruptType.SerialComplete:
RST(0x58);
break;
case InterruptType.ButtonPress:
RST(0x60);
break;
}
Tick(12);
}
/// <summary>
/// Checks if the list of breakpoints contains the current PC.
/// </summary>
/// <returns></returns>
public bool IsAtBreakpoint()
{
if (breakpoints.Contains(this.R.pc))
return true;
else return false;
}
/// <summary>
/// Adds each of the breakpoints.
/// </summary>
public void AddBreakpoints()
{
breakpoints.Add(0x100); //Entry point for ROM
breakpoints.Add(0x0546);
breakpoints.Add(0x1aac);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Globalization;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class ExceptionTest
{
// data value and server consts
private const string badServer = "NotAServer";
private const string sqlsvrBadConn = "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.";
private const string logonFailedErrorMessage = "Login failed for user '{0}'.";
private const string execReaderFailedMessage = "ExecuteReader requires an open and available Connection. The connection's current state is closed.";
private const string warningNoiseMessage = "The full-text search condition contained noise word(s).";
private const string warningInfoMessage = "Test of info messages";
private const string orderIdQuery = "select orderid from orders where orderid < 10250";
#if MANAGED_SNI
[CheckConnStrSetupFact]
public static void NonWindowsIntAuthFailureTest()
{
string connectionString = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { IntegratedSecurity = true }).ConnectionString;
Assert.Throws<NotSupportedException>(() => new SqlConnection(connectionString).Open());
// Should not receive any exception when using IntAuth=false
connectionString = (new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { IntegratedSecurity = false }).ConnectionString;
new SqlConnection(connectionString).Open();
}
#endif
[CheckConnStrSetupFact]
public static void WarningTest()
{
Action<object, SqlInfoMessageEventArgs> warningCallback =
(object sender, SqlInfoMessageEventArgs imevent) =>
{
for (int i = 0; i < imevent.Errors.Count; i++)
{
Assert.True(imevent.Errors[i].Message.Contains(warningInfoMessage), "FAILED: WarningTest Callback did not contain correct message.");
}
};
SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback);
using (SqlConnection sqlConnection = new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { Pooling = false }).ConnectionString))
{
sqlConnection.InfoMessage += handler;
sqlConnection.Open();
SqlCommand cmd = new SqlCommand(string.Format("PRINT N'{0}'", warningInfoMessage), sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.InfoMessage -= handler;
cmd.ExecuteNonQuery();
}
}
[CheckConnStrSetupFact]
public static void WarningsBeforeRowsTest()
{
bool hitWarnings = false;
int iteration = 0;
Action<object, SqlInfoMessageEventArgs> warningCallback =
(object sender, SqlInfoMessageEventArgs imevent) =>
{
for (int i = 0; i < imevent.Errors.Count; i++)
{
Assert.True(imevent.Errors[i].Message.Contains(warningNoiseMessage), "FAILED: WarningsBeforeRowsTest Callback did not contain correct message. Failed in loop iteration: " + iteration);
}
hitWarnings = true;
};
SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback);
SqlConnection sqlConnection = new SqlConnection(DataTestUtility.TcpConnStr);
sqlConnection.InfoMessage += handler;
sqlConnection.Open();
foreach (string orderClause in new string[] { "", " order by FirstName" })
{
foreach (bool messagesOnErrors in new bool[] { true, false })
{
iteration++;
sqlConnection.FireInfoMessageEventOnUserErrors = messagesOnErrors;
// These queries should return warnings because AND here is a noise word.
SqlCommand cmd = new SqlCommand("select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"Anne AND\"')" + orderClause, sqlConnection);
using (SqlDataReader reader = cmd.ExecuteReader())
{
Assert.True(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be TRUE)");
bool receivedRows = false;
while (reader.Read())
{
receivedRows = true;
}
Assert.True(receivedRows, "FAILED: Should have received rows from this query.");
Assert.True(hitWarnings, "FAILED: Should have received warnings from this query");
}
hitWarnings = false;
cmd.CommandText = "select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"NotARealPerson AND\"')" + orderClause;
using (SqlDataReader reader = cmd.ExecuteReader())
{
Assert.False(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be FALSE)");
bool receivedRows = false;
while (reader.Read())
{
receivedRows = true;
}
Assert.False(receivedRows, "FAILED: Should have NOT received rows from this query.");
Assert.True(hitWarnings, "FAILED: Should have received warnings from this query");
}
}
}
sqlConnection.Close();
}
private static bool CheckThatExceptionsAreDistinctButHaveSameData(SqlException e1, SqlException e2)
{
Assert.True(e1 != e2, "FAILED: verification of exception cloning in subsequent connection attempts");
Assert.False((e1 == null) || (e2 == null), "FAILED: One of exceptions is null, another is not");
bool equal = (e1.Message == e2.Message) && (e1.HelpLink == e2.HelpLink) && (e1.InnerException == e2.InnerException)
&& (e1.Source == e2.Source) && (e1.Data.Count == e2.Data.Count) && (e1.Errors == e2.Errors);
IDictionaryEnumerator enum1 = e1.Data.GetEnumerator();
IDictionaryEnumerator enum2 = e2.Data.GetEnumerator();
while (equal)
{
if (!enum1.MoveNext())
break;
enum2.MoveNext();
equal = (enum1.Key == enum2.Key) && (enum2.Value == enum2.Value);
}
Assert.True(equal, string.Format("FAILED: exceptions do not contain the same data (besides call stack):\nFirst: {0}\nSecond: {1}\n", e1, e2));
return true;
}
[CheckConnStrSetupFact]
public static void ExceptionTests()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
// tests improper server name thrown from constructor of tdsparser
SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), sqlsvrBadConn, VerifyException);
// tests incorrect password - thrown from the adapter
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty };
string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
// tests incorrect database name - exception thrown from adapter
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { InitialCatalog = "NotADatabase" };
errorMessage = string.Format(CultureInfo.InvariantCulture, "Cannot open database \"{0}\" requested by the login. The login failed.", badBuilder.InitialCatalog);
SqlException firstAttemptException = VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 2, 4060, 1, 11));
// Verify that the same error results in a different instance of an exception, but with the same data
VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => CheckThatExceptionsAreDistinctButHaveSameData(firstAttemptException, ex));
// tests incorrect user name - exception thrown from adapter
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { UserID = "NotAUser" };
errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
}
[CheckConnStrSetupFact]
public static void VariousExceptionTests()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
// Test 1 - A
SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
{
using (SqlCommand command = sqlConnection.CreateCommand())
{
command.CommandText = orderIdQuery;
VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
}
}
// Test 1 - B
badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty };
using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
{
string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID);
VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14));
}
}
[CheckConnStrSetupFact]
public static void IndependentConnectionExceptionTest()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 };
using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString))
{
// Test 1
VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), sqlsvrBadConn, VerifyException);
// Test 2
using (SqlCommand command = new SqlCommand(orderIdQuery, sqlConnection))
{
VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage);
}
}
}
private static void GenerateConnectionException(string connectionString)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand command = sqlConnection.CreateCommand())
{
command.CommandText = orderIdQuery;
command.ExecuteReader();
}
}
}
private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage, Func<TException, bool> exVerifier) where TException : Exception
{
TException ex = Assert.Throws<TException>(connectAction);
Assert.True(ex.Message.Contains(expectedExceptionMessage), string.Format("FAILED: SqlException did not contain expected error message. Actual message: {0}", ex.Message));
Assert.True(exVerifier(ex), "FAILED: Exception verifier failed on the exception.");
return ex;
}
private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage) where TException : Exception
{
return VerifyConnectionFailure<TException>(connectAction, expectedExceptionMessage, (ex) => true);
}
private static bool VerifyException(SqlException exception)
{
VerifyException(exception, 1);
return true;
}
private static bool VerifyException(SqlException exception, int count, int? errorNumber = null, int? errorState = null, int? severity = null)
{
// Verify that there are the correct number of errors in the exception
Assert.True(exception.Errors.Count == count, string.Format("FAILED: Incorrect number of errors. Expected: {0}. Actual: {1}.", count, exception.Errors.Count));
// Ensure that all errors have an error-level severity
for (int i = 0; i < count; i++)
{
Assert.True(exception.Errors[i].Class >= 10, "FAILED: verification of Exception! Exception contains a warning!");
}
// Check the properties of the exception populated by the server are correct
if (errorNumber.HasValue)
{
Assert.True(errorNumber.Value == exception.Number, string.Format("FAILED: Error number of exception is incorrect. Expected: {0}. Actual: {1}.", errorNumber.Value, exception.Number));
}
if (errorState.HasValue)
{
Assert.True(errorState.Value == exception.State, string.Format("FAILED: Error state of exception is incorrect. Expected: {0}. Actual: {1}.", errorState.Value, exception.State));
}
if (severity.HasValue)
{
Assert.True(severity.Value == exception.Class, string.Format("FAILED: Severity of exception is incorrect. Expected: {0}. Actual: {1}.", severity.Value, exception.Class));
}
if ((errorNumber.HasValue) && (errorState.HasValue) && (severity.HasValue))
{
string detailsText = string.Format("Error Number:{0},State:{1},Class:{2}", errorNumber.Value, errorState.Value, severity.Value);
Assert.True(exception.ToString().Contains(detailsText), string.Format("FAILED: SqlException.ToString does not contain the error number, state and severity information"));
}
// verify that the this[] function on the collection works, as well as the All function
SqlError[] errors = new SqlError[exception.Errors.Count];
exception.Errors.CopyTo(errors, 0);
Assert.True((errors[0].Message).Equals(exception.Errors[0].Message), string.Format("FAILED: verification of Exception! ErrorCollection indexer/CopyTo resulted in incorrect value."));
return true;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
namespace System.Management.Automation
{
internal class MUIFileSearcher
{
/// <summary>
/// Constructor. It is private so that MUIFileSearcher is used only internal for this class.
/// To access functionality in this class, static api should be used.
/// </summary>
/// <param name="target"></param>
/// <param name="searchPaths"></param>
/// <param name="searchMode"></param>
private MUIFileSearcher(string target, Collection<String> searchPaths, SearchMode searchMode)
{
Target = target;
SearchPaths = searchPaths;
SearchMode = searchMode;
}
/// <summary>
/// A constructor to make searchMode optional.
/// </summary>
/// <param name="target"></param>
/// <param name="searchPaths"></param>
private MUIFileSearcher(string target, Collection<String> searchPaths)
: this(target, searchPaths, SearchMode.Unique)
{
}
#region Basic Properties
/// <summary>
/// Search target. It can be
/// 1. a file name
/// 2. a search pattern
/// It can also include a path, in that case,
/// 1. the path will be searched first for the existence of the files.
/// </summary>
internal string Target { get; } = null;
/// <summary>
/// Search path as provided by user.
/// </summary>
internal Collection<String> SearchPaths { get; } = null;
/// <summary>
/// Search mode for this file search.
/// </summary>
internal SearchMode SearchMode { get; } = SearchMode.Unique;
private Collection<String> _result = null;
/// <summary>
/// Result of the search.
/// </summary>
internal Collection<String> Result
{
get
{
if (_result == null)
{
_result = new Collection<String>();
// SearchForFiles will fill the result collection.
SearchForFiles();
}
return _result;
}
}
#endregion
#region File Search
/// <summary>
/// _uniqueMatches is used to track matches already found during the search process.
/// This is useful for ignoring duplicates in the case of unique search.
/// </summary>
private Hashtable _uniqueMatches = new Hashtable(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// search for files using the target, searchPaths member of this class.
/// </summary>
private void SearchForFiles()
{
if (String.IsNullOrEmpty(this.Target))
return;
string pattern = Path.GetFileName(this.Target);
if (String.IsNullOrEmpty(pattern))
return;
Collection<String> normalizedSearchPaths = NormalizeSearchPaths(this.Target, this.SearchPaths);
foreach (string directory in normalizedSearchPaths)
{
SearchForFiles(pattern, directory);
if (this.SearchMode == SearchMode.First && this.Result.Count > 0)
{
return;
}
}
}
private string[] GetFiles(string path, string pattern)
{
#if UNIX
// On Linux, file names are case sensitive, so we need to add
// extra logic to select the files that match the given pattern.
ArrayList result = new ArrayList();
string[] files = Directory.GetFiles(path);
foreach (string filePath in files)
{
if (filePath.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) >= 0)
{
result.Add(filePath);
}
}
return (String[])result.ToArray(typeof(string));
#else
return Directory.GetFiles(path, pattern);
#endif
}
private void AddFiles(string muiDirectory, string directory, string pattern)
{
if (Directory.Exists(muiDirectory))
{
string[] files = GetFiles(muiDirectory, pattern);
if (files == null)
return;
foreach (string file in files)
{
string path = Path.Combine(muiDirectory, file);
switch (this.SearchMode)
{
case SearchMode.All:
_result.Add(path);
break;
case SearchMode.Unique:
// Construct a Unique filename for this directory.
// Remember the file may belong to one of the sub-culture
// directories. In this case we should not be returning
// same files that are residing in 2 or more sub-culture
// directories.
string leafFileName = Path.GetFileName(file);
string uniqueToDirectory = Path.Combine(directory, leafFileName);
if (!_uniqueMatches.Contains(uniqueToDirectory))
{
_result.Add(path);
_uniqueMatches[uniqueToDirectory] = true;
}
break;
case SearchMode.First:
_result.Add(path);
return;
default:
break;
}
}
}
}
/// <summary>
/// Search for files of a particular pattern under a particular directory.
/// This will do MUI search in which appropriate language directories are
/// searched in order.
/// </summary>
/// <param name="pattern"></param>
/// <param name="directory"></param>
private void SearchForFiles(string pattern, string directory)
{
List<string> cultureNameList = new List<string>();
CultureInfo culture = CultureInfo.CurrentUICulture;
while (culture != null && !String.IsNullOrEmpty(culture.Name))
{
cultureNameList.Add(culture.Name);
culture = culture.Parent;
}
cultureNameList.Add("");
// Add en-US and en as fallback languages
if (!cultureNameList.Contains("en-US"))
{
cultureNameList.Add("en-US");
}
if (!cultureNameList.Contains("en"))
{
cultureNameList.Add("en");
}
foreach (string name in cultureNameList)
{
string muiDirectory = Path.Combine(directory, name);
AddFiles(muiDirectory, directory, pattern);
if (this.SearchMode == SearchMode.First && this.Result.Count > 0)
{
return;
}
}
return;
}
/// <summary>
/// A help file is located in 3 steps
/// 1. If file itself contains a path itself, try to locate the file
/// from path. LocateFile will fail if this file doesn't exist.
/// 2. Try to locate the file from searchPaths. Normally the searchPaths will
/// contain the cmdlet/provider assembly directory if currently we are searching
/// help for cmdlet and providers.
/// 3. Try to locate the file in the default PowerShell installation directory.
/// </summary>
/// <param name="target"></param>
/// <param name="searchPaths"></param>
/// <returns></returns>
private static Collection<String> NormalizeSearchPaths(string target, Collection<String> searchPaths)
{
Collection<String> result = new Collection<String>();
// step 1: if target has path attached, directly locate
// file from there.
if (!String.IsNullOrEmpty(target) && !String.IsNullOrEmpty(Path.GetDirectoryName(target)))
{
string directory = Path.GetDirectoryName(target);
if (Directory.Exists(directory))
{
result.Add(Path.GetFullPath(directory));
}
//user specifically wanted to search in a particular directory
//so return..
return result;
}
// step 2: add directories specified in to search path.
if (searchPaths != null)
{
foreach (string directory in searchPaths)
{
if (!result.Contains(directory) && Directory.Exists(directory))
{
result.Add(directory);
}
}
}
// step 3: locate the file in the default PowerShell installation directory.
string defaultPSPath = GetMshDefaultInstallationPath();
if (defaultPSPath != null &&
!result.Contains(defaultPSPath) &&
Directory.Exists(defaultPSPath))
{
result.Add(defaultPSPath);
}
return result;
}
/// <summary>
/// Helper method which returns the default monad installation path based on ShellID
/// registry key.
/// </summary>
/// <returns>string representing path.</returns>
/// <remarks>
/// If ShellID is not defined or Path property is not defined returns null.
/// </remarks>
private static string GetMshDefaultInstallationPath()
{
string returnValue = CommandDiscovery.GetShellPathFromRegistry(Utils.DefaultPowerShellShellID);
if (returnValue != null)
{
returnValue = Path.GetDirectoryName(returnValue);
}
// returnValue can be null.
return returnValue;
}
#endregion
#region Static API's
/// <summary>
/// Search for files in default search paths.
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
internal static Collection<String> SearchFiles(string pattern)
{
return SearchFiles(pattern, new Collection<String>());
}
/// <summary>
/// Search for files in specified search paths.
/// </summary>
/// <param name="pattern"></param>
/// <param name="searchPaths"></param>
/// <returns></returns>
internal static Collection<String> SearchFiles(string pattern, Collection<String> searchPaths)
{
MUIFileSearcher searcher = new MUIFileSearcher(pattern, searchPaths);
return searcher.Result;
}
/// <summary>
/// Locate a file in default search paths
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
internal static string LocateFile(string file)
{
return LocateFile(file, new Collection<String>());
}
/// <summary>
/// Get the file in different search paths corresponding to current culture.
///
/// The file name to search is the filename part of path parameter. (Normally path
/// parameter should contain only the filename part. But it is possible for
/// RunspaceConfiguration to directly specify a hard coded path for help file there).
///
/// </summary>
/// <param name="file">This is the path to the file. If it has a path, we need to search under that path first</param>
/// <param name="searchPaths">Additional search paths</param>
/// <returns></returns>
internal static string LocateFile(string file, Collection<String> searchPaths)
{
MUIFileSearcher searcher = new MUIFileSearcher(file, searchPaths, SearchMode.First);
if (searcher.Result == null || searcher.Result.Count == 0)
return null;
return searcher.Result[0];
}
#endregion
}
/// <summary>
/// This enum defines different search mode for the MUIFileSearcher
/// </summary>
internal enum SearchMode
{
// return the first match
First,
// return all matches, with duplicates allowed
All,
// return all matches, with duplicates ignored
Unique
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CodeExporter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Serialization {
using System;
using System.Collections;
using System.IO;
using System.ComponentModel;
using System.Xml.Schema;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Globalization;
using System.Diagnostics;
using System.Security.Permissions;
/// <include file='doc\CodeExporter.uex' path='docs/doc[@for="CodeExporter"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
public abstract class CodeExporter {
Hashtable exportedMappings;
Hashtable exportedClasses; // TypeMapping -> CodeTypeDeclaration
CodeNamespace codeNamespace;
CodeCompileUnit codeCompileUnit;
bool rootExported;
TypeScope scope;
CodeAttributeDeclarationCollection includeMetadata = new CodeAttributeDeclarationCollection();
CodeGenerationOptions options;
CodeDomProvider codeProvider;
CodeAttributeDeclaration generatedCodeAttribute;
internal CodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable exportedMappings) {
if (codeNamespace != null)
CodeGenerator.ValidateIdentifiers(codeNamespace);
this.codeNamespace = codeNamespace;
if (codeCompileUnit != null) {
if (!codeCompileUnit.ReferencedAssemblies.Contains("System.dll"))
codeCompileUnit.ReferencedAssemblies.Add("System.dll");
if (!codeCompileUnit.ReferencedAssemblies.Contains("System.Xml.dll"))
codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll");
}
this.codeCompileUnit = codeCompileUnit;
this.options = options;
this.exportedMappings = exportedMappings;
this.codeProvider = codeProvider;
}
internal CodeCompileUnit CodeCompileUnit {
get { return codeCompileUnit; }
}
internal CodeNamespace CodeNamespace {
get {
if (codeNamespace == null)
codeNamespace = new CodeNamespace();
return codeNamespace;
}
}
internal CodeDomProvider CodeProvider {
get {
if (codeProvider == null)
codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
return codeProvider;
}
}
internal Hashtable ExportedClasses {
get {
if (exportedClasses == null)
exportedClasses = new Hashtable();
return exportedClasses;
}
}
internal Hashtable ExportedMappings {
get {
if (exportedMappings == null)
exportedMappings = new Hashtable();
return exportedMappings;
}
}
internal bool GenerateProperties {
get { return (options & CodeGenerationOptions.GenerateProperties) != 0; }
}
internal CodeAttributeDeclaration GeneratedCodeAttribute {
get {
if (generatedCodeAttribute == null) {
CodeAttributeDeclaration decl = new CodeAttributeDeclaration(typeof(GeneratedCodeAttribute).FullName);
Assembly a = Assembly.GetEntryAssembly();
if (a == null) {
a = Assembly.GetExecutingAssembly();
if (a == null) {
a = typeof(CodeExporter).Assembly;
}
}
AssemblyName assemblyName = a.GetName();
decl.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(assemblyName.Name)));
string version = GetProductVersion(a);
decl.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(version == null ? assemblyName.Version.ToString() : version)));
generatedCodeAttribute = decl;
}
return generatedCodeAttribute;
}
}
internal static CodeAttributeDeclaration FindAttributeDeclaration(Type type, CodeAttributeDeclarationCollection metadata) {
foreach (CodeAttributeDeclaration attribute in metadata) {
if (attribute.Name == type.FullName || attribute.Name == type.Name) {
return attribute;
}
}
return null;
}
private static string GetProductVersion(Assembly assembly) {
object[] attributes = assembly.GetCustomAttributes(true);
for ( int i = 0; i<attributes.Length; i++ ) {
if (attributes[i] is AssemblyInformationalVersionAttribute) {
AssemblyInformationalVersionAttribute version = (AssemblyInformationalVersionAttribute)attributes[i];
return version.InformationalVersion;
}
}
return null;
}
/// <include file='doc\XmlCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.IncludeMetadata"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CodeAttributeDeclarationCollection IncludeMetadata {
get { return includeMetadata; }
}
internal TypeScope Scope {
get { return scope; }
}
internal void CheckScope(TypeScope scope) {
if (this.scope == null) {
this.scope = scope;
}
else if (this.scope != scope) {
throw new InvalidOperationException(Res.GetString(Res.XmlMappingsScopeMismatch));
}
}
internal abstract void ExportDerivedStructs(StructMapping mapping);
internal abstract void EnsureTypesExported(Accessor[] accessors, string ns);
internal static void AddWarningComment(CodeCommentStatementCollection comments, string text) {
Debug.Assert(comments != null);
comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlCodegenWarningDetails, text), false));
}
internal void ExportRoot(StructMapping mapping, Type includeType) {
if (!rootExported) {
rootExported = true;
ExportDerivedStructs(mapping);
for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) {
if (!derived.ReferencedByElement && derived.IncludeInSchema && !derived.IsAnonymousType) {
CodeAttributeDeclaration include = new CodeAttributeDeclaration(includeType.FullName);
include.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(derived.TypeDesc.FullName)));
includeMetadata.Add(include);
}
}
Hashtable typesIncluded = new Hashtable();
foreach (TypeMapping m in Scope.TypeMappings) {
if (m is ArrayMapping) {
ArrayMapping arrayMapping = (ArrayMapping) m;
if (ShouldInclude(arrayMapping) && !typesIncluded.Contains(arrayMapping.TypeDesc.FullName)) {
CodeAttributeDeclaration include = new CodeAttributeDeclaration(includeType.FullName);
include.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(arrayMapping.TypeDesc.FullName)));
includeMetadata.Add(include);
typesIncluded.Add(arrayMapping.TypeDesc.FullName, string.Empty);
EnsureTypesExported(arrayMapping.Elements, arrayMapping.Namespace);
}
}
}
}
}
private static bool ShouldInclude(ArrayMapping arrayMapping) {
if (arrayMapping.ReferencedByElement)
return false;
if (arrayMapping.Next != null)
return false;
if (arrayMapping.Elements.Length == 1) {
TypeKind kind = arrayMapping.Elements[0].Mapping.TypeDesc.Kind;
if (kind == TypeKind.Node)
return false;
}
for (int i = 0; i < arrayMapping.Elements.Length; i++) {
if (arrayMapping.Elements[i].Name != arrayMapping.Elements[i].Mapping.DefaultElementName) {
// in the case we need custom attributes to serialize an array instance, we cannot include arrau mapping without explicit reference.
return false;
}
}
return true;
}
internal CodeTypeDeclaration ExportEnum(EnumMapping mapping, Type type) {
CodeTypeDeclaration codeClass = new CodeTypeDeclaration(mapping.TypeDesc.Name);
codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true));
codeClass.IsEnum = true;
if (mapping.IsFlags && mapping.Constants.Length > 31) {
codeClass.BaseTypes.Add(new CodeTypeReference(typeof(long)));
}
codeClass.TypeAttributes |= TypeAttributes.Public;
CodeNamespace.Types.Add(codeClass);
for (int i = 0; i < mapping.Constants.Length; i++) {
ExportConstant(codeClass, mapping.Constants[i], type, mapping.IsFlags, 1L << i);
}
if (mapping.IsFlags) {
// Add [FlagsAttribute]
CodeAttributeDeclaration flags = new CodeAttributeDeclaration(typeof(FlagsAttribute).FullName);
codeClass.CustomAttributes.Add(flags);
}
CodeGenerator.ValidateIdentifiers(codeClass);
return codeClass;
}
internal void AddTypeMetadata(CodeAttributeDeclarationCollection metadata, Type type, string defaultName, string name, string ns, bool includeInSchema) {
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(type.FullName);
if (name == null || name.Length == 0) {
attribute.Arguments.Add(new CodeAttributeArgument("AnonymousType", new CodePrimitiveExpression(true)));
}
else {
if (defaultName != name) {
attribute.Arguments.Add(new CodeAttributeArgument("TypeName", new CodePrimitiveExpression(name)));
}
}
if (ns != null && ns.Length != 0) {
attribute.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(ns)));
}
if (!includeInSchema) {
attribute.Arguments.Add(new CodeAttributeArgument("IncludeInSchema", new CodePrimitiveExpression(false)));
}
if (attribute.Arguments.Count > 0) {
metadata.Add(attribute);
}
}
internal static void AddIncludeMetadata(CodeAttributeDeclarationCollection metadata, StructMapping mapping, Type type) {
if (mapping.IsAnonymousType)
return;
for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) {
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(type.FullName);
attribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(derived.TypeDesc.FullName)));
metadata.Add(attribute);
AddIncludeMetadata(metadata, derived, type);
}
}
internal static void ExportConstant(CodeTypeDeclaration codeClass, ConstantMapping constant, Type type, bool init, long enumValue) {
CodeMemberField field = new CodeMemberField(typeof(int).FullName, constant.Name);
field.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true));
if (init)
field.InitExpression = new CodePrimitiveExpression(enumValue);
codeClass.Members.Add(field);
if (constant.XmlName != constant.Name) {
CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(type.FullName);
attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(constant.XmlName)));
field.CustomAttributes.Add(attribute);
}
}
internal static object PromoteType(Type type, object value) {
if (type == typeof(sbyte)) {
return ((IConvertible)value).ToInt16(null);
}
else if (type == typeof(UInt16)) {
return ((IConvertible)value).ToInt32(null);
}
else if (type == typeof(UInt32)) {
return ((IConvertible)value).ToInt64(null);
}
else if (type == typeof(UInt64)) {
return ((IConvertible)value).ToDecimal(null);
}
else {
return value;
}
}
internal CodeMemberProperty CreatePropertyDeclaration(CodeMemberField field, string name, string typeName) {
CodeMemberProperty prop = new CodeMemberProperty();
prop.Type = new CodeTypeReference(typeName);
prop.Name = name;
prop.Attributes = (prop.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
//add get
CodeMethodReturnStatement ret = new CodeMethodReturnStatement();
ret.Expression = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
prop.GetStatements.Add(ret);
CodeAssignStatement propertySet = new CodeAssignStatement();
CodeExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name);
CodeExpression right = new CodePropertySetValueReferenceExpression();
propertySet.Left = left;
propertySet.Right = right;
if (EnableDataBinding)
{
prop.SetStatements.Add(propertySet);
prop.SetStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), RaisePropertyChangedEventMethod.Name, new CodePrimitiveExpression(name)));
}
else
prop.SetStatements.Add(propertySet);
return prop;
}
internal static string MakeFieldName(string name) {
return CodeIdentifier.MakeCamel(name) + "Field";
}
internal void AddPropertyChangedNotifier(CodeTypeDeclaration codeClass)
{
if (EnableDataBinding && codeClass != null)
{
if (codeClass.BaseTypes.Count == 0)
{
codeClass.BaseTypes.Add(typeof(object));
}
codeClass.BaseTypes.Add(new CodeTypeReference(typeof(System.ComponentModel.INotifyPropertyChanged)));
codeClass.Members.Add(PropertyChangedEvent);
codeClass.Members.Add(RaisePropertyChangedEventMethod);
}
}
bool EnableDataBinding {
get { return (options & CodeGenerationOptions.EnableDataBinding) != 0; }
}
internal static CodeMemberMethod RaisePropertyChangedEventMethod
{
get
{
CodeMemberMethod raisePropertyChangedEventMethod = new CodeMemberMethod();
raisePropertyChangedEventMethod.Name = "RaisePropertyChanged";
raisePropertyChangedEventMethod.Attributes = MemberAttributes.Family | MemberAttributes.Final;
CodeArgumentReferenceExpression propertyName = new CodeArgumentReferenceExpression("propertyName");
raisePropertyChangedEventMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), propertyName.ParameterName));
CodeVariableReferenceExpression propertyChanged = new CodeVariableReferenceExpression("propertyChanged");
raisePropertyChangedEventMethod.Statements.Add(new CodeVariableDeclarationStatement(typeof(PropertyChangedEventHandler), propertyChanged.VariableName, new CodeEventReferenceExpression(new CodeThisReferenceExpression(), PropertyChangedEvent.Name)));
CodeConditionStatement ifStatement = new CodeConditionStatement(new CodeBinaryOperatorExpression(propertyChanged, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)));
raisePropertyChangedEventMethod.Statements.Add(ifStatement);
ifStatement.TrueStatements.Add(new CodeDelegateInvokeExpression(propertyChanged, new CodeThisReferenceExpression(), new CodeObjectCreateExpression(typeof(PropertyChangedEventArgs), propertyName)));
return raisePropertyChangedEventMethod;
}
}
internal static CodeMemberEvent PropertyChangedEvent
{
get
{
CodeMemberEvent propertyChangedEvent = new CodeMemberEvent();
propertyChangedEvent.Attributes = MemberAttributes.Public;
propertyChangedEvent.Name = "PropertyChanged";
propertyChangedEvent.Type = new CodeTypeReference(typeof(PropertyChangedEventHandler));
propertyChangedEvent.ImplementationTypes.Add(typeof(System.ComponentModel.INotifyPropertyChanged));
return propertyChangedEvent;
}
}
}
}
| |
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Sample.WebActors.Actors.Auction
{
using System;
using Stact;
using Stact.Actors;
using Stact.Channels;
using Stact.Fibers;
/// <summary>
/// A model representation of an auction, of which each auction running in a system would have
/// an instance of this class to manage the operations.
///
/// Some interesting points in the design so far.
///
/// Channels work, particularly for commands sent to the actor (Bid, Ask)
///
/// Responses are absolutely ugly, having to be part of the command message sent to the actor
/// There has to be a better way to handle this
///
/// Current thought is the creation of a "Mailbox" concept, whereby any type of message can be
/// sent to the mailbox, and the mailbox will ensure proper delivery of messages to the appropriate channels
///
/// At the same time, a form of reservation that could be created and packaged with a message (including something
/// similar to a MessageId or TransactionId, wrapped inside a Future() object) would support an easier notion of
/// binding a continuation to the receive of a response message.
///
/// This mailbox concept could be wrapped around an actor (or part of the api itself) to allow typed sends to the actor without
/// knowing the specific input channel at the time of send
///
/// An actor repository, or something similar to that, would provide location services or something to deal with the
/// connection of actors. For instance, if a search is performed to find auctions for boats, the response would include a
/// list of actors, one for each auction. It may be that the query is sent to an actor, and a list of actors is returned
/// instead. Not sure here, but clearly a way to map a message/guid to an instance is important.
///
/// It may just be the KeyedChannel that I created, whereas a message is sent to a keyed channel, which then
/// delivers it to the actor method itself.
/// </summary>
public class AuctionActor :
Actor
{
private readonly decimal _openingBid;
private readonly Scheduler _scheduler;
private decimal _bidIncrement;
private Mailbox<AuctionCompleted> _bidderCompleted;
private Mailbox<Outbid> _bidderOutbid;
private DateTime _expiresAt;
private Fiber _fiber;
private decimal _highBid;
private Actor _highBidder;
private Actor _seller;
private ChannelAdapter _input;
private ChannelConnection _subscriptions;
public AuctionActor(Fiber fiber, Scheduler scheduler, DateTime expiresAt, decimal openingBid, decimal bidIncrement)
{
_fiber = fiber;
_scheduler = scheduler;
_expiresAt = expiresAt;
_openingBid = openingBid;
_bidIncrement = bidIncrement;
_highBid = openingBid - bidIncrement;
_input = new ChannelAdapter();
_subscriptions = _input.Connect(x =>
{
x.Consume<Bid>()
.Using(m => ReceiveBid(m));
x.Consume<Ask>()
.Using(m => ReceiveAsk(m));
});
scheduler.Schedule(expiresAt.ToUniversalTime() - SystemUtil.UtcNow, _fiber, EndAuction);
}
private Channel<Ask> AskChannel { get; set; }
private Channel<Bid> BidChannel { get; set; }
public void Send<T>(T message)
{
_input.Send(message);
}
public void Send<T>(T message, RequestResponseChannel replyTo)
{
_input.Send(message);
}
private void ReceiveAsk(Ask message)
{
message.Sender.Send(new Status
{
ExpiresAt = _expiresAt,
Asked = _highBid,
});
}
private void EndAuction()
{
if (_highBid >= _openingBid)
{
var completed = new AuctionCompleted
{
HighestBid = _highBid
};
_bidderCompleted.Send(completed);
}
}
private void ReceiveBid(Bid bid)
{
if (SystemUtil.UtcNow >= _expiresAt)
{
bid.Bidder.Send(new AuctionOver());
return;
}
if (bid.Amount < _highBid + _bidIncrement)
{
bid.Bidder.Send(new Outbid
{
Asked = _highBid
});
return;
}
if (_highBid >= _openingBid)
{
_bidderOutbid.Send(new Outbid
{
Asked = bid.Amount,
});
}
_highBid = bid.Amount;
_highBidder = bid.Bidder;
}
}
public abstract class AuctionMessage
{
}
public class Bid :
AuctionMessage
{
public decimal Amount { get; set; }
public Actor Bidder { get; set; }
}
public class Ask :
AuctionMessage
{
public Actor Sender { get; set; }
}
public abstract class AuctionResponse
{
}
public class Status :
AuctionResponse
{
public decimal Asked { get; set; }
public DateTime ExpiresAt { get; set; }
}
public class Accepted :
AuctionResponse
{
}
public class Outbid :
AuctionResponse
{
public decimal Asked { get; set; }
}
public class AuctionCompleted :
AuctionResponse
{
public decimal HighestBid { get; set; }
}
public class AuctionFailed :
AuctionResponse
{
}
public class AuctionOver :
AuctionResponse
{
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Mvc.JQuery.DataTables.Reflection;
namespace Mvc.JQuery.DataTables
{
static class TypeFilters
{
private static readonly Func<string, Type, object> ParseValue =
(input, t) => t.GetTypeInfo().IsEnum ? Enum.Parse(t, input) : Convert.ChangeType(input, t);
internal static string FilterMethod(string q, List<object> parametersForLinqQuery, Type type)
{
Func<string, string, string> makeClause = (method, query) =>
{
parametersForLinqQuery.Add(ParseValue(query, type));
var indexOfParameter = parametersForLinqQuery.Count - 1;
return string.Format("{0}(@{1})", method, indexOfParameter);
};
if (q.StartsWith("^"))
{
if (q.EndsWith("$"))
{
parametersForLinqQuery.Add(ParseValue(q.Substring(1, q.Length - 2), type));
var indexOfParameter = parametersForLinqQuery.Count - 1;
return string.Format("Equals((object)@{0})", indexOfParameter);
}
return makeClause("StartsWith", q.Substring(1));
}
else
{
if (q.EndsWith("$"))
{
return makeClause("EndsWith", q.Substring(0, q.Length - 1));
}
return makeClause("Contains", q);
}
}
public static string NumericFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query.StartsWith("^")) query = query.TrimStart('^');
if (query.EndsWith("$")) query = query.TrimEnd('$');
if (query == "~") return string.Empty;
if (query.Contains("~"))
{
var parts = query.Split('~');
var clause = null as string;
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[0]));
clause = string.Format("{0} >= @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException)
{
}
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, parts[1]));
if (clause != null) clause += " and ";
clause += string.Format("{0} <= @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException)
{
}
return clause ?? "true";
}
else
{
try
{
parametersForLinqQuery.Add(ChangeType(propertyInfo, query));
return string.Format("{0} == @{1}", columnname, parametersForLinqQuery.Count - 1);
}
catch (FormatException)
{
}
return null;
}
}
private static object ChangeType(DataTablesPropertyInfo propertyInfo, string query)
{
if (propertyInfo.PropertyInfo.PropertyType.GetTypeInfo().IsGenericType && propertyInfo.Type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
Type u = Nullable.GetUnderlyingType(propertyInfo.Type);
return Convert.ChangeType(query, u);
}
else
{
return Convert.ChangeType(query, propertyInfo.Type);
}
}
public static string DateTimeOffsetFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query == "~") return string.Empty;
var filterString = null as string;
if (query.Contains("~"))
{
var parts = query.Split('~');
DateTimeOffset start, end;
if (DateTimeOffset.TryParse(parts[0] ?? "", out start))
{
filterString = columnname + " >= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(start);
}
if (DateTimeOffset.TryParse(parts[1] ?? "", out end))
{
filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(end);
}
return filterString ?? "";
}
else
{
DateTimeOffset dateTime;
if (DateTimeOffset.TryParse(query, out dateTime))
{
if (dateTime.Date == dateTime)
{
dateTime = dateTime.ToUniversalTime();
parametersForLinqQuery.Add(dateTime);
parametersForLinqQuery.Add(dateTime.AddDays(1));
filterString = string.Format("{0} >= @{1} and {0} < @{2}", columnname, parametersForLinqQuery.Count - 2, parametersForLinqQuery.Count - 1);
}
else
{
dateTime = dateTime.ToUniversalTime();
filterString = string.Format("{0} == @" + parametersForLinqQuery.Count, columnname);
parametersForLinqQuery.Add(dateTime);
}
}
return filterString;
}
}
public static string DateTimeFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query == "~") return string.Empty;
var filterString = null as string;
if (query.Contains("~"))
{
var parts = query.Split('~');
DateTime start, end;
if (DateTime.TryParse(parts[0] ?? "", out start))
{
filterString = columnname + " >= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(start);
}
if (DateTime.TryParse(parts[1] ?? "", out end))
{
filterString = (filterString == null ? null : filterString + " and ") + columnname + " <= @" + parametersForLinqQuery.Count;
parametersForLinqQuery.Add(end);
}
return filterString ?? "";
}
else
{
DateTime dateTime;
if (DateTime.TryParse(query, out dateTime))
{
if (dateTime.Date == dateTime)
{
dateTime = dateTime.ToUniversalTime();
parametersForLinqQuery.Add(dateTime);
parametersForLinqQuery.Add(dateTime.AddDays(1));
filterString = string.Format("({0} >= @{1} and {0} < @{2})", columnname, parametersForLinqQuery.Count - 2, parametersForLinqQuery.Count - 1);
}
else
{
dateTime = dateTime.ToUniversalTime();
filterString = string.Format("{0} == @" + parametersForLinqQuery.Count, columnname);
parametersForLinqQuery.Add(dateTime);
}
}
return filterString;
}
}
public static string BoolFilter(string query, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (query != null)
query = query.TrimStart('^').TrimEnd('$');
var lowerCaseQuery = query.ToLowerInvariant();
if (lowerCaseQuery == "false" || lowerCaseQuery == "true")
{
if (query.ToLower() == "true") return columnname + " == true";
return columnname + " == false";
}
if (propertyInfo.Type == typeof(bool?))
{
if (lowerCaseQuery == "null") return columnname + " == null";
}
return null;
}
public static string StringFilter(string q, string columnname, DataTablesPropertyInfo columntype, List<object> parametersforlinqquery)
{
if (q == ".*") return "";
if (q.StartsWith("^"))
{
if (q.EndsWith("$"))
{
parametersforlinqquery.Add(q.Substring(1, q.Length - 2));
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
return string.Format("{0} == {1}", columnname, parameterArg);
}
else
{
parametersforlinqquery.Add(q.Substring(1));
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
return string.Format("({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1})))", columnname, parameterArg);
}
}
else
{
parametersforlinqquery.Add(q);
var parameterArg = "@" + (parametersforlinqquery.Count - 1);
//return string.Format("{0} == {1}", columnname, parameterArg);
return
string.Format(
"({0} != null && {0} != \"\" && ({0} == {1} || {0}.StartsWith({1}) || {0}.Contains({1})))",
columnname, parameterArg);
}
}
public static string EnumFilter(string q, string columnname, DataTablesPropertyInfo propertyInfo, List<object> parametersForLinqQuery)
{
if (q.StartsWith("^")) q = q.Substring(1);
if (q.EndsWith("$")) q = q.Substring(0, q.Length - 1);
parametersForLinqQuery.Add(ParseValue(q, propertyInfo.Type));
return columnname + " == @" + (parametersForLinqQuery.Count - 1);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Microsoft.Rest.Generator.Utilities
{
/// <summary>
/// Provides useful extension methods to simplify common coding tasks.
/// </summary>
public static class Extensions
{
/// <summary>
/// Maps an action with side effects over a sequence.
/// </summary>
/// <param name='sequence'>The sequence to map over.</param>
/// <param name='action'>The action to map.</param>
/// <typeparam name='T'>Type of elements in the sequence.</typeparam>
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
if (sequence == null)
{
throw new ArgumentNullException("sequence");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
foreach (T element in sequence)
{
action(element);
}
}
/// <summary>
/// Returns a collection of the descendant elements for this collection.
/// </summary>
/// <typeparam name='T'>Type of elements in the sequence.</typeparam>
/// <param name="items">Child collection</param>
/// <param name="childSelector">Child selector</param>
/// <returns>List of all items and descendants of each item</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design.")]
public static IEnumerable<T> Descendants<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> childSelector)
{
foreach (var item in items)
{
foreach (var childResult in childSelector(item).Descendants(childSelector))
yield return childResult;
yield return item;
}
}
/// <summary>
/// Determines whether a sequence is empty.
/// </summary>
/// <typeparam name='T'>Type of elements in the sequence.</typeparam>
/// <param name='sequence'>The sequence.</param>
/// <returns>True if the sequence is empty, false otherwise.</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> sequence)
{
if (sequence == null ||
!sequence.Any())
{
return true;
}
return false;
}
/// <summary>
/// Word wrap a string of text to a given width.
/// </summary>
/// <param name='text'>The text to word wrap.</param>
/// <param name='width'>Width available to wrap.</param>
/// <returns>Lines of word wrapped text.</returns>
public static IEnumerable<string> WordWrap(this string text, int width)
{
Debug.Assert(text != null, "text should not be null.");
int start = 0; // Start of the current line
int end = 0; // End of the current line
char last = ' '; // Last character processed
// Walk the entire string, processing line by line
for (int i = 0; i < text.Length; i++)
{
// Support newlines inside the comment text.
if (text[i] == '\n')
{
yield return text.Substring(start, i - start + 1).Trim();
start = i + 1;
end = start;
last = ' ';
continue;
}
// If our current line is longer than the desired wrap width,
// we'll stop the line here
if (i - start >= width && start != end)
{
// Yield the current line
yield return text.Substring(start, end - start + 1).Trim();
// Set things up for the next line
start = end + 1;
end = start;
last = ' ';
}
// If the last character was a space, mark that spot as a
// candidate for a potential line break
if (!char.IsWhiteSpace(last) && char.IsWhiteSpace(text[i]))
{
end = i - 1;
}
last = text[i];
}
// Don't forget to include the last line of text
if (start < text.Length)
{
yield return text.Substring(start, text.Length - start).Trim();
}
}
/// <summary>
/// Performs shallow copy of properties from source into destination.
/// </summary>
/// <typeparam name="TU">Destination type</typeparam>
/// <typeparam name="TV">Source type</typeparam>
/// <param name="destination">Destination object.</param>
/// <param name="source">Source object.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "U", Justification = "Common naming for generics.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "V", Justification = "Common naming for generics.")]
public static void LoadFrom<TU, TV>(this TU destination, TV source)
where TU : class
where TV : class
{
if (destination == null)
{
throw new ArgumentNullException("destination");
}
if (source == null)
{
throw new ArgumentNullException("source");
}
var propertyNames = typeof(TU).GetProperties().Select(p => p.Name);
foreach (var propertyName in propertyNames)
{
var destinationProperty = typeof(TU).GetBaseProperty(propertyName);
var sourceProperty = typeof(TV).GetBaseProperty(propertyName);
if (destinationProperty != null &&
sourceProperty != null &&
sourceProperty.PropertyType == destinationProperty.PropertyType &&
sourceProperty.SetMethod != null)
{
destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
}
}
}
private static PropertyInfo GetBaseProperty(this Type type, string propertyName)
{
if (type != null)
{
PropertyInfo propertyInfo = type.GetProperty(propertyName);
if (propertyInfo != null)
{
if (propertyInfo.SetMethod != null)
{
return propertyInfo;
}
if (type.BaseType != null)
{
return type.BaseType.GetBaseProperty(propertyName);
}
}
}
return null;
}
/// <summary>
/// Converts the specified string to a camel cased string.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The camel case string.</returns>
public static string ToCamelCase(this string value)
{
return CodeNamer.CamelCase(value);
}
/// <summary>
/// Converts the specified string to a pascal cased string.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The pascal case string.</returns>
public static string ToPascalCase(this string value)
{
return CodeNamer.PascalCase(value);
}
/// <summary>
/// Escape reserved characters in xml comments with their escaped representations
/// </summary>
/// <param name="comment">The xml comment to escape</param>
/// <returns>The text appropriately escaped for inclusing in an xml comment</returns>
public static string EscapeXmlComment(this string comment)
{
if (comment == null)
{
return null;
}
return new StringBuilder(comment)
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">").ToString();
}
}
}
| |
//
// DaapSource.cs
//
// Authors:
// Alexander Hixon <hixon.alexander@mediati.org>
//
// Copyright (C) 2008 Alexander Hixon
//
// 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 Mono.Unix;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Library;
using Banshee.Sources;
using Banshee.ServiceStack;
using DAAP = Daap;
namespace Banshee.Daap
{
public class DaapSource : PrimarySource, IDurationAggregator, IUnmapableSource, IImportSource
{
private DAAP.Service service;
private DAAP.Client client;
private DAAP.Database database;
private bool connected = false;
public DAAP.Database Database {
get { return database; }
}
private bool is_activating;
public DaapSource (DAAP.Service service) : base (Catalog.GetString ("Music Share"), service.Name,
(service.Address.ToString () + service.Port).Replace (":", "").Replace (".", ""), 300)
{
this.service = service;
Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Disconnect"));
Properties.SetString ("UnmapSourceActionIconName", "gtk-disconnect");
SupportsPlaylists = false;
SavedCount = 0;
UpdateIcon ();
AfterInitialized ();
}
private void UpdateIcon ()
{
if (service != null && !service.IsProtected) {
Properties.SetStringList ("Icon.Name", "computer", "network-server");
} else {
Properties.SetStringList ("Icon.Name", "system-lock-screen", "computer", "network-server");
}
}
public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
if (track.PrimarySource == this && track.Uri.Scheme.StartsWith ("http")) {
foreach (double percent in database.DownloadTrack ((int)track.ExternalId, track.MimeType, uri.AbsolutePath)) {
job.DetailedProgress = percent;
}
}
}
public override void Activate ()
{
if (client != null || is_activating) {
return;
}
ClearErrorView ();
is_activating = true;
base.Activate ();
SetStatus (String.Format (Catalog.GetString ("Connecting to {0}"), service.Name), false);
ThreadAssist.Spawn (delegate {
try {
client = new DAAP.Client (service);
client.Updated += OnClientUpdated;
if (client.AuthenticationMethod == DAAP.AuthenticationMethod.None) {
client.Login ();
} else {
ThreadAssist.ProxyToMain (PromptLogin);
}
} catch(Exception e) {
ThreadAssist.ProxyToMain (delegate {
ShowErrorView (DaapErrorType.BrokenAuthentication);
});
Hyena.Log.Exception (e);
}
is_activating = false;
});
}
private void ShowErrorView (DaapErrorType error_type)
{
PurgeTracks ();
Reload ();
client = null;
DaapErrorView error_view = new DaapErrorView (this, error_type);
error_view.Show ();
Properties.Set<Banshee.Sources.Gui.ISourceContents> ("Nereid.SourceContents", error_view);
HideStatus ();
}
private void ClearErrorView ()
{
Properties.Remove ("Nereid.SourceContents");
}
internal bool Disconnect (bool logout)
{
// Stop currently playing track if its from us.
try {
if (ServiceManager.PlayerEngine.CurrentState == Banshee.MediaEngine.PlayerState.Playing) {
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null && track.PrimarySource == this) {
ServiceManager.PlayerEngine.Close ();
}
}
} catch {}
connected = false;
// Remove tracks associated with this source, since we don't want
// them after we unmap - we'll refetch.
PurgeTracks ();
if (client != null) {
if (logout) {
client.Logout ();
}
client.Dispose ();
client = null;
database = null;
}
if (database != null) {
try {
DaapService.ProxyServer.UnregisterDatabase (database);
} catch {}
database.TrackAdded -= OnDatabaseTrackAdded;
database.TrackRemoved -= OnDatabaseTrackRemoved;
database = null;
}
List<Source> children = new List<Source> (Children);
foreach (Source child in children) {
if (child is Banshee.Sources.IUnmapableSource) {
(child as Banshee.Sources.IUnmapableSource).Unmap ();
}
}
ClearChildSources ();
return true;
}
public override void Dispose ()
{
Disconnect (true);
base.Dispose ();
}
private void PromptLogin ()
{
SetStatus (Catalog.GetString ("Logging in to {0}."), false);
DaapLoginDialog dialog = new DaapLoginDialog (client.Name,
client.AuthenticationMethod == DAAP.AuthenticationMethod.UserAndPassword);
if (dialog.Run () == (int) Gtk.ResponseType.Ok) {
AuthenticatedLogin (dialog.Username, dialog.Password);
} else {
ShowErrorView (DaapErrorType.UserDisconnect);
}
dialog.Destroy ();
}
private void AuthenticatedLogin (string username, string password)
{
ThreadAssist.Spawn (delegate {
try {
client.Login (username, password);
} catch (DAAP.AuthenticationException) {
ThreadAssist.ProxyToMain (delegate {
ShowErrorView (DaapErrorType.InvalidAuthentication);
});
}
});
}
private void OnClientUpdated (object o, EventArgs args)
{
try {
if (database == null && client.Databases.Count > 0) {
database = client.Databases[0];
DaapService.ProxyServer.RegisterDatabase (database);
database.TrackAdded += OnDatabaseTrackAdded;
database.TrackRemoved += OnDatabaseTrackRemoved;
SetStatus (String.Format (Catalog.GetPluralString (
"Loading {0} track", "Loading {0} tracks", database.TrackCount),
database.TrackCount), false
);
// Notify (eg reload the source before sync is done) at most 5 times
int notify_every = Math.Max (250, (database.Tracks.Count / 4));
notify_every -= notify_every % 250;
int count = 0;
DaapTrackInfo daap_track = null;
HyenaSqliteConnection conn = ServiceManager.DbConnection;
conn.BeginTransaction ();
foreach (DAAP.Track track in database.Tracks) {
daap_track = new DaapTrackInfo (track, this);
// Only notify once in a while because otherwise the source Reloading slows things way down
if (++count % notify_every == 0) {
conn.CommitTransaction ();
daap_track.Save (true);
conn.BeginTransaction ();
} else {
daap_track.Save (false);
}
}
conn.CommitTransaction ();
// Save the last track once more to trigger the NotifyTrackAdded
if (daap_track != null) {
daap_track.Save ();
}
SetStatus (Catalog.GetString ("Loading playlists"), false);
AddPlaylistSources ();
connected = true;
Reload ();
HideStatus ();
}
Name = client.Name;
UpdateIcon ();
OnUpdated ();
} catch (Exception e) {
Hyena.Log.Exception ("Caught exception while loading daap share", e);
ThreadAssist.ProxyToMain (delegate {
HideStatus ();
ShowErrorView (DaapErrorType.UserDisconnect);
});
}
}
private void AddPlaylistSources ()
{
foreach (DAAP.Playlist pl in database.Playlists) {
DaapPlaylistSource source = new DaapPlaylistSource (pl, this);
ThreadAssist.ProxyToMain (delegate {
if (source.Count == 0) {
source.Unmap ();
} else {
AddChildSource (source);
}
});
}
}
public void OnDatabaseTrackAdded (object o, DAAP.TrackArgs args)
{
DaapTrackInfo track = new DaapTrackInfo (args.Track, this);
track.Save ();
}
public void OnDatabaseTrackRemoved (object o, DAAP.TrackArgs args)
{
//RemoveTrack (
}
public override bool CanRemoveTracks {
get { return false; }
}
public override bool CanDeleteTracks {
get { return false; }
}
public override bool ConfirmRemoveTracks {
get { return false; }
}
public override bool HasEditableTrackProperties {
get { return false; }
}
public bool Unmap ()
{
// Disconnect and clear out our tracks and such.
Disconnect (true);
ShowErrorView (DaapErrorType.UserDisconnect);
return true;
}
public bool CanUnmap {
get { return connected; }
}
public bool ConfirmBeforeUnmap {
get { return false; }
}
public void Import ()
{
ServiceManager.SourceManager.MusicLibrary.MergeSourceInput (this, SourceMergeType.All);
}
public bool CanImport {
get { return connected; }
}
int IImportSource.SortOrder {
get { return 30; }
}
string IImportSource.ImportLabel {
get { return null; }
}
public string [] IconNames {
get { return Properties.GetStringList ("Icon.Name"); }
}
}
}
| |
//
// 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.Scheduler;
using Microsoft.WindowsAzure.Management.Scheduler.Models;
namespace Microsoft.WindowsAzure.Management.Scheduler
{
public static partial class JobCollectionOperationsExtensions
{
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Job Collection
/// operation.
/// </param>
/// <returns>
/// The Create Job Collection operation response.
/// </returns>
public static JobCollectionCreateResponse BeginCreating(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).BeginCreatingAsync(cloudServiceName, jobCollectionName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Job Collection
/// operation.
/// </param>
/// <returns>
/// The Create Job Collection operation response.
/// </returns>
public static Task<JobCollectionCreateResponse> BeginCreatingAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters)
{
return operations.BeginCreatingAsync(cloudServiceName, jobCollectionName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse BeginDeleting(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).BeginDeletingAsync(cloudServiceName, jobCollectionName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> BeginDeletingAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return operations.BeginDeletingAsync(cloudServiceName, jobCollectionName, CancellationToken.None);
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Job Collection
/// operation.
/// </param>
/// <returns>
/// The Update Job Collection operation response.
/// </returns>
public static JobCollectionUpdateResponse BeginUpdating(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).BeginUpdatingAsync(cloudServiceName, jobCollectionName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Job Collection
/// operation.
/// </param>
/// <returns>
/// The Update Job Collection operation response.
/// </returns>
public static Task<JobCollectionUpdateResponse> BeginUpdatingAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters)
{
return operations.BeginUpdatingAsync(cloudServiceName, jobCollectionName, parameters, CancellationToken.None);
}
/// <summary>
/// Determine if the JobCollection name is available to be used.
/// JobCollection names must be unique within a cloud-service.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. A name for the JobCollection. The name must be unique as
/// scoped within the CloudService. The name can be up to 100
/// characters in length.
/// </param>
/// <returns>
/// The Check Name Availability operation response.
/// </returns>
public static JobCollectionCheckNameAvailabilityResponse CheckNameAvailability(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).CheckNameAvailabilityAsync(cloudServiceName, jobCollectionName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Determine if the JobCollection name is available to be used.
/// JobCollection names must be unique within a cloud-service.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. A name for the JobCollection. The name must be unique as
/// scoped within the CloudService. The name can be up to 100
/// characters in length.
/// </param>
/// <returns>
/// The Check Name Availability operation response.
/// </returns>
public static Task<JobCollectionCheckNameAvailabilityResponse> CheckNameAvailabilityAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return operations.CheckNameAvailabilityAsync(cloudServiceName, jobCollectionName, CancellationToken.None);
}
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Job Collection
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static SchedulerOperationStatusResponse Create(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).CreateAsync(cloudServiceName, jobCollectionName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Job Collection
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<SchedulerOperationStatusResponse> CreateAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters)
{
return operations.CreateAsync(cloudServiceName, jobCollectionName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to delete.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static SchedulerOperationStatusResponse Delete(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).DeleteAsync(cloudServiceName, jobCollectionName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to delete.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<SchedulerOperationStatusResponse> DeleteAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return operations.DeleteAsync(cloudServiceName, jobCollectionName, CancellationToken.None);
}
/// <summary>
/// Retreive a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. Name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. Name of the job collection.
/// </param>
/// <returns>
/// The Get Job Collection operation response.
/// </returns>
public static JobCollectionGetResponse Get(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).GetAsync(cloudServiceName, jobCollectionName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retreive a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. Name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. Name of the job collection.
/// </param>
/// <returns>
/// The Get Job Collection operation response.
/// </returns>
public static Task<JobCollectionGetResponse> GetAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName)
{
return operations.GetAsync(cloudServiceName, jobCollectionName, CancellationToken.None);
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Job Collection
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static SchedulerOperationStatusResponse Update(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobCollectionOperations)s).UpdateAsync(cloudServiceName, jobCollectionName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations.
/// </param>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Job Collection
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<SchedulerOperationStatusResponse> UpdateAsync(this IJobCollectionOperations operations, string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters)
{
return operations.UpdateAsync(cloudServiceName, jobCollectionName, parameters, CancellationToken.None);
}
}
}
| |
// 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.Primitives;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// Defines the <see langword="abstract"/> base class for export providers, which provide
/// methods for retrieving <see cref="Export"/> objects.
/// </summary>
public abstract partial class ExportProvider
{
private static readonly Export[] EmptyExports = new Export[] { };
/// <summary>
/// Initializes a new instance of the <see cref="ExportProvider"/> class.
/// </summary>
protected ExportProvider()
{
}
/// <summary>
/// Occurs when the exports in the <see cref="ExportProvider"/> have changed.
/// </summary>
public event EventHandler<ExportsChangeEventArgs> ExportsChanged;
/// <summary>
/// Occurs when the exports in the <see cref="ExportProvider"/> are changing.
/// </summary>
public event EventHandler<ExportsChangeEventArgs> ExportsChanging;
/// <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"/> objects to get.
/// </param>
/// <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>
/// <exception cref="ArgumentNullException">
/// <paramref name="definition"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ExactlyOne"/> and
/// there are zero <see cref="Export"/> objects that match the conditions of the specified
/// <see cref="ImportDefinition"/>.
/// </para>
/// -or-
/// <para>
/// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ZeroOrOne"/> or
/// <see cref="ImportCardinality.ExactlyOne"/> and there are more than one <see cref="Export"/>
/// objects that match the conditions of the specified <see cref="ImportDefinition"/>.
/// </para>
/// </exception>
public IEnumerable<Export> GetExports(ImportDefinition definition)
{
return GetExports(definition, null);
}
/// <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"/> objects to get.
/// </param>
/// <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>
/// <exception cref="ArgumentNullException">
/// <paramref name="definition"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ImportCardinalityMismatchException">
/// <para>
/// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ExactlyOne"/> and
/// there are zero <see cref="Export"/> objects that match the conditions of the specified
/// <see cref="ImportDefinition"/>.
/// </para>
/// -or-
/// <para>
/// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ZeroOrOne"/> or
/// <see cref="ImportCardinality.ExactlyOne"/> and there are more than one <see cref="Export"/>
/// objects that match the conditions of the specified <see cref="ImportDefinition"/>.
/// </para>
/// </exception>
public IEnumerable<Export> GetExports(ImportDefinition definition, AtomicComposition atomicComposition)
{
Requires.NotNull(definition, nameof(definition));
Contract.Ensures(Contract.Result<IEnumerable<Export>>() != null);
IEnumerable<Export> exports;
ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports);
switch(result)
{
case ExportCardinalityCheckResult.Match:
return exports;
case ExportCardinalityCheckResult.NoExports:
throw new ImportCardinalityMismatchException(string.Format(CultureInfo.CurrentCulture, SR.CardinalityMismatch_NoExports, definition.ToString()));
default:
Assumes.IsTrue(result == ExportCardinalityCheckResult.TooManyExports);
throw new ImportCardinalityMismatchException(string.Format(CultureInfo.CurrentCulture, SR.CardinalityMismatch_TooManyExports, definition.ToString()));
}
}
/// <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"/> objects to get.
/// </param>
/// <param name="exports">
/// When this method returns, contains 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}"/>.
/// </param>
/// <returns>
/// <see langword="true"/> if <see cref="ImportDefinition.Cardinality"/> is
/// <see cref="ImportCardinality.ZeroOrOne"/> or <see cref="ImportCardinality.ZeroOrMore"/> and
/// there are zero <see cref="Export"/> objects that match the conditions of the specified
/// <see cref="ImportDefinition"/>. <see langword="true"/> if
/// <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ZeroOrOne"/> or
/// <see cref="ImportCardinality.ExactlyOne"/> and there is exactly one <see cref="Export"/>
/// that matches the conditions of the specified <see cref="ImportDefinition"/>; otherwise,
/// <see langword="false"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="definition"/> is <see langword="null"/>.
/// </exception>
public bool TryGetExports(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable<Export> exports)
{
Requires.NotNull(definition, nameof(definition));
exports = null;
ExportCardinalityCheckResult result = TryGetExportsCore(definition, atomicComposition, out exports);
return (result == ExportCardinalityCheckResult.Match);
}
/// <summary>
/// Returns all exports that match the constraint defined by the specified definition.
/// </summary>
/// <param name="definition">
/// The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="Export"/> objects to return.
/// </param>
/// <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">
/// Overriders of this method should not treat cardinality-related mismatches
/// as errors, and should not throw exceptions in those cases. For instance,
/// if <see cref="ImportDefinition.Cardinality"/> is <see cref="ImportCardinality.ExactlyOne"/>
/// and there are zero <see cref="Export"/> objects that match the conditions of the
/// specified <see cref="ImportDefinition"/>, an <see cref="IEnumerable{T}"/> should be returned.
/// </note>
/// </remarks>
protected abstract IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition);
/// <summary>
/// Raises the <see cref="ExportsChanged"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ExportsChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnExportsChanged(ExportsChangeEventArgs e)
{
EventHandler<ExportsChangeEventArgs> changedEvent = ExportsChanged;
if (changedEvent != null)
{
CompositionResult result = CompositionServices.TryFire(changedEvent, this, e);
result.ThrowOnErrors(e.AtomicComposition);
}
}
/// <summary>
/// Raises the <see cref="ExportsChanging"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ExportsChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnExportsChanging(ExportsChangeEventArgs e)
{
EventHandler<ExportsChangeEventArgs> changingEvent = ExportsChanging;
if (changingEvent != null)
{
CompositionResult result = CompositionServices.TryFire(changingEvent, this, e);
result.ThrowOnErrors(e.AtomicComposition);
}
}
private ExportCardinalityCheckResult TryGetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition, out IEnumerable<Export> exports)
{
Assumes.NotNull(definition);
exports = GetExportsCore(definition, atomicComposition);
var checkResult = ExportServices.CheckCardinality(definition, exports);
// Export providers treat >1 match as zero for cardinality 0-1 imports
// If this policy is moved we need to revisit the assumption that the
// ImportEngine made during previewing the only required imports to
// now also preview optional imports.
if (checkResult == ExportCardinalityCheckResult.TooManyExports &&
definition.Cardinality == ImportCardinality.ZeroOrOne)
{
checkResult = ExportCardinalityCheckResult.Match;
exports = null;
}
if (exports == null)
{
exports = EmptyExports;
}
return checkResult;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
/**
* <summary>Collection of predefined handlers for various system types.</summary>
*/
internal static class BinarySystemHandlers
{
/** Write handlers. */
private static readonly CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler> WriteHandlers =
new CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler>();
/** Read handlers. */
private static readonly IBinarySystemReader[] ReadHandlers = new IBinarySystemReader[255];
/** Type ids. */
private static readonly Dictionary<Type, byte> TypeIds = new Dictionary<Type, byte>
{
{typeof (bool), BinaryUtils.TypeBool},
{typeof (byte), BinaryUtils.TypeByte},
{typeof (sbyte), BinaryUtils.TypeByte},
{typeof (short), BinaryUtils.TypeShort},
{typeof (ushort), BinaryUtils.TypeShort},
{typeof (char), BinaryUtils.TypeChar},
{typeof (int), BinaryUtils.TypeInt},
{typeof (uint), BinaryUtils.TypeInt},
{typeof (long), BinaryUtils.TypeLong},
{typeof (ulong), BinaryUtils.TypeLong},
{typeof (float), BinaryUtils.TypeFloat},
{typeof (double), BinaryUtils.TypeDouble},
{typeof (string), BinaryUtils.TypeString},
{typeof (decimal), BinaryUtils.TypeDecimal},
{typeof (Guid), BinaryUtils.TypeGuid},
{typeof (Guid?), BinaryUtils.TypeGuid},
{typeof (ArrayList), BinaryUtils.TypeCollection},
{typeof (Hashtable), BinaryUtils.TypeDictionary},
{typeof (bool[]), BinaryUtils.TypeArrayBool},
{typeof (byte[]), BinaryUtils.TypeArrayByte},
{typeof (sbyte[]), BinaryUtils.TypeArrayByte},
{typeof (short[]), BinaryUtils.TypeArrayShort},
{typeof (ushort[]), BinaryUtils.TypeArrayShort},
{typeof (char[]), BinaryUtils.TypeArrayChar},
{typeof (int[]), BinaryUtils.TypeArrayInt},
{typeof (uint[]), BinaryUtils.TypeArrayInt},
{typeof (long[]), BinaryUtils.TypeArrayLong},
{typeof (ulong[]), BinaryUtils.TypeArrayLong},
{typeof (float[]), BinaryUtils.TypeArrayFloat},
{typeof (double[]), BinaryUtils.TypeArrayDouble},
{typeof (string[]), BinaryUtils.TypeArrayString},
{typeof (decimal?[]), BinaryUtils.TypeArrayDecimal},
{typeof (Guid?[]), BinaryUtils.TypeArrayGuid},
{typeof (object[]), BinaryUtils.TypeArray}
};
/// <summary>
/// Initializes the <see cref="BinarySystemHandlers"/> class.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability.")]
static BinarySystemHandlers()
{
// 1. Primitives.
ReadHandlers[BinaryUtils.TypeBool] = new BinarySystemReader<bool>(s => s.ReadBool());
ReadHandlers[BinaryUtils.TypeByte] = new BinarySystemReader<byte>(s => s.ReadByte());
ReadHandlers[BinaryUtils.TypeShort] = new BinarySystemReader<short>(s => s.ReadShort());
ReadHandlers[BinaryUtils.TypeChar] = new BinarySystemReader<char>(s => s.ReadChar());
ReadHandlers[BinaryUtils.TypeInt] = new BinarySystemReader<int>(s => s.ReadInt());
ReadHandlers[BinaryUtils.TypeLong] = new BinarySystemReader<long>(s => s.ReadLong());
ReadHandlers[BinaryUtils.TypeFloat] = new BinarySystemReader<float>(s => s.ReadFloat());
ReadHandlers[BinaryUtils.TypeDouble] = new BinarySystemReader<double>(s => s.ReadDouble());
ReadHandlers[BinaryUtils.TypeDecimal] = new BinarySystemReader<decimal?>(BinaryUtils.ReadDecimal);
// 2. Date.
ReadHandlers[BinaryUtils.TypeTimestamp] = new BinarySystemReader<DateTime?>(BinaryUtils.ReadTimestamp);
// 3. String.
ReadHandlers[BinaryUtils.TypeString] = new BinarySystemReader<string>(BinaryUtils.ReadString);
// 4. Guid.
ReadHandlers[BinaryUtils.TypeGuid] = new BinarySystemReader<Guid?>(s => BinaryUtils.ReadGuid(s));
// 5. Primitive arrays.
ReadHandlers[BinaryUtils.TypeArrayBool] = new BinarySystemReader<bool[]>(BinaryUtils.ReadBooleanArray);
ReadHandlers[BinaryUtils.TypeArrayByte] =
new BinarySystemDualReader<byte[], sbyte[]>(BinaryUtils.ReadByteArray, BinaryUtils.ReadSbyteArray);
ReadHandlers[BinaryUtils.TypeArrayShort] =
new BinarySystemDualReader<short[], ushort[]>(BinaryUtils.ReadShortArray,
BinaryUtils.ReadUshortArray);
ReadHandlers[BinaryUtils.TypeArrayChar] =
new BinarySystemReader<char[]>(BinaryUtils.ReadCharArray);
ReadHandlers[BinaryUtils.TypeArrayInt] =
new BinarySystemDualReader<int[], uint[]>(BinaryUtils.ReadIntArray, BinaryUtils.ReadUintArray);
ReadHandlers[BinaryUtils.TypeArrayLong] =
new BinarySystemDualReader<long[], ulong[]>(BinaryUtils.ReadLongArray,
BinaryUtils.ReadUlongArray);
ReadHandlers[BinaryUtils.TypeArrayFloat] =
new BinarySystemReader<float[]>(BinaryUtils.ReadFloatArray);
ReadHandlers[BinaryUtils.TypeArrayDouble] =
new BinarySystemReader<double[]>(BinaryUtils.ReadDoubleArray);
ReadHandlers[BinaryUtils.TypeArrayDecimal] =
new BinarySystemReader<decimal?[]>(BinaryUtils.ReadDecimalArray);
// 6. Date array.
ReadHandlers[BinaryUtils.TypeArrayTimestamp] =
new BinarySystemReader<DateTime?[]>(BinaryUtils.ReadTimestampArray);
// 7. String array.
ReadHandlers[BinaryUtils.TypeArrayString] = new BinarySystemTypedArrayReader<string>();
// 8. Guid array.
ReadHandlers[BinaryUtils.TypeArrayGuid] = new BinarySystemTypedArrayReader<Guid?>();
// 9. Array.
ReadHandlers[BinaryUtils.TypeArray] = new BinarySystemReader(ReadArray);
// 11. Arbitrary collection.
ReadHandlers[BinaryUtils.TypeCollection] = new BinarySystemReader(ReadCollection);
// 13. Arbitrary dictionary.
ReadHandlers[BinaryUtils.TypeDictionary] = new BinarySystemReader(ReadDictionary);
// 14. Enum.
ReadHandlers[BinaryUtils.TypeArrayEnum] = new BinarySystemReader(ReadEnumArray);
}
/// <summary>
/// Try getting write handler for type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static IBinarySystemWriteHandler GetWriteHandler(Type type)
{
return WriteHandlers.GetOrAdd(type, t =>
{
return FindWriteHandler(t);
});
}
/// <summary>
/// Find write handler for type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>
/// Write handler or NULL.
/// </returns>
private static IBinarySystemWriteHandler FindWriteHandler(Type type)
{
// 1. Well-known types.
if (type == typeof(string))
return new BinarySystemWriteHandler<string>(WriteString, false);
if (type == typeof(decimal))
return new BinarySystemWriteHandler<decimal>(WriteDecimal, false);
if (type == typeof(Guid))
return new BinarySystemWriteHandler<Guid>(WriteGuid, false);
if (type == typeof (BinaryObject))
return new BinarySystemWriteHandler<BinaryObject>(WriteBinary, false);
if (type == typeof (BinaryEnum))
return new BinarySystemWriteHandler<BinaryEnum>(WriteBinaryEnum, false);
if (type.IsEnum)
{
var underlyingType = Enum.GetUnderlyingType(type);
if (underlyingType == typeof(int))
return new BinarySystemWriteHandler<int>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(uint))
return new BinarySystemWriteHandler<uint>((w, i) => w.WriteEnum(unchecked((int) i), type), false);
if (underlyingType == typeof(byte))
return new BinarySystemWriteHandler<byte>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(sbyte))
return new BinarySystemWriteHandler<sbyte>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(short))
return new BinarySystemWriteHandler<short>((w, i) => w.WriteEnum(i, type), false);
if (underlyingType == typeof(ushort))
return new BinarySystemWriteHandler<ushort>((w, i) => w.WriteEnum(i, type), false);
return null; // Other enums, such as long and ulong, can't be expressed as int.
}
if (type == typeof(Ignite))
return new BinarySystemWriteHandler<object>(WriteIgnite, false);
// All types below can be written as handles.
if (type == typeof (ArrayList))
return new BinarySystemWriteHandler<ICollection>(WriteArrayList, true);
if (type == typeof (Hashtable))
return new BinarySystemWriteHandler<IDictionary>(WriteHashtable, true);
if (type.IsArray)
{
// We know how to write any array type.
Type elemType = type.GetElementType();
// Primitives.
if (elemType == typeof (bool))
return new BinarySystemWriteHandler<bool[]>(WriteBoolArray, true);
if (elemType == typeof(byte))
return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true);
if (elemType == typeof(short))
return new BinarySystemWriteHandler<short[]>(WriteShortArray, true);
if (elemType == typeof(char))
return new BinarySystemWriteHandler<char[]>(WriteCharArray, true);
if (elemType == typeof(int))
return new BinarySystemWriteHandler<int[]>(WriteIntArray, true);
if (elemType == typeof(long))
return new BinarySystemWriteHandler<long[]>(WriteLongArray, true);
if (elemType == typeof(float))
return new BinarySystemWriteHandler<float[]>(WriteFloatArray, true);
if (elemType == typeof(double))
return new BinarySystemWriteHandler<double[]>(WriteDoubleArray, true);
// Non-CLS primitives.
if (elemType == typeof(sbyte))
return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true);
if (elemType == typeof(ushort))
return new BinarySystemWriteHandler<short[]>(WriteShortArray, true);
if (elemType == typeof(uint))
return new BinarySystemWriteHandler<int[]>(WriteIntArray, true);
if (elemType == typeof(ulong))
return new BinarySystemWriteHandler<long[]>(WriteLongArray, true);
// Special types.
if (elemType == typeof (decimal?))
return new BinarySystemWriteHandler<decimal?[]>(WriteDecimalArray, true);
if (elemType == typeof(string))
return new BinarySystemWriteHandler<string[]>(WriteStringArray, true);
if (elemType == typeof(Guid?))
return new BinarySystemWriteHandler<Guid?[]>(WriteGuidArray, true);
// Enums.
if (IsIntEnum(elemType) || elemType == typeof(BinaryEnum))
return new BinarySystemWriteHandler<object>(WriteEnumArray, true);
// Object array.
return new BinarySystemWriteHandler<object>(WriteArray, true);
}
return null;
}
/// <summary>
/// Determines whether specified type is an enum which fits into Int32.
/// </summary>
private static bool IsIntEnum(Type type)
{
if (!type.IsEnum)
return false;
var underlyingType = Enum.GetUnderlyingType(type);
return underlyingType == typeof(int)
|| underlyingType == typeof(short)
|| underlyingType == typeof(ushort)
|| underlyingType == typeof(byte)
|| underlyingType == typeof(sbyte);
}
/// <summary>
/// Find write handler for type.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Write handler or NULL.</returns>
public static byte GetTypeId(Type type)
{
byte res;
if (TypeIds.TryGetValue(type, out res))
return res;
if (type.IsEnum)
return BinaryUtils.TypeEnum;
if (type.IsArray && type.GetElementType().IsEnum)
return BinaryUtils.TypeArrayEnum;
return BinaryUtils.TypeObject;
}
/// <summary>
/// Reads an object of predefined type.
/// </summary>
public static bool TryReadSystemType<T>(byte typeId, BinaryReader ctx, out T res)
{
var handler = ReadHandlers[typeId];
if (handler == null)
{
res = default(T);
return false;
}
res = handler.Read<T>(ctx);
return true;
}
/// <summary>
/// Write decimal.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteDecimal(BinaryWriter ctx, decimal obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeDecimal);
BinaryUtils.WriteDecimal(obj, ctx.Stream);
}
/// <summary>
/// Write string.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Object.</param>
private static void WriteString(BinaryWriter ctx, string obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeString);
BinaryUtils.WriteString(obj, ctx.Stream);
}
/// <summary>
/// Write Guid.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteGuid(BinaryWriter ctx, Guid obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeGuid);
BinaryUtils.WriteGuid(obj, ctx.Stream);
}
/// <summary>
/// Write boolaen array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteBoolArray(BinaryWriter ctx, bool[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayBool);
BinaryUtils.WriteBooleanArray(obj, ctx.Stream);
}
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteByteArray(BinaryWriter ctx, byte[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte);
BinaryUtils.WriteByteArray(obj, ctx.Stream);
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteShortArray(BinaryWriter ctx, short[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort);
BinaryUtils.WriteShortArray(obj, ctx.Stream);
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteCharArray(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayChar);
BinaryUtils.WriteCharArray((char[])obj, ctx.Stream);
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteIntArray(BinaryWriter ctx, int[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt);
BinaryUtils.WriteIntArray(obj, ctx.Stream);
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteLongArray(BinaryWriter ctx, long[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong);
BinaryUtils.WriteLongArray(obj, ctx.Stream);
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteFloatArray(BinaryWriter ctx, float[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayFloat);
BinaryUtils.WriteFloatArray(obj, ctx.Stream);
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteDoubleArray(BinaryWriter ctx, double[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayDouble);
BinaryUtils.WriteDoubleArray(obj, ctx.Stream);
}
/// <summary>
/// Write decimal array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteDecimalArray(BinaryWriter ctx, decimal?[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayDecimal);
BinaryUtils.WriteDecimalArray(obj, ctx.Stream);
}
/// <summary>
/// Write string array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteStringArray(BinaryWriter ctx, string[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayString);
BinaryUtils.WriteStringArray(obj, ctx.Stream);
}
/// <summary>
/// Write nullable GUID array.
/// </summary>
/// <param name="ctx">Context.</param>
/// <param name="obj">Value.</param>
private static void WriteGuidArray(BinaryWriter ctx, Guid?[] obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayGuid);
BinaryUtils.WriteGuidArray(obj, ctx.Stream);
}
/// <summary>
/// Writes the enum array.
/// </summary>
private static void WriteEnumArray(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArrayEnum);
BinaryUtils.WriteArray((Array) obj, ctx);
}
/// <summary>
/// Writes the array.
/// </summary>
private static void WriteArray(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeArray);
BinaryUtils.WriteArray((Array) obj, ctx);
}
/**
* <summary>Write ArrayList.</summary>
*/
private static void WriteArrayList(BinaryWriter ctx, ICollection obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeCollection);
BinaryUtils.WriteCollection(obj, ctx, BinaryUtils.CollectionArrayList);
}
/**
* <summary>Write Hashtable.</summary>
*/
private static void WriteHashtable(BinaryWriter ctx, IDictionary obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeDictionary);
BinaryUtils.WriteDictionary(obj, ctx, BinaryUtils.MapHashMap);
}
/**
* <summary>Write binary object.</summary>
*/
private static void WriteBinary(BinaryWriter ctx, BinaryObject obj)
{
ctx.Stream.WriteByte(BinaryUtils.TypeBinary);
BinaryUtils.WriteBinary(ctx.Stream, obj);
}
/// <summary>
/// Write enum.
/// </summary>
private static void WriteBinaryEnum(BinaryWriter ctx, BinaryEnum obj)
{
var binEnum = obj;
ctx.Stream.WriteByte(BinaryUtils.TypeEnum);
ctx.WriteInt(binEnum.TypeId);
ctx.WriteInt(binEnum.EnumValue);
}
/**
* <summary>Read enum array.</summary>
*/
private static object ReadEnumArray(BinaryReader ctx, Type type)
{
var elemType = type.GetElementType() ?? typeof(object);
return BinaryUtils.ReadTypedArray(ctx, true, elemType);
}
/// <summary>
/// Reads the array.
/// </summary>
private static object ReadArray(BinaryReader ctx, Type type)
{
var elemType = type.GetElementType();
if (elemType == null)
{
if (ctx.Mode == BinaryMode.ForceBinary)
{
// Forced binary mode: use object because primitives are not represented as IBinaryObject.
elemType = typeof(object);
}
else
{
// Infer element type from typeId.
var typeId = ctx.ReadInt();
if (typeId != BinaryUtils.ObjTypeId)
{
elemType = ctx.Marshaller.GetDescriptor(true, typeId, true).Type;
}
return BinaryUtils.ReadTypedArray(ctx, false, elemType ?? typeof(object));
}
}
// Element type is known, no need to check typeId.
// In case of incompatible types we'll get exception either way.
return BinaryUtils.ReadTypedArray(ctx, true, elemType);
}
/**
* <summary>Read collection.</summary>
*/
private static object ReadCollection(BinaryReader ctx, Type type)
{
return BinaryUtils.ReadCollection(ctx, null, null);
}
/**
* <summary>Read dictionary.</summary>
*/
private static object ReadDictionary(BinaryReader ctx, Type type)
{
return BinaryUtils.ReadDictionary(ctx, null);
}
/// <summary>
/// Write Ignite.
/// </summary>
private static void WriteIgnite(BinaryWriter ctx, object obj)
{
ctx.Stream.WriteByte(BinaryUtils.HdrNull);
}
/**
* <summary>Read delegate.</summary>
* <param name="ctx">Read context.</param>
* <param name="type">Type.</param>
*/
private delegate object BinarySystemReadDelegate(BinaryReader ctx, Type type);
/// <summary>
/// System type reader.
/// </summary>
private interface IBinarySystemReader
{
/// <summary>
/// Reads a value of specified type from reader.
/// </summary>
T Read<T>(BinaryReader ctx);
}
/// <summary>
/// System type generic reader.
/// </summary>
private interface IBinarySystemReader<out T>
{
/// <summary>
/// Reads a value of specified type from reader.
/// </summary>
T Read(BinaryReader ctx);
}
/// <summary>
/// Default reader with boxing.
/// </summary>
private class BinarySystemReader : IBinarySystemReader
{
/** */
private readonly BinarySystemReadDelegate _readDelegate;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemReader"/> class.
/// </summary>
/// <param name="readDelegate">The read delegate.</param>
public BinarySystemReader(BinarySystemReadDelegate readDelegate)
{
Debug.Assert(readDelegate != null);
_readDelegate = readDelegate;
}
/** <inheritdoc /> */
public T Read<T>(BinaryReader ctx)
{
return (T)_readDelegate(ctx, typeof(T));
}
}
/// <summary>
/// Reader without boxing.
/// </summary>
private class BinarySystemReader<T> : IBinarySystemReader
{
/** */
private readonly Func<IBinaryStream, T> _readDelegate;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemReader{T}"/> class.
/// </summary>
/// <param name="readDelegate">The read delegate.</param>
public BinarySystemReader(Func<IBinaryStream, T> readDelegate)
{
Debug.Assert(readDelegate != null);
_readDelegate = readDelegate;
}
/** <inheritdoc /> */
public TResult Read<TResult>(BinaryReader ctx)
{
return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream));
}
}
/// <summary>
/// Reader without boxing.
/// </summary>
private class BinarySystemTypedArrayReader<T> : IBinarySystemReader
{
public TResult Read<TResult>(BinaryReader ctx)
{
return TypeCaster<TResult>.Cast(BinaryUtils.ReadArray<T>(ctx, false));
}
}
/// <summary>
/// Reader with selection based on requested type.
/// </summary>
private class BinarySystemDualReader<T1, T2> : IBinarySystemReader, IBinarySystemReader<T2>
{
/** */
private readonly Func<IBinaryStream, T1> _readDelegate1;
/** */
private readonly Func<IBinaryStream, T2> _readDelegate2;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemDualReader{T1,T2}"/> class.
/// </summary>
/// <param name="readDelegate1">The read delegate1.</param>
/// <param name="readDelegate2">The read delegate2.</param>
public BinarySystemDualReader(Func<IBinaryStream, T1> readDelegate1, Func<IBinaryStream, T2> readDelegate2)
{
Debug.Assert(readDelegate1 != null);
Debug.Assert(readDelegate2 != null);
_readDelegate1 = readDelegate1;
_readDelegate2 = readDelegate2;
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
T2 IBinarySystemReader<T2>.Read(BinaryReader ctx)
{
return _readDelegate2(ctx.Stream);
}
/** <inheritdoc /> */
public T Read<T>(BinaryReader ctx)
{
// Can't use "as" because of variance.
// For example, IBinarySystemReader<byte[]> can be cast to IBinarySystemReader<sbyte[]>, which
// will cause incorrect behavior.
if (typeof (T) == typeof (T2))
return ((IBinarySystemReader<T>) this).Read(ctx);
return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream));
}
}
}
/// <summary>
/// Write delegate + handles flag.
/// </summary>
internal interface IBinarySystemWriteHandler
{
/// <summary>
/// Gets a value indicating whether this handler supports handles.
/// </summary>
bool SupportsHandles { get; }
/// <summary>
/// Writes object to a specified writer.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="obj">The object.</param>
void Write<T>(BinaryWriter writer, T obj);
}
/// <summary>
/// Write delegate + handles flag.
/// </summary>
internal class BinarySystemWriteHandler<T1> : IBinarySystemWriteHandler
{
/** */
private readonly Action<BinaryWriter, T1> _writeAction;
/** */
private readonly bool _supportsHandles;
/// <summary>
/// Initializes a new instance of the <see cref="BinarySystemWriteHandler{T1}" /> class.
/// </summary>
/// <param name="writeAction">The write action.</param>
/// <param name="supportsHandles">Handles flag.</param>
public BinarySystemWriteHandler(Action<BinaryWriter, T1> writeAction, bool supportsHandles)
{
Debug.Assert(writeAction != null);
_writeAction = writeAction;
_supportsHandles = supportsHandles;
}
/** <inheritdoc /> */
public void Write<T>(BinaryWriter writer, T obj)
{
_writeAction(writer, TypeCaster<T1>.Cast(obj));
}
/** <inheritdoc /> */
public bool SupportsHandles
{
get { return _supportsHandles; }
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using Content.Shared.Damage;
using Content.Shared.Damage.Prototypes;
using Content.Shared.FixedPoint;
using NUnit.Framework;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Prototypes;
namespace Content.IntegrationTests.Tests.Damageable
{
[TestFixture]
[TestOf(typeof(DamageableComponent))]
[TestOf(typeof(DamageableSystem))]
public sealed class DamageableTest : ContentIntegrationTest
{
private const string Prototypes = @"
# Define some damage groups
- type: damageType
id: TestDamage1
- type: damageType
id: TestDamage2a
- type: damageType
id: TestDamage2b
- type: damageType
id: TestDamage3a
- type: damageType
id: TestDamage3b
- type: damageType
id: TestDamage3c
# Define damage Groups with 1,2,3 damage types
- type: damageGroup
id: TestGroup1
damageTypes:
- TestDamage1
- type: damageGroup
id: TestGroup2
damageTypes:
- TestDamage2a
- TestDamage2b
- type: damageGroup
id: TestGroup3
damageTypes:
- TestDamage3a
- TestDamage3b
- TestDamage3c
# This container should not support TestDamage1 or TestDamage2b
- type: damageContainer
id: testDamageContainer
supportedGroups:
- TestGroup3
supportedTypes:
- TestDamage2a
- type: entity
id: TestDamageableEntityId
name: TestDamageableEntityId
components:
- type: Damageable
damageContainer: testDamageContainer
";
// public bool & function to determine whether dealing damage resulted in actual damage change
public bool DamageChanged = false;
public void DamageChangedListener(EntityUid _, DamageableComponent comp, DamageChangedEvent args)
{
DamageChanged = true;
}
[Test]
public async Task TestDamageableComponents()
{
var server = StartServerDummyTicker(new ServerContentIntegrationOption
{
ExtraPrototypes = Prototypes
});
await server.WaitIdleAsync();
var sEntityManager = server.ResolveDependency<IEntityManager>();
var sMapManager = server.ResolveDependency<IMapManager>();
var sPrototypeManager = server.ResolveDependency<IPrototypeManager>();
var sEntitySystemManager = server.ResolveDependency<IEntitySystemManager>();
sEntityManager.EventBus.SubscribeLocalEvent<DamageableComponent, DamageChangedEvent>(DamageChangedListener);
EntityUid sDamageableEntity = default;
DamageableComponent sDamageableComponent = null;
DamageableSystem sDamageableSystem = null;
DamageGroupPrototype group1 = default!;
DamageGroupPrototype group2 = default!;
DamageGroupPrototype group3 = default!;
DamageTypePrototype type1 = default!;
DamageTypePrototype type2a = default!;
DamageTypePrototype type2b = default!;
DamageTypePrototype type3a = default!;
DamageTypePrototype type3b = default!;
DamageTypePrototype type3c = default!;
FixedPoint2 typeDamage, groupDamage;
await server.WaitPost(() =>
{
var mapId = sMapManager.NextMapId();
var coordinates = new MapCoordinates(0, 0, mapId);
sMapManager.CreateMap(mapId);
sDamageableEntity = sEntityManager.SpawnEntity("TestDamageableEntityId", coordinates);
sDamageableComponent = IoCManager.Resolve<IEntityManager>().GetComponent<DamageableComponent>(sDamageableEntity);
sDamageableSystem = sEntitySystemManager.GetEntitySystem<DamageableSystem>();
group1 = sPrototypeManager.Index<DamageGroupPrototype>("TestGroup1");
group2 = sPrototypeManager.Index<DamageGroupPrototype>("TestGroup2");
group3 = sPrototypeManager.Index<DamageGroupPrototype>("TestGroup3");
type1 = sPrototypeManager.Index<DamageTypePrototype>("TestDamage1");
type2a = sPrototypeManager.Index<DamageTypePrototype>("TestDamage2a");
type2b = sPrototypeManager.Index<DamageTypePrototype>("TestDamage2b");
type3a = sPrototypeManager.Index<DamageTypePrototype>("TestDamage3a");
type3b = sPrototypeManager.Index<DamageTypePrototype>("TestDamage3b");
type3c = sPrototypeManager.Index<DamageTypePrototype>("TestDamage3c");
});
await server.WaitRunTicks(5);
await server.WaitAssertion(() =>
{
var uid = (EntityUid) sDamageableEntity;
// Check that the correct types are supported.
Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type1.ID), Is.False);
Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type2a.ID), Is.True);
Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type2b.ID), Is.False);
Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3a.ID), Is.True);
Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3b.ID), Is.True);
Assert.That(sDamageableComponent.Damage.DamageDict.ContainsKey(type3c.ID), Is.True);
// Check that damage is evenly distributed over a group if its a nice multiple
var types = group3.DamageTypes;
var damageToDeal = FixedPoint2.New(types.Count() * 5);
DamageSpecifier damage = new(group3, damageToDeal);
sDamageableSystem.TryChangeDamage(uid, damage, true);
Assert.That(DamageChanged);
DamageChanged = false;
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(damageToDeal));
Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(damageToDeal));
foreach (var type in types)
{
Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage));
Assert.That(typeDamage, Is.EqualTo(damageToDeal / types.Count()));
}
// Heal
sDamageableSystem.TryChangeDamage(uid, -damage);
Assert.That(DamageChanged);
DamageChanged = false;
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero));
Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(FixedPoint2.Zero));
foreach (var type in types)
{
Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage));
Assert.That(typeDamage, Is.EqualTo(FixedPoint2.Zero));
}
// Check that damage works properly if it is NOT perfectly divisible among group members
types = group3.DamageTypes;
damageToDeal = FixedPoint2.New(types.Count() * 5 - 1);
damage = new DamageSpecifier(group3, damageToDeal);
sDamageableSystem.TryChangeDamage(uid, damage, true);
Assert.That(DamageChanged);
DamageChanged = false;
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(damageToDeal));
Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(damageToDeal));
Assert.That(sDamageableComponent.Damage.DamageDict[type3a.ID], Is.EqualTo(damageToDeal / types.Count()));
Assert.That(sDamageableComponent.Damage.DamageDict[type3b.ID], Is.EqualTo(damageToDeal / types.Count()));
// last one will get 0.01 less, since its not perfectly divisble by 3
Assert.That(sDamageableComponent.Damage.DamageDict[type3c.ID], Is.EqualTo(damageToDeal / types.Count() - 0.01));
// Heal
sDamageableSystem.TryChangeDamage(uid, -damage);
Assert.That(DamageChanged);
DamageChanged = false;
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero));
Assert.That(sDamageableComponent.DamagePerGroup[group3.ID], Is.EqualTo(FixedPoint2.Zero));
foreach (var type in types)
{
Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type, out typeDamage));
Assert.That(typeDamage, Is.EqualTo(FixedPoint2.Zero));
}
// Test that unsupported groups return false when setting/getting damage (and don't change damage)
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero));
damage = new DamageSpecifier(group1, FixedPoint2.New(10)) + new DamageSpecifier(type2b, FixedPoint2.New(10));
sDamageableSystem.TryChangeDamage(uid, damage, true);
Assert.That(DamageChanged, Is.False);
Assert.That(sDamageableComponent.DamagePerGroup.TryGetValue(group1.ID, out groupDamage), Is.False);
Assert.That(sDamageableComponent.Damage.DamageDict.TryGetValue(type1.ID, out typeDamage), Is.False);
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero));
// Test SetAll function
sDamageableSystem.SetAllDamage(sDamageableComponent, 10);
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.New(10 * sDamageableComponent.Damage.DamageDict.Count())));
sDamageableSystem.SetAllDamage(sDamageableComponent, 0);
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero));
// Test 'wasted' healing
sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(type3a, 5));
sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(type3b, 7));
sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(group3, -11));
Assert.That(sDamageableComponent.Damage.DamageDict[type3a.ID], Is.EqualTo(FixedPoint2.New(1.33)));
Assert.That(sDamageableComponent.Damage.DamageDict[type3b.ID], Is.EqualTo(FixedPoint2.New(3.33)));
Assert.That(sDamageableComponent.Damage.DamageDict[type3c.ID], Is.EqualTo(FixedPoint2.New(0)));
// Test Over-Healing
sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(group3, FixedPoint2.New(-100)));
Assert.That(DamageChanged);
DamageChanged = false;
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero));
// Test that if no health change occurred, returns false
sDamageableSystem.TryChangeDamage(uid, new DamageSpecifier(group3, -100));
Assert.That(DamageChanged, Is.False);
Assert.That(sDamageableComponent.TotalDamage, Is.EqualTo(FixedPoint2.Zero));
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Vim25Api;
using AppUtil;
using System.Collections;
namespace History
{
///<summary>
///This sample displays the performance measurements of specified counter of specified
///Host System (if available) for duration of last 20 minutes(by default, if not specified)
///at the console.
///</summary>
///<param name="hostname">Required: Name of the host from which to obtain counter data.</param>
///<param name="interval">Required: Sampling interval.</param>
///<param name="starttime">Optional: Number of minutes to go back in time to start retrieving
///metrics. Default is 20.</param>
///<param name="duration">Optional: Duration for which to retrieve metrics. Default is 20.
///Cannot be larger value than starttime.</param>
///<param name="groupname">Required: cpu, memory</param>
///<param name="countername">Required: Usage, Overhead.</param>
///<remarks>
///--url [webserviceurl]
///--username [username] --password [password] --hostname [name of the history server]
///--groupname cpu --countername usage
///To display historical values for the specified group and counter:
///run.bat com.vmware.samples.performance.History --url [webserviceurl]
///--username [username] --password [password] --hostname [] --groupname cpu --countername usage
///</remarks>
///
class History
{
private static AppUtil.AppUtil cb = null;
Hashtable _pci = new Hashtable();
/// <summary>
///Displays the performance measurements of specified counter of specified
///Host System.
/// </summary>
private void displayHistory() {
ManagedObjectReference hostmor
= cb.getServiceUtil().GetDecendentMoRef(null,"HostSystem",
cb.get_option("hostname"));
if(hostmor == null) {
Console.WriteLine("Host " + cb.get_option("hostname") + " not found");
return;
}
ManagedObjectReference pmRef
= cb.getConnection()._sic.perfManager;
CounterInfo(pmRef);
//Retrieves all configured historical archive sampling intervals.
PerfInterval[] intervals
= (PerfInterval[])cb.getServiceUtil().GetDynamicProperty(pmRef,
"historicalInterval");
int interval = (int.Parse(cb.get_option("interval")));
Boolean valid = checkInterval(intervals,interval);
if(!valid) {
Console.WriteLine("Invalid inerval, Specify one from above");
return;
}
PerfCounterInfo pci = getCounterInfo(cb.get_option("groupname"),
cb.get_option("countername"),
PerfSummaryType.average);
if(pci == null) {
Console.WriteLine("Incorrect Group Name and Counters Specified");
return;
}
//specifies the query parameters to be used while retrieving statistics.
//e.g. entity, maxsample etc.
PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.entity = hostmor;
qSpec.maxSample= 10;
qSpec.maxSampleSpecified = true;
PerfQuerySpec[] qSpecs = new PerfQuerySpec[] {qSpec};
DateTime sTime;
DateTime eTime = cb.getConnection()._service.CurrentTime(
cb.getConnection().ServiceRef);
double duration = double.Parse(cb.get_option("duration"));
double startTime = double.Parse(cb.get_option("starttime"));
sTime = eTime.AddMinutes(-duration);
Console.WriteLine("Start Time " + sTime.TimeOfDay.ToString());
Console.WriteLine("End Time " + eTime.TimeOfDay.ToString());
Console.WriteLine();
//Retrieves the query available of performance metric for a host.
PerfMetricId[] aMetrics
= cb.getConnection()._service.QueryAvailablePerfMetric(pmRef,
hostmor,
sTime,
true,
eTime,
true,
interval,true);
PerfMetricId ourCounter = null;
for(int index=0; index<aMetrics.Length; ++index) {
if(aMetrics[index].counterId == pci.key) {
ourCounter = aMetrics[index];
break;
}
}
if(ourCounter == null) {
Console.WriteLine("No data on Host to collect. "
+"Has it been running for at least "
+ cb.get_option("duration") + " minutes");
} else {
qSpec = new PerfQuerySpec();
qSpec.entity= hostmor;
qSpec.startTime =sTime;
qSpec.endTime= eTime;
qSpec.metricId = (new PerfMetricId[]{ourCounter});
qSpec.intervalId =interval;
qSpec.intervalIdSpecified = true;
qSpec.startTimeSpecified = true;
qSpec.endTimeSpecified = true;
qSpecs = new PerfQuerySpec[] {qSpec};
//
PerfEntityMetricBase[] samples
= cb.getConnection()._service.QueryPerf(pmRef, qSpecs);
if(samples != null) {
displayValues(samples, pci, ourCounter, interval);
}
else {
Console.WriteLine("No Smaples Found");
}
}
}
/// <summary>
/// Validate the input interval.
/// </summary>
/// <param name="intervals"></param>
/// <param name="interval"></param>
/// <returns>returns a Boolean type value true or false</returns>
private Boolean checkInterval(PerfInterval [] intervals, int interval) {
Boolean flag = false;
for(int i=0; i<intervals.Length; ++i) {
PerfInterval pi = intervals[i];
if(pi.samplingPeriod == interval){
flag = true;
break;
}
}
if(!flag){
Console.WriteLine("Available summary collection intervals");
Console.WriteLine("Period\tLength\tName");
for(int i=0; i<intervals.Length; ++i) {
PerfInterval pi = intervals[i];
Console.WriteLine(pi.samplingPeriod + "\t"
+pi.length+"\t"+pi.name);
}
Console.WriteLine();
}
return flag;
}
///<summary>
///Retrieves counter information.
///</summary>
///<param name="pmRef"></param>
private void CounterInfo(ManagedObjectReference pmRef) {
PerfCounterInfo[] cInfos
= (PerfCounterInfo[])cb.getServiceUtil().GetDynamicProperty(pmRef,
"perfCounter");
for(int i=0; i<cInfos.Length; ++i) {
PerfCounterInfo cInfo = cInfos[i];
String group = cInfo.groupInfo.key;
Hashtable nameMap = null;
if(!_pci.ContainsKey(group)) {
nameMap = new Hashtable();
_pci.Add(group, nameMap);
} else {
nameMap = (Hashtable)_pci[group];
}
String name = cInfo.nameInfo.key;
ArrayList counters = null;
if(!nameMap.ContainsKey(name)) {
counters = new ArrayList();
nameMap.Add(name, counters);
} else {
counters = (ArrayList)nameMap[name];
}
counters.Add(cInfo);
}
}
///<summary>
///Retrieves counter information for given groupname and countername.
///</summary>
///<param name="groupName"></param>
///<param name="counterName"></param>
///<returns>Returns the arraylist of counter name.</returns>
private ArrayList getCounterInfos(String groupName, String counterName) {
Hashtable nameMap = (Hashtable)_pci[groupName];
if(nameMap != null) {
ArrayList ret = (ArrayList)nameMap[counterName];
if(ret != null) {
return new ArrayList(ret);
}
}
return null;
}
/// <summary>
/// Retrieves counter information for given groupname and countername and rolluptype.
/// </summary>
/// <param name="groupName"></param>
/// <param name="counterName"></param>
/// <param name="rollupType"></param>
/// <returns>
/// Returns the object type with the current information of performance counter
/// </returns>
private PerfCounterInfo getCounterInfo(String groupName,
String counterName,
PerfSummaryType rollupType) {
ArrayList counters = getCounterInfos(groupName, counterName);
if(counters != null) {
for(IEnumerator i=counters.GetEnumerator(); i.MoveNext();) {
PerfCounterInfo pci = (PerfCounterInfo)i.Current;
if(rollupType == null || rollupType.Equals(pci.rollupType)) {
return pci;
}
}
}
return null;
}
/// <summary>
/// Displays the values timestamps, intervals, instances etc.
/// </summary>
/// <param name="values"></param>
/// <param name="pci"></param>
/// <param name="pmid"></param>
/// <param name="interval"></param>
private void displayValues(PerfEntityMetricBase[] values,
PerfCounterInfo pci,
PerfMetricId pmid,
int interval) {
for(int i=0; i<values.Length; ++i) {
PerfMetricSeries[] vals = ((PerfEntityMetric)values[i]).value;
PerfSampleInfo[] infos = ((PerfEntityMetric)values[i]).sampleInfo;
if (infos == null || infos.Length == 0) {
Console.WriteLine("No Samples available. Continuing.");
continue;
}
Console.WriteLine("Sample time range: "
+ infos[0].timestamp.TimeOfDay.ToString() + " - " +
infos[infos.Length-1].timestamp.TimeOfDay.ToString() +
", read every "+interval+" seconds");
for(int vi=0; vi<vals.Length; ++vi) {
if(pci != null) {
if(pci.key != vals[vi].id.counterId)
continue;
Console.WriteLine(pci.nameInfo.summary
+ " - Instance: " + pmid.instance);
}
if(vals[vi].GetType().Name.Equals("PerfMetricIntSeries")){
PerfMetricIntSeries val = (PerfMetricIntSeries)vals[vi];
long[] longs = val.value;
for(int k=0; k<longs.Length; ++k) {
Console.WriteLine(longs[k] + " ");
}
Console.WriteLine();
}
}
}
}
/// <summary>
/// Validate if the start time is greater than duration.
/// </summary>
/// <returns>Returns the Boolean value true or false.</returns>
private Boolean customValidation() {
int duration = int.Parse(cb.get_option("duration"));
int starttime = int.Parse(cb.get_option("starttime"));
if(duration > starttime) {
Console.WriteLine("Duration must be less than startime");
return false;
}
else {
return true;
}
}
/// <summary>
/// This method is used to add application specific user options
/// </summary>
///<returns> Array of OptionSpec containing the details of application
/// specific user options
///</returns>
///
private static OptionSpec[] constructOptions() {
OptionSpec [] useroptions = new OptionSpec[6];
useroptions[0] = new OptionSpec("hostname","String",1
,"Name of the host system"
,null);
useroptions[1] = new OptionSpec("interval","String",1,
"Sampling Interval",
null);
useroptions[2] = new OptionSpec("starttime","String",0
,"In minutes, to specfiy what's start time " +
"from which samples needs to be collected"
,"20");
useroptions[3] = new OptionSpec("duration","String",0,
"Duration for which samples needs to be taken",
"20");
useroptions[4] = new OptionSpec("groupname","String",1
,"cpu, mem etc..."
,null);
useroptions[5] = new OptionSpec("countername","String",1,
"usage, overhead etc...",
null);
return useroptions;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(String[] args) {
History obj = new History();
cb = AppUtil.AppUtil.initialize("History",
History.constructOptions()
,args);
Boolean valid = obj.customValidation();
if(valid) {
cb.connect();
obj.displayHistory();
cb.disConnect();
Console.WriteLine("Press any key to exit");
Console.Read();
}
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using NLog.Config;
using NLog.Filters;
using Xunit.Extensions;
namespace NLog.UnitTests.Layouts
{
using NLog.LayoutRenderers;
using NLog.LayoutRenderers.Wrappers;
using NLog.Layouts;
using NLog.Targets;
using System;
using Xunit;
using static Config.TargetConfigurationTests;
public class SimpleLayoutParserTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
SimpleLayout l = "${message}";
Assert.Single(l.Renderers);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
}
[Fact]
public void UnclosedTest()
{
new SimpleLayout("${message");
}
[Fact]
public void SingleParamTest()
{
SimpleLayout l = "${mdc:item=AAA}";
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA", mdc.Item);
}
[Fact]
public void ValueWithColonTest()
{
SimpleLayout l = "${mdc:item=AAA\\:}";
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA:", mdc.Item);
}
[Fact]
public void ValueWithBracketTest()
{
SimpleLayout l = "${mdc:item=AAA\\}\\:}";
Assert.Equal("${mdc:item=AAA\\}\\:}", l.Text);
//Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA}:", mdc.Item);
}
[Fact]
public void DefaultValueTest()
{
SimpleLayout l = "${mdc:BBB}";
//Assert.Equal(1, l.Renderers.Count);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("BBB", mdc.Item);
}
[Fact]
public void DefaultValueWithBracketTest()
{
SimpleLayout l = "${mdc:AAA\\}\\:}";
Assert.Equal("${mdc:AAA\\}\\:}", l.Text);
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA}:", mdc.Item);
}
[Fact]
public void DefaultValueWithOtherParametersTest()
{
SimpleLayout l = "${exception:message,type:separator=x}";
Assert.Single(l.Renderers);
ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer;
Assert.NotNull(elr);
Assert.Equal("message,type", elr.Format);
Assert.Equal("x", elr.Separator);
}
[Fact]
public void EmptyValueTest()
{
SimpleLayout l = "${mdc:item=}";
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("", mdc.Item);
}
[Fact]
public void NestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${ndc:topFrames=3:separator=x}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void DoubleNestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${rot13:inner=${ndc:topFrames=3:separator=x}}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:inner=${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void DoubleNestedLayoutWithDefaultLayoutParametersTest()
{
SimpleLayout l = "${rot13:${rot13:${ndc:topFrames=3:separator=x}}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void AmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10}";
Assert.Single(l.Renderers);
var pad = l.Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void MissingLayoutRendererTest()
{
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = "${rot13:${foobar}}";
});
}
[Fact]
public void DoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:uppercase=true:padding=10}";
Assert.Single(l.Renderers);
var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void ReverseDoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10:uppercase=true}";
Assert.Single(l.Renderers);
var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void EscapeTest()
{
AssertEscapeRoundTrips(string.Empty);
AssertEscapeRoundTrips("hello ${${}} world!");
AssertEscapeRoundTrips("hello $");
AssertEscapeRoundTrips("hello ${");
AssertEscapeRoundTrips("hello $${{");
AssertEscapeRoundTrips("hello ${message}");
AssertEscapeRoundTrips("hello ${${level}}");
AssertEscapeRoundTrips("hello ${${level}${message}}");
}
[Fact]
public void EvaluateTest()
{
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Level = LogLevel.Warn;
Assert.Equal("Warn", SimpleLayout.Evaluate("${level}", logEventInfo));
}
[Fact]
public void EvaluateTest2()
{
Assert.Equal("Off", SimpleLayout.Evaluate("${level}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${message}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${logger}"));
}
private static void AssertEscapeRoundTrips(string originalString)
{
string escapedString = SimpleLayout.Escape(originalString);
SimpleLayout l = escapedString;
string renderedString = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal(originalString, renderedString);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV1()
{
MappedDiagnosticsContext.Clear();
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\u003a(?<digits>\\d)[ -]*)\u007b8,16\u007d(?=(\\d[ -]*)\u007b3\u007d(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.True(l1.Regex);
Assert.True(l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV2()
{
MappedDiagnosticsContext.Clear();
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\:(?<digits>\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.True(l1.Regex);
Assert.True(l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void InnerLayoutWithColonTest_with_workaround()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test${literal:text=\:} Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithColonTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\: Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashSingleTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest2()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal(@"Test{Hello\}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_reverse()
{
SimpleLayout l = @"${when:Inner=Test{Hello\}:when=1 == 1}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_no_escape()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest()
{
SimpleLayout l = @"${when:when=1 == 1:inner=Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Log_{#}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_need_escape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=L\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("L}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape2()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape3()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape4()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape5()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{a\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{a}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_and_layoutrender()
{
SimpleLayout l = @"${when:when=1 == 1:inner=${counter}/Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("1/Log_{#}.log", l.Render(le));
}
[Fact]
public void InvalidLayoutWillParsePartly()
{
SimpleLayout l = @"aaa ${iDontExist} bbb";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("aaa bbb", l.Render(le));
}
[Fact]
public void InvalidLayoutWillThrowIfExceptionThrowingIsOn()
{
LogManager.ThrowConfigExceptions = true;
Assert.Throws<ArgumentException>(() =>
{
SimpleLayout l = @"aaa ${iDontExist} bbb";
});
}
/// <summary>
///
/// Test layout with Genernic List type. - is the seperator
///
///
/// </summary>
/// <remarks>
/// comma escape is backtick (cannot use backslash due to layout parse)
/// </remarks>
/// <param name="input"></param>
/// <param name="propname"></param>
/// <param name="expected"></param>
[Theory]
[InlineData("2,3,4", "numbers", "2-3-4")]
[InlineData("a,b,c", "Strings", "a-b-c")]
[InlineData("a,b,c", "Objects", "a-b-c")]
[InlineData("a,,b,c", "Strings", "a--b-c")]
[InlineData("a`b,c", "Strings", "a`b-c")]
[InlineData("a\'b,c", "Strings", "a'b-c")]
[InlineData("'a,b',c", "Strings", "a,b-c")]
[InlineData("2.0,3.0,4.0", "doubles", "2-3-4")]
[InlineData("2.1,3.2,4.3", "doubles", "2.1-3.2-4.3")]
[InlineData("Ignore,Neutral,Ignore", "enums", "Ignore-Neutral-Ignore")]
[InlineData("ASCII,ISO-8859-1, UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
[InlineData("ASCII,ISO-8859-1,UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
[InlineData("Value1,Value3,Value2", "FlagEnums", "Value1-Value3-Value2")]
[InlineData("2,3,4", "IEnumerableNumber", "2-3-4")]
[InlineData("2,3,4", "IListNumber", "2-3-4")]
[InlineData("2,3,4", "HashsetNumber", "2-3-4")]
#if !NET3_5
[InlineData("2,3,4", "ISetNumber", "2-3-4")]
#endif
[InlineData("a,b,c", "IEnumerableString", "a-b-c")]
[InlineData("a,b,c", "IListString", "a-b-c")]
[InlineData("a,b,c", "HashSetString", "a-b-c")]
#if !NET3_5
[InlineData("a,b,c", "ISetString", "a-b-c")]
#endif
public void LayoutWithListParamTest(string input, string propname, string expected)
{
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
var actual = l.Render(le);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("2,,3,4", "numbers")]
[InlineData("a,bc", "numbers")]
[InlineData("value1,value10", "FlagEnums")]
public void LayoutWithListParamTest_incorrect(string input, string propname)
{
//note flags enum already supported
//can;t convert empty to int
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";
});
}
private class LayoutRendererWithListParam : LayoutRenderer
{
public List<double> Doubles { get; set; }
public List<FilterResult> Enums { get; set; }
public List<MyFlagsEnum> FlagEnums { get; set; }
public List<int> Numbers { get; set; }
public List<string> Strings { get; set; }
public List<object> Objects { get; set; }
public List<Encoding> Encodings { get; set; }
public IEnumerable<string> IEnumerableString { get; set; }
public IEnumerable<int> IEnumerableNumber { get; set; }
public IList<string> IListString { get; set; }
public IList<int> IListNumber { get; set; }
#if !NET3_5
public ISet<string> ISetString { get; set; }
public ISet<int> ISetNumber { get; set; }
#endif
public HashSet<int> HashSetNumber { get; set; }
public HashSet<string> HashSetString { get; set; }
/// <summary>
/// Renders the specified environmental information and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
Append(builder, Strings);
AppendFormattable(builder, Numbers);
AppendFormattable(builder, Enums);
AppendFormattable(builder, FlagEnums);
AppendFormattable(builder, Doubles);
Append(builder, Encodings?.Select(e => e.BodyName).ToList());
Append(builder, Objects);
Append(builder, IEnumerableString);
AppendFormattable(builder, IEnumerableNumber);
Append(builder, IListString);
AppendFormattable(builder, IListNumber);
#if !NET3_5
Append(builder, ISetString);
AppendFormattable(builder, ISetNumber);
#endif
Append(builder, HashSetString);
AppendFormattable(builder, HashSetNumber);
}
private void Append<T>(StringBuilder builder, IEnumerable<T> items)
{
if (items != null) builder.Append(string.Join("-", items.ToArray()));
}
private void AppendFormattable<T>(StringBuilder builder, IEnumerable<T> items)
where T : IFormattable
{
if (items != null) builder.Append(string.Join("-", items.Select(it => it.ToString(null, CultureInfo.InvariantCulture)).ToArray()));
}
}
}
}
| |
// 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 Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableStackTest : SimpleElementImmutablesTestBase
{
/// <summary>
/// A test for Empty
/// </summary>
/// <typeparam name="T">The type of elements held in the stack.</typeparam>
private void EmptyTestHelper<T>() where T : new()
{
IImmutableStack<T> actual = ImmutableStack<T>.Empty;
Assert.NotNull(actual);
Assert.True(actual.IsEmpty);
AssertAreSame(ImmutableStack<T>.Empty, actual.Clear());
AssertAreSame(ImmutableStack<T>.Empty, actual.Push(new T()).Clear());
}
private ImmutableStack<T> InitStackHelper<T>(params T[] values)
{
Assert.NotNull(values);
var result = ImmutableStack<T>.Empty;
foreach (var value in values)
{
result = result.Push(value);
}
return result;
}
private void PushAndCountTestHelper<T>() where T : new()
{
var actual0 = ImmutableStack<T>.Empty;
Assert.Equal(0, actual0.Count());
var actual1 = actual0.Push(new T());
Assert.Equal(1, actual1.Count());
Assert.Equal(0, actual0.Count());
var actual2 = actual1.Push(new T());
Assert.Equal(2, actual2.Count());
Assert.Equal(0, actual0.Count());
}
private void PopTestHelper<T>(params T[] values)
{
Assert.NotNull(values);
Assert.InRange(values.Length, 1, int.MaxValue);
var full = this.InitStackHelper(values);
var currentStack = full;
// This loop tests the immutable properties of Pop.
for (int expectedCount = values.Length; expectedCount > 0; expectedCount--)
{
Assert.Equal(expectedCount, currentStack.Count());
currentStack.Pop();
Assert.Equal(expectedCount, currentStack.Count());
var nextStack = currentStack.Pop();
Assert.Equal(expectedCount, currentStack.Count());
Assert.NotSame(currentStack, nextStack);
AssertAreSame(currentStack.Pop(), currentStack.Pop(), "Popping the stack 2X should yield the same shorter stack.");
currentStack = nextStack;
}
}
private void PeekTestHelper<T>(params T[] values)
{
Assert.NotNull(values);
Assert.InRange(values.Length, 1, int.MaxValue);
var current = this.InitStackHelper(values);
for (int i = values.Length - 1; i >= 0; i--)
{
AssertAreSame(values[i], current.Peek());
T element;
current.Pop(out element);
AssertAreSame(current.Peek(), element);
var next = current.Pop();
AssertAreSame(values[i], current.Peek(), "Pop mutated the stack instance.");
current = next;
}
}
private void EnumeratorTestHelper<T>(params T[] values)
{
var full = this.InitStackHelper(values);
int i = values.Length - 1;
foreach (var element in full)
{
AssertAreSame(values[i--], element);
}
Assert.Equal(-1, i);
i = values.Length - 1;
foreach (T element in (System.Collections.IEnumerable)full)
{
AssertAreSame(values[i--], element);
}
Assert.Equal(-1, i);
}
[Fact]
public void EmptyTest()
{
this.EmptyTestHelper<GenericParameterHelper>();
this.EmptyTestHelper<int>();
}
[Fact]
public void PushAndCountTest()
{
this.PushAndCountTestHelper<GenericParameterHelper>();
this.PushAndCountTestHelper<int>();
}
[Fact]
public void PopTest()
{
this.PopTestHelper(
new GenericParameterHelper(1),
new GenericParameterHelper(2),
new GenericParameterHelper(3));
this.PopTestHelper(1, 2, 3);
}
[Fact]
public void PopOutValue()
{
var stack = ImmutableStack<int>.Empty.Push(5).Push(6);
int top;
stack = stack.Pop(out top);
Assert.Equal(6, top);
var empty = stack.Pop(out top);
Assert.Equal(5, top);
Assert.True(empty.IsEmpty);
// Try again with the interface to verify extension method behavior.
IImmutableStack<int> stackInterface = stack;
Assert.Same(empty, stackInterface.Pop(out top));
Assert.Equal(5, top);
}
[Fact]
public void PeekTest()
{
this.PeekTestHelper(
new GenericParameterHelper(1),
new GenericParameterHelper(2),
new GenericParameterHelper(3));
this.PeekTestHelper(1, 2, 3);
}
[Fact]
public void EnumeratorTest()
{
this.EnumeratorTestHelper(new GenericParameterHelper(1), new GenericParameterHelper(2));
this.EnumeratorTestHelper<GenericParameterHelper>();
this.EnumeratorTestHelper(1, 2);
this.EnumeratorTestHelper<int>();
var stack = ImmutableStack.Create<int>(5);
var enumeratorStruct = stack.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.True(enumeratorStruct.MoveNext());
Assert.Equal(5, enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumeratorStruct.Current);
Assert.False(enumeratorStruct.MoveNext());
var enumerator = ((IEnumerable<int>)stack).GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal(5, enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
}
[Fact]
public void EqualityTest()
{
Assert.False(ImmutableStack<int>.Empty.Equals(null));
Assert.False(ImmutableStack<int>.Empty.Equals("hi"));
Assert.Equal(ImmutableStack<int>.Empty, ImmutableStack<int>.Empty);
Assert.Equal(ImmutableStack<int>.Empty.Push(3), ImmutableStack<int>.Empty.Push(3));
Assert.NotEqual(ImmutableStack<int>.Empty.Push(5), ImmutableStack<int>.Empty.Push(3));
Assert.NotEqual(ImmutableStack<int>.Empty.Push(3).Push(5), ImmutableStack<int>.Empty.Push(3));
Assert.NotEqual(ImmutableStack<int>.Empty.Push(3), ImmutableStack<int>.Empty.Push(3).Push(5));
}
[Fact]
public void GetEnumerator_EmptyStackMoveNext_ReturnsFalse()
{
ImmutableStack<int> stack = ImmutableStack<int>.Empty;
Assert.False(stack.GetEnumerator().MoveNext());
}
[Fact]
public void EmptyPeekThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableStack<GenericParameterHelper>.Empty.Peek());
}
[Fact]
public void EmptyPopThrows()
{
Assert.Throws<InvalidOperationException>(() => ImmutableStack<GenericParameterHelper>.Empty.Pop());
}
[Fact]
public void Create()
{
ImmutableStack<int> stack = ImmutableStack.Create<int>();
Assert.True(stack.IsEmpty);
stack = ImmutableStack.Create(1);
Assert.False(stack.IsEmpty);
Assert.Equal(new[] { 1 }, stack);
stack = ImmutableStack.Create(1, 2);
Assert.False(stack.IsEmpty);
Assert.Equal(new[] { 2, 1 }, stack);
stack = ImmutableStack.CreateRange((IEnumerable<int>)new[] { 1, 2 });
Assert.False(stack.IsEmpty);
Assert.Equal(new[] { 2, 1 }, stack);
Assert.Throws<ArgumentNullException>("items", () => ImmutableStack.CreateRange((IEnumerable<int>)null));
Assert.Throws<ArgumentNullException>("items", () => ImmutableStack.Create((int[])null));
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableStack.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableStack.Create<string>("1", "2", "3"));
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
var stack = ImmutableStack<T>.Empty;
foreach (var value in contents.Reverse())
{
stack = stack.Push(value);
}
return stack;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
namespace Revit.SDK.Samples.WindowWizard.CS
{
/// <summary>
/// The wizard form
/// </summary>
public partial class WizardForm : System.Windows.Forms.Form
{
#region Class Memeber Variables
/// <summary>
/// store the wizard parameter
/// </summary>
WizardParameter m_para;
/// <summary>
/// store the family types list
/// </summary>
List<String> m_types = new List<string>();
/// <summary>
/// store the bindSource
/// </summary>
BindingSource bindSource = new BindingSource();
/// <summary>
/// store the new type button tooltip
/// </summary>
ToolTip m_newTip = new ToolTip();
/// <summary>
/// store the copy type button tooltip
/// </summary>
ToolTip m_copyTip = new ToolTip();
/// <summary>
/// store the error tooltip
/// </summary>
ToolTip m_errorTip = new ToolTip();
/// <summary>
/// store the font
/// </summary>
Font m_highFont, m_commonFont;
/// <summary>
/// store DoubleHungWinPara list
/// </summary>
BindingList<DoubleHungWinPara> paraList = new BindingList<DoubleHungWinPara>();
#endregion
/// <summary>
/// constructor of WizardForm
/// </summary>
/// <param name="para">the WizardParameter</param>
public WizardForm(WizardParameter para)
{
m_para = para;
InitializeComponent();
InitializePara();
m_newTip.SetToolTip(button_newType, "Add new type");
m_copyTip.SetToolTip(button_duplicateType, "Duplicate the type");
m_errorTip.ShowAlways = false;
m_highFont = InputDimensionLabel.Font;
m_commonFont = WindowPropertyLabel.Font;
SetPanelVisibility(2);
}
/// <summary>
/// The nextbutton click function
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void Step1_NextButton_Click(object sender, EventArgs e)
{
if (this.panel1.Visible)
{
InitializePara();
SetPanelVisibility(2);
}
else if (this.panel2.Visible)
{
transforData();
SetPanelVisibility(3);
}
else if (this.panel3.Visible)
{
SetPanelVisibility(4);
SetGridData();
}
else if (this.panel4.Visible)
{
m_para.PathName = this.m_pathName.Text;
this.DialogResult = DialogResult.OK;
Close();
}
}
/// <summary>
/// set panel visibility
/// </summary>
/// <param name="panelNum">panel number</param>
private void SetPanelVisibility(int panelNum)
{
switch (panelNum)
{
case 1:
this.panel1.Visible = true;
this.panel2.Visible = false;
this.panel3.Visible = false;
this.panel4.Visible = false;
this.Step1_BackButton.Enabled = false;
break;
case 2:
this.panel1.Visible = false;
this.panel2.Visible = true;
this.panel3.Visible = false;
this.panel4.Visible = false;
this.Step1_BackButton.Enabled = false;
this.InputDimensionLabel.ForeColor = System.Drawing.Color.Black;
this.InputDimensionLabel.Font = m_highFont;
this.WindowPropertyLabel.ForeColor = System.Drawing.Color.Gray;
this.WindowPropertyLabel.Font = m_commonFont;
this.InputPathLabel.ForeColor = System.Drawing.Color.Gray;
this.InputPathLabel.Font = m_commonFont;
break;
case 3:
this.panel3.Visible = true;
this.panel1.Visible = false;
this.panel2.Visible = false;
this.panel4.Visible = false;
this.Step1_BackButton.Enabled = true;
this.Step1_NextButton.Text = "Next >";
this.InputPathLabel.ForeColor = System.Drawing.Color.Gray;
this.InputDimensionLabel.Font = m_commonFont;
this.WindowPropertyLabel.ForeColor = System.Drawing.Color.Black;
this.WindowPropertyLabel.Font = m_highFont;
this.InputPathLabel.ForeColor = System.Drawing.Color.Gray;
this.InputPathLabel.Font = m_commonFont;
break;
case 4:
this.panel1.Visible = false;
this.panel2.Visible = false;
this.panel3.Visible = false;
this.panel4.Visible = true;
this.Step1_BackButton.Enabled = true;
this.Step1_NextButton.Text = "Finish";
this.InputPathLabel.ForeColor = System.Drawing.Color.Gray;
this.InputDimensionLabel.Font = m_commonFont;
this.WindowPropertyLabel.ForeColor = System.Drawing.Color.Gray;
this.WindowPropertyLabel.Font = m_commonFont;
this.InputPathLabel.ForeColor = System.Drawing.Color.Black;
this.InputPathLabel.Font = m_highFont;
break;
}
}
/// <summary>
/// the backbutton click function
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void Step1_BackButton_Click(object sender, EventArgs e)
{
if (this.panel2.Visible)
{
SetPanelVisibility(1);
}
else if (this.panel3.Visible)
{
SetPanelVisibility(2);
}
else if (this.panel4.Visible)
{
SetPanelVisibility(3);
}
}
/// <summary>
/// transfer data
/// </summary>
private void transforData()
{
if (m_para.m_template == "DoubleHung")
{
DoubleHungWinPara dbhungPara = new DoubleHungWinPara(m_para.Validator.IsMetric);
dbhungPara.Height = Convert.ToDouble(m_height.Text, System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat);
dbhungPara.Width = Convert.ToDouble(m_width.Text);
dbhungPara.Inset = Convert.ToDouble(m_inset.Text);
dbhungPara.SillHeight = Convert.ToDouble(m_sillHeight.Text);
dbhungPara.Type = m_comboType.Text;
m_para.CurrentPara = dbhungPara;
if (!m_para.WinParaTab.Contains(dbhungPara.Type))
{
m_para.WinParaTab.Add(dbhungPara.Type, dbhungPara);
m_comboType.Items.Add(dbhungPara.Type);
}
else
{
m_para.WinParaTab[dbhungPara.Type] = dbhungPara;
}
}
Update();
}
/// <summary>
/// Initialize data
/// </summary>
private void InitializePara()
{
DoubleHungWinPara dbhungPara = new DoubleHungWinPara(m_para.Validator.IsMetric);
if (!m_para.WinParaTab.Contains(dbhungPara.Type))
{
m_para.WinParaTab.Add(dbhungPara.Type, dbhungPara);
m_types.Add(dbhungPara.Type);
}
else
{
m_para.WinParaTab[dbhungPara.Type] = dbhungPara;
}
bindSource.DataSource = m_types;
this.m_comboType.Items.Add(m_para.CurrentPara.Type);
this.m_comboType.SelectedIndex = 0;
this.m_glassMat.DataSource = m_para.GlassMaterials;
this.m_sashMat.DataSource = m_para.FrameMaterials;
this.m_pathName.Text = m_para.PathName;
SetParaText(dbhungPara);
}
/// <summary>
/// The newtype button click function
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void button_newType_Click(object sender, EventArgs e)
{
transforData();
DoubleHungWinPara newPara = new DoubleHungWinPara(m_para.Validator.IsMetric);
SetParaText(newPara);
this.m_comboType.Focus();
}
/// <summary>
/// The duplicatebutton click function
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void button_duplicateType_Click(object sender, EventArgs e)
{
transforData();
DoubleHungWinPara copyPara = new DoubleHungWinPara((DoubleHungWinPara)m_para.CurrentPara);
SetParaText(copyPara);
this.m_comboType.Focus();
}
/// <summary>
/// set WindowParameter text
/// </summary>
/// <param name="para">the WindowParameter</param>
private void SetParaText(WindowParameter para)
{
DoubleHungWinPara dbhungPara = para as DoubleHungWinPara;
m_sillHeight.Text = Convert.ToString(dbhungPara.SillHeight);
m_width.Text = Convert.ToString(dbhungPara.Width);
m_height.Text = Convert.ToString(dbhungPara.Height);
m_inset.Text = Convert.ToString(dbhungPara.Inset);
m_comboType.Text = dbhungPara.Type;
}
/// <summary>
/// set grid data
/// </summary>
private void SetGridData()
{
paraList.Clear();
foreach (String key in m_para.WinParaTab.Keys)
{
DoubleHungWinPara para = m_para.WinParaTab[key] as DoubleHungWinPara;
if (null == para)
{
continue;
}
paraList.Add(para);
}
this.dataGridView1.DataSource = paraList;
}
/// <summary>
/// m_height textbox's text changed event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_height_TextChanged(object sender, EventArgs e)
{
ValidateInput(m_height);
}
/// <summary>
/// m_width textbox's text changed event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_width_TextChanged(object sender, EventArgs e)
{
ValidateInput(m_width);
}
/// <summary>
/// m_inset textbox's text changed event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_inset_TextChanged(object sender, EventArgs e)
{
ValidateInput(m_inset);
}
/// <summary>
/// m_sillHeight textbox's text changed event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_sillHeight_TextChanged(object sender, EventArgs e)
{
ValidateInput(m_sillHeight);
}
/// <summary>
/// m_comboType SelectedIndexChanged event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_comboType_SelectedIndexChanged(object sender, EventArgs e)
{
m_para.CurrentPara = m_para.WinParaTab[m_comboType.SelectedItem.ToString()] as WindowParameter;
SetParaText(m_para.CurrentPara);
}
/// <summary>
/// m_glassMat SelectedIndexChanged event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_glassMat_SelectedIndexChanged(object sender, EventArgs e)
{
m_para.GlassMat = m_glassMat.SelectedItem.ToString();
}
/// <summary>
/// m_sashMat SelectedIndexChanged event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_sashMat_SelectedIndexChanged(object sender, EventArgs e)
{
m_para.SashMat = m_sashMat.SelectedItem.ToString();
}
/// <summary>
/// validate control input value
/// </summary>
/// <param name="control">the control</param>
private bool ValidateInput(Control control)
{
if (null == control)
{
return true;
}
if (String.IsNullOrEmpty(control.Text))
{
this.Step1_NextButton.Enabled = false;
return false;
}
TextBox textbox = control as TextBox;
if (null == textbox)
{
return true;
}
double value = 0.0;
String result = m_para.Validator.IsDouble(textbox.Text, ref value);
if (!String.IsNullOrEmpty(result))
{
m_errorTip.SetToolTip(textbox, result);
textbox.Text = String.Empty;
this.Step1_NextButton.Enabled = false;
return false;
}
m_errorTip.RemoveAll();
switch (textbox.Name)
{
case "m_height":
result = m_para.Validator.IsHeightInRange(value);
break;
case "m_width":
result = m_para.Validator.IsWidthInRange(value);
break;
case "m_inset":
result = m_para.Validator.IsInsetInRange(value);
break;
case "m_sillHeight":
result = m_para.Validator.IsSillHeightInRange(value);
break;
default:
break;
}
if (!String.IsNullOrEmpty(result))
{
m_errorTip.SetToolTip(textbox, result);
this.Step1_NextButton.Enabled = false;
return false;
}
m_errorTip.RemoveAll();
this.Step1_NextButton.Enabled = true;
return true;
}
/// <summary>
/// m_buttonBrowser click event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_buttonBrowser_Click(object sender, EventArgs e)
{
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.CheckPathExists = true;
saveDialog.SupportMultiDottedExtensions = true;
saveDialog.OverwritePrompt = true;
saveDialog.ValidateNames = true;
saveDialog.Filter = "Family file(*.rfa)|*.rfa|All files(*.*)|*.*";
saveDialog.FilterIndex = 2;
if (DialogResult.OK == saveDialog.ShowDialog())
{
if (!String.IsNullOrEmpty(saveDialog.FileName))
{
m_pathName.Text = saveDialog.FileName;
}
}
}
/// <summary>
/// m_height leave event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_height_Leave(object sender, EventArgs e)
{
CheckValue(m_height);
}
/// <summary>
/// check input
/// </summary>
/// <param name="control">the host control</param>
private void CheckValue(Control control)
{
if (String.IsNullOrEmpty(control.Text))
{
control.Focus();
m_errorTip.SetToolTip(control, "Please input a valid value");
}
if (!ValidateInput(control))
{
control.Focus();
control.Text = String.Empty;
}
}
/// <summary>
/// m_width leave event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_width_Leave(object sender, EventArgs e)
{
CheckValue(m_width);
}
/// <summary>
/// m_inset leave event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_inset_Leave(object sender, EventArgs e)
{
CheckValue(m_inset);
}
/// <summary>
/// m_sillHeight leave event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_sillHeight_Leave(object sender, EventArgs e)
{
CheckValue(m_sillHeight);
}
/// <summary>
/// m_comboType leave event
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void m_comboType_Leave(object sender, EventArgs e)
{
CheckValue(m_comboType);
}
/// <summary>
/// Step1_HelpButton click event to open the help document
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
private void Step1_HelpButton_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
char[] sp={'\\'};
path = path.Substring(0, path.LastIndexOfAny(sp));
path = path.Substring(0,path.LastIndexOfAny(sp)) + "\\ReadMe_WindowWizard.rtf";
System.Diagnostics.Process.Start(path);
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class UnionTests
{
private const int DuplicateFactor = 8;
// Get two ranges, with the right starting where the left ends
public static IEnumerable<object[]> UnionUnorderedCountData(int[] counts)
{
foreach (int left in counts)
{
foreach (int right in counts)
{
yield return new object[] { left, right };
}
}
}
private static IEnumerable<object[]> UnionUnorderedData(int[] counts)
{
foreach (object[] parms in UnorderedSources.BinaryRanges(counts, (l, r) => l, counts))
{
yield return parms.Take(4).ToArray();
}
}
// Union returns only the ordered portion ordered.
// Get two ranges, both ordered.
public static IEnumerable<object[]> UnionData(int[] counts)
{
foreach (object[] parms in UnionUnorderedData(counts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
// Get two ranges, with only the left being ordered.
public static IEnumerable<object[]> UnionFirstOrderedData(int[] counts)
{
foreach (object[] parms in UnionUnorderedData(counts))
{
yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] };
}
}
// Get two ranges, with only the right being ordered.
public static IEnumerable<object[]> UnionSecondOrderedData(int[] counts)
{
foreach (object[] parms in UnionUnorderedData(counts))
{
yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] };
}
}
// Get two ranges, both sourced from arrays, with duplicate items in each array.
// Used in distinctness tests, in contrast to relying on a Select predicate to generate duplicate items.
public static IEnumerable<object[]> UnionSourceMultipleData(int[] counts)
{
foreach (int leftCount in counts)
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel();
foreach (int rightCount in new[] { 0, 1, Math.Max(DuplicateFactor, leftCount / 2), Math.Max(DuplicateFactor, leftCount) }.Distinct())
{
int rightStart = leftCount - Math.Min(leftCount, rightCount) / 2;
ParallelQuery<int> right = Enumerable.Range(0, rightCount * DuplicateFactor).Select(x => x % rightCount + rightStart).ToArray().AsParallel();
yield return new object[] { left, leftCount, right, rightCount, Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2 };
}
}
}
//
// Union
//
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
foreach (int i in leftQuery.Union(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_Longrunning()
{
Union_Unordered(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })]
public static void Union(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
foreach (int i in leftQuery.Union(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(leftCount + rightCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionFirstOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_FirstOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount);
int seen = 0;
foreach (int i in leftQuery.Union(rightQuery))
{
if (i < leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionFirstOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_FirstOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_FirstOrdered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionSecondOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_SecondOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
foreach (int i in leftQuery.Union(rightQuery))
{
if (i >= leftCount)
{
Assert.Equal(seen++, i);
}
else
{
seenUnordered.Add(i);
}
}
Assert.Equal(leftCount + rightCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSecondOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_SecondOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_SecondOrdered(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered_NotPipelined(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount);
Assert.All(leftQuery.Union(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_NotPipelined_Longrunning()
{
Union_Unordered_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })]
public static void Union_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
int seen = 0;
Assert.All(leftQuery.Union(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(leftCount + rightCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionFirstOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_FirstOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount);
int seen = 0;
Assert.All(leftQuery.Union(rightQuery).ToList(), x =>
{
if (x < leftCount) Assert.Equal(seen++, x);
else seenUnordered.Add(x);
});
Assert.Equal(leftCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionFirstOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_FirstOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_FirstOrdered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionSecondOrderedData), new[] { 0, 1, 2, 16 })]
public static void Union_SecondOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount);
int seen = leftCount;
Assert.All(leftQuery.Union(rightQuery).ToList(), x =>
{
if (x >= leftCount) Assert.Equal(seen++, x);
else seenUnordered.Add(x);
});
Assert.Equal(leftCount + rightCount, seen);
seenUnordered.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSecondOrderedData), new[] { 512, 1024 * 8 })]
public static void Union_SecondOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_SecondOrdered_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered_Distinct(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount);
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_Distinct_Longrunning()
{
Union_Unordered_Distinct(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, 16 })]
public static void Union_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
int seen = 0;
foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(expectedCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Distinct(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionUnorderedCountData), new[] { 0, 1, 2, 16 })]
public static void Union_Unordered_Distinct_NotPipelined(int leftCount, int rightCount)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(leftCount, rightCount);
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount);
Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(),
x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void Union_Unordered_Distinct_NotPipelined_Longrunning()
{
Union_Unordered_Distinct_NotPipelined(Sources.OuterLoopCount, Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(UnionData), new[] { 0, 1, 2, DuplicateFactor * 2 })]
public static void Union_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
leftCount = Math.Min(DuplicateFactor, leftCount);
rightCount = Math.Min(DuplicateFactor, rightCount);
int offset = leftCount - Math.Min(leftCount, rightCount) / 2;
int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2;
int seen = 0;
Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(),
x => Assert.Equal(seen++, x));
Assert.Equal(expectedCount, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionData), new[] { 512, 1024 * 8 })]
public static void Union_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
Union_Distinct_NotPipelined(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(UnionSourceMultipleData), new[] { 0, 1, 2, DuplicateFactor * 2 })]
public static void Union_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.Union(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSourceMultipleData), new[] { 512, 1024 * 8 })]
public static void Union_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData(nameof(UnionSourceMultipleData), new[] { 0, 1, 2, DuplicateFactor * 2 })]
public static void Union_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
int seen = 0;
Assert.All(leftQuery.AsOrdered().Union(rightQuery.AsOrdered()), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnionSourceMultipleData), new[] { 512, 1024 * 8 })]
public static void Union_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Union_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Fact]
public static void Union_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Union_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Union(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Union(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Union(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Union(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Union_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1)));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Union(null));
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Union(null, EqualityComparer<int>.Default));
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Diagnostics.Contracts;
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
namespace System.Collections.Generic
{
// Summary:
// Represents a generic collection of key/value pairs.
[ContractClass(typeof(IDictionaryContract<,>))]
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey,TValue>>
{
// Summary:
// Gets an System.Collections.Generic.ICollection<T> containing the keys of
// the System.Collections.Generic.IDictionary<TKey,TValue>.
//
// Returns:
// An System.Collections.Generic.ICollection<T> containing the keys of the object
// that implements System.Collections.Generic.IDictionary<TKey,TValue>.
ICollection<TKey> Keys
{
get;
}
//
// Summary:
// Gets an System.Collections.Generic.ICollection<T> containing the values in
// the System.Collections.Generic.IDictionary<TKey,TValue>.
//
// Returns:
// An System.Collections.Generic.ICollection<T> containing the values in the
// object that implements System.Collections.Generic.IDictionary<TKey,TValue>.
ICollection<TValue> Values
{
get;
}
// Summary:
// Gets or sets the element with the specified key.
//
// Parameters:
// key:
// The key of the element to get or set.
//
// Returns:
// The element with the specified key.
//
// Exceptions:
// System.NotSupportedException:
// The property is set and the System.Collections.Generic.IDictionary<TKey,TValue>
// is read-only.
//
// System.ArgumentNullException:
// key is null.
//
// System.Collections.Generic.KeyNotFoundException:
// The property is retrieved and key is not found.
TValue this[TKey key]
{
get;
set;
}
// Summary:
// Adds an element with the provided key and value to the System.Collections.Generic.IDictionary<TKey,TValue>.
//
// Parameters:
// value:
// The object to use as the value of the element to add.
//
// key:
// The object to use as the key of the element to add.
//
// Exceptions:
// System.NotSupportedException:
// The System.Collections.Generic.IDictionary<TKey,TValue> is read-only.
//
// System.ArgumentException:
// An element with the same key already exists in the System.Collections.Generic.IDictionary<TKey,TValue>.
//
// System.ArgumentNullException:
// key is null.
void Add(TKey key, TValue value);
//
// Summary:
// Determines whether the System.Collections.Generic.IDictionary<TKey,TValue>
// contains an element with the specified key.
//
// Parameters:
// key:
// The key to locate in the System.Collections.Generic.IDictionary<TKey,TValue>.
//
// Returns:
// true if the System.Collections.Generic.IDictionary<TKey,TValue> contains
// an element with the key; otherwise, false.
//
// Exceptions:
// System.ArgumentNullException:
// key is null.
[Pure]
bool ContainsKey(TKey key);
//
// Summary:
// Removes the element with the specified key from the System.Collections.Generic.IDictionary<TKey,TValue>.
//
// Parameters:
// key:
// The key of the element to remove.
//
// Returns:
// true if the element is successfully removed; otherwise, false. This method
// also returns false if key was not found in the original System.Collections.Generic.IDictionary<TKey,TValue>.
//
// Exceptions:
// System.NotSupportedException:
// The System.Collections.Generic.IDictionary<TKey,TValue> is read-only.
//
// System.ArgumentNullException:
// key is null.
bool Remove(TKey key);
[Pure]
bool TryGetValue(TKey key, out TValue value);
}
[ContractClassFor(typeof(IDictionary<,>))]
abstract class IDictionaryContract<TKey, TValue> : IDictionary<TKey,TValue>
{
#region IDictionary<TKey,TValue> Members
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get {
Contract.Ensures(Contract.Result<ICollection<TKey>>() != null);
throw new NotImplementedException();
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get {
Contract.Ensures(Contract.Result<ICollection<TValue>>() != null);
throw new NotImplementedException();
}
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get
{
Contract.Requires(!ReferenceEquals(key, null));
// Contract.Requires(ContainsKey(key));
throw new NotImplementedException();
}
set
{
Contract.Requires(!ReferenceEquals(key, null));
// Contract.Ensures(ContainsKey(key));
//Contract.Ensures(old(ContainsKey(key)) ==> Count == old(Count));
//Contract.Ensures(!old(ContainsKey(key)) ==> Count == old(Count) + 1);
throw new NotImplementedException();
}
}
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
Contract.Requires(!ReferenceEquals(key, null));
// Contract.Requires(!ContainsKey(key));
//modifies this.*;
//Contract.Ensures(ContainsKey(key));
}
public bool ContainsKey(TKey key)
{
Contract.Requires(!ReferenceEquals(key, null));
Contract.Ensures(!Contract.Result<bool>() || (Count > 0));
throw new NotImplementedException();
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
Contract.Requires(!ReferenceEquals(key, null));
// Contract.Ensures(!Contract.Result<bool>() || Contract.OldValue(ContainsKey(key)) && !ContainsKey(key));
throw new NotImplementedException();
}
bool IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)
{
Contract.Requires(!ReferenceEquals(key, null));
Contract.Ensures(Contract.Result<bool>() == ContainsKey(key));
throw new NotImplementedException();
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public int Count
{
get { throw new NotImplementedException(); }
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { throw new NotImplementedException(); }
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotImplementedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable Members
public object[] Model {
get { throw new NotImplementedException(); }
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Xml;
using System.Reflection;
using System.Text;
using System.Threading;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Mono.Addins;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicInventoryAccessModule")]
public class BasicInventoryAccessModule : INonSharedRegionModule, IInventoryAccessModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_Enabled = false;
protected Scene m_Scene;
protected IUserManagement m_UserManagement;
protected IUserManagement UserManagementModule
{
get
{
if (m_UserManagement == null)
m_UserManagement = m_Scene.RequestModuleInterface<IUserManagement>();
return m_UserManagement;
}
}
public bool CoalesceMultipleObjectsToInventory { get; set; }
#region INonSharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "BasicInventoryAccessModule"; }
}
public virtual void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryAccessModule", "");
if (name == Name)
{
m_Enabled = true;
InitialiseCommon(source);
m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name);
}
}
}
/// <summary>
/// Common module config for both this and descendant classes.
/// </summary>
/// <param name="source"></param>
protected virtual void InitialiseCommon(IConfigSource source)
{
IConfig inventoryConfig = source.Configs["Inventory"];
if (inventoryConfig != null)
CoalesceMultipleObjectsToInventory
= inventoryConfig.GetBoolean("CoalesceMultipleObjectsToInventory", true);
else
CoalesceMultipleObjectsToInventory = true;
}
public virtual void PostInitialise()
{
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scene = scene;
scene.RegisterModuleInterface<IInventoryAccessModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
}
protected virtual void OnNewClient(IClientAPI client)
{
client.OnCreateNewInventoryItem += CreateNewInventoryItem;
}
public virtual void Close()
{
if (!m_Enabled)
return;
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scene = null;
}
public virtual void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion
#region Inventory Access
/// <summary>
/// Create a new inventory item. Called when the client creates a new item directly within their
/// inventory (e.g. by selecting a context inventory menu option).
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="folderID"></param>
/// <param name="callbackID"></param>
/// <param name="description"></param>
/// <param name="name"></param>
/// <param name="invType"></param>
/// <param name="type"></param>
/// <param name="wearableType"></param>
/// <param name="nextOwnerMask"></param>
public void CreateNewInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte assetType,
byte wearableType, uint nextOwnerMask, int creationDate)
{
m_log.DebugFormat("[INVENTORY ACCESS MODULE]: Received request to create inventory item {0} in folder {1}", name, folderID);
if (!m_Scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId))
return;
if (transactionID == UUID.Zero)
{
ScenePresence presence;
if (m_Scene.TryGetScenePresence(remoteClient.AgentId, out presence))
{
byte[] data = null;
if (invType == (sbyte)InventoryType.Landmark && presence != null)
{
string suffix = string.Empty, prefix = string.Empty;
string strdata = GenerateLandmark(presence, out prefix, out suffix);
data = Encoding.ASCII.GetBytes(strdata);
name = prefix + name;
description += suffix;
}
AssetBase asset = m_Scene.CreateAsset(name, description, assetType, data, remoteClient.AgentId);
m_Scene.AssetService.Store(asset);
m_Scene.CreateNewInventoryItem(
remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID,
name, description, 0, callbackID, asset, invType, nextOwnerMask, creationDate);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ACCESS MODULE]: ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem",
remoteClient.AgentId);
}
}
else
{
IAgentAssetTransactions agentTransactions = m_Scene.AgentTransactionsModule;
if (agentTransactions != null)
{
agentTransactions.HandleItemCreationFromTransaction(
remoteClient, transactionID, folderID, callbackID, description,
name, invType, assetType, wearableType, nextOwnerMask);
}
}
}
protected virtual string GenerateLandmark(ScenePresence presence, out string prefix, out string suffix)
{
prefix = string.Empty;
suffix = string.Empty;
Vector3 pos = presence.AbsolutePosition;
return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n",
presence.Scene.RegionInfo.RegionID,
pos.X, pos.Y, pos.Z,
presence.RegionHandle);
}
/// <summary>
/// Capability originating call to update the asset of an item in an agent's inventory
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="data"></param>
/// <returns></returns>
public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
{
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = m_Scene.InventoryService.GetItem(item);
if (item.Owner != remoteClient.AgentId)
return UUID.Zero;
if (item != null)
{
if ((InventoryType)item.InvType == InventoryType.Notecard)
{
if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false);
return UUID.Zero;
}
remoteClient.SendAlertMessage("Notecard saved");
}
else if ((InventoryType)item.InvType == InventoryType.LSL)
{
if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false);
return UUID.Zero;
}
remoteClient.SendAlertMessage("Script saved");
}
AssetBase asset =
CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString());
item.AssetID = asset.FullID;
m_Scene.AssetService.Store(asset);
m_Scene.InventoryService.UpdateItem(item);
// remoteClient.SendInventoryItemCreateUpdate(item);
return (asset.FullID);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update",
itemID);
}
return UUID.Zero;
}
public virtual List<InventoryItemBase> CopyToInventory(
DeRezAction action, UUID folderID,
List<SceneObjectGroup> objectGroups, IClientAPI remoteClient, bool asAttachment)
{
List<InventoryItemBase> copiedItems = new List<InventoryItemBase>();
Dictionary<UUID, List<SceneObjectGroup>> bundlesToCopy = new Dictionary<UUID, List<SceneObjectGroup>>();
if (CoalesceMultipleObjectsToInventory)
{
// The following code groups the SOG's by owner. No objects
// belonging to different people can be coalesced, for obvious
// reasons.
foreach (SceneObjectGroup g in objectGroups)
{
if (!bundlesToCopy.ContainsKey(g.OwnerID))
bundlesToCopy[g.OwnerID] = new List<SceneObjectGroup>();
bundlesToCopy[g.OwnerID].Add(g);
}
}
else
{
// If we don't want to coalesce then put every object in its own bundle.
foreach (SceneObjectGroup g in objectGroups)
{
List<SceneObjectGroup> bundle = new List<SceneObjectGroup>();
bundle.Add(g);
bundlesToCopy[g.UUID] = bundle;
}
}
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Copying {0} object bundles to folder {1} action {2} for {3}",
// bundlesToCopy.Count, folderID, action, remoteClient.Name);
// Each iteration is really a separate asset being created,
// with distinct destinations as well.
foreach (List<SceneObjectGroup> bundle in bundlesToCopy.Values)
copiedItems.Add(CopyBundleToInventory(action, folderID, bundle, remoteClient, asAttachment));
return copiedItems;
}
/// <summary>
/// Copy a bundle of objects to inventory. If there is only one object, then this will create an object
/// item. If there are multiple objects then these will be saved as a single coalesced item.
/// </summary>
/// <param name="action"></param>
/// <param name="folderID"></param>
/// <param name="objlist"></param>
/// <param name="remoteClient"></param>
/// <param name="asAttachment">Should be true if the bundle is being copied as an attachment. This prevents
/// attempted serialization of any script state which would abort any operating scripts.</param>
/// <returns>The inventory item created by the copy</returns>
protected InventoryItemBase CopyBundleToInventory(
DeRezAction action, UUID folderID, List<SceneObjectGroup> objlist, IClientAPI remoteClient,
bool asAttachment)
{
CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero);
// Dictionary<UUID, Vector3> originalPositions = new Dictionary<UUID, Vector3>();
foreach (SceneObjectGroup objectGroup in objlist)
{
if (objectGroup.RootPart.KeyframeMotion != null)
objectGroup.RootPart.KeyframeMotion.Stop();
objectGroup.RootPart.KeyframeMotion = null;
// Vector3 inventoryStoredPosition = new Vector3
// (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize)
// ? 250
// : objectGroup.AbsolutePosition.X)
// ,
// (objectGroup.AbsolutePosition.Y > (int)Constants.RegionSize)
// ? 250
// : objectGroup.AbsolutePosition.Y,
// objectGroup.AbsolutePosition.Z);
//
// originalPositions[objectGroup.UUID] = objectGroup.AbsolutePosition;
//
// objectGroup.AbsolutePosition = inventoryStoredPosition;
// Make sure all bits but the ones we want are clear
// on take.
// This will be applied to the current perms, so
// it will do what we want.
objectGroup.RootPart.NextOwnerMask &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify |
(uint)PermissionMask.Export);
objectGroup.RootPart.NextOwnerMask |=
(uint)PermissionMask.Move;
coa.Add(objectGroup);
}
string itemXml;
// If we're being called from a script, then trying to serialize that same script's state will not complete
// in any reasonable time period. Therefore, we'll avoid it. The worst that can happen is that if
// the client/server crashes rather than logging out normally, the attachment's scripts will resume
// without state on relog. Arguably, this is what we want anyway.
if (objlist.Count > 1)
itemXml = CoalescedSceneObjectsSerializer.ToXml(coa, !asAttachment);
else
itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0], !asAttachment);
// // Restore the position of each group now that it has been stored to inventory.
// foreach (SceneObjectGroup objectGroup in objlist)
// objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID];
InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID);
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Created item is {0}",
// item != null ? item.ID.ToString() : "NULL");
if (item == null)
return null;
// Can't know creator is the same, so null it in inventory
if (objlist.Count > 1)
{
item.CreatorId = UUID.Zero.ToString();
item.Flags = (uint)InventoryItemFlags.ObjectHasMultipleItems;
}
else
{
item.CreatorId = objlist[0].RootPart.CreatorID.ToString();
item.CreatorData = objlist[0].RootPart.CreatorData;
item.SaleType = objlist[0].RootPart.ObjectSaleType;
item.SalePrice = objlist[0].RootPart.SalePrice;
}
AssetBase asset = CreateAsset(
objlist[0].GetPartName(objlist[0].RootPart.LocalId),
objlist[0].GetPartDescription(objlist[0].RootPart.LocalId),
(sbyte)AssetType.Object,
Utils.StringToBytes(itemXml),
objlist[0].OwnerID.ToString());
m_Scene.AssetService.Store(asset);
item.AssetID = asset.FullID;
if (DeRezAction.SaveToExistingUserInventoryItem == action)
{
m_Scene.InventoryService.UpdateItem(item);
}
else
{
AddPermissions(item, objlist[0], objlist, remoteClient);
item.CreationDate = Util.UnixTimeSinceEpoch();
item.Description = asset.Description;
item.Name = asset.Name;
item.AssetType = asset.Type;
m_Scene.AddInventoryItem(item);
if (remoteClient != null && item.Owner == remoteClient.AgentId)
{
remoteClient.SendInventoryItemCreateUpdate(item, 0);
}
else
{
ScenePresence notifyUser = m_Scene.GetScenePresence(item.Owner);
if (notifyUser != null)
{
notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
}
}
}
// This is a hook to do some per-asset post-processing for subclasses that need that
if (remoteClient != null)
ExportAsset(remoteClient.AgentId, asset.FullID);
return item;
}
protected virtual void ExportAsset(UUID agentID, UUID assetID)
{
// nothing to do here
}
/// <summary>
/// Add relevant permissions for an object to the item.
/// </summary>
/// <param name="item"></param>
/// <param name="so"></param>
/// <param name="objsForEffectivePermissions"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
protected InventoryItemBase AddPermissions(
InventoryItemBase item, SceneObjectGroup so, List<SceneObjectGroup> objsForEffectivePermissions,
IClientAPI remoteClient)
{
uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move | PermissionMask.Export) | 7;
foreach (SceneObjectGroup grp in objsForEffectivePermissions)
effectivePerms &= grp.GetEffectivePermissions();
effectivePerms |= (uint)PermissionMask.Move;
if (remoteClient != null && (remoteClient.AgentId != so.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions())
{
uint perms = effectivePerms;
uint nextPerms = (perms & 7) << 13;
if ((nextPerms & (uint)PermissionMask.Copy) == 0)
perms &= ~(uint)PermissionMask.Copy;
if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
perms &= ~(uint)PermissionMask.Transfer;
if ((nextPerms & (uint)PermissionMask.Modify) == 0)
perms &= ~(uint)PermissionMask.Modify;
item.BasePermissions = perms & so.RootPart.NextOwnerMask;
item.CurrentPermissions = item.BasePermissions;
item.NextPermissions = perms & so.RootPart.NextOwnerMask;
item.EveryOnePermissions = so.RootPart.EveryoneMask & so.RootPart.NextOwnerMask;
item.GroupPermissions = so.RootPart.GroupMask & so.RootPart.NextOwnerMask;
// Magic number badness. Maybe this deserves an enum.
// bit 4 (16) is the "Slam" bit, it means treat as passed
// and apply next owner perms on rez
item.CurrentPermissions |= 16; // Slam!
}
else
{
item.BasePermissions = effectivePerms;
item.CurrentPermissions = effectivePerms;
item.NextPermissions = so.RootPart.NextOwnerMask & effectivePerms;
item.EveryOnePermissions = so.RootPart.EveryoneMask & effectivePerms;
item.GroupPermissions = so.RootPart.GroupMask & effectivePerms;
item.CurrentPermissions &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify |
(uint)PermissionMask.Move |
(uint)PermissionMask.Export |
7); // Preserve folded permissions
}
return item;
}
/// <summary>
/// Create an item using details for the given scene object.
/// </summary>
/// <param name="action"></param>
/// <param name="remoteClient"></param>
/// <param name="so"></param>
/// <param name="folderID"></param>
/// <returns></returns>
protected InventoryItemBase CreateItemForObject(
DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID)
{
// Get the user info of the item destination
//
UUID userID = UUID.Zero;
if (action == DeRezAction.Take || action == DeRezAction.TakeCopy ||
action == DeRezAction.SaveToExistingUserInventoryItem)
{
// Take or take copy require a taker
// Saving changes requires a local user
//
if (remoteClient == null)
return null;
userID = remoteClient.AgentId;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is {1} {2}",
// action, remoteClient.Name, userID);
}
else if (so.RootPart.OwnerID == so.RootPart.GroupID)
{
// Group owned objects go to the last owner before the object was transferred.
userID = so.RootPart.LastOwnerID;
}
else
{
// Other returns / deletes go to the object owner
//
userID = so.RootPart.OwnerID;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is object owner {1}",
// action, userID);
}
if (userID == UUID.Zero) // Can't proceed
{
return null;
}
// If we're returning someone's item, it goes back to the
// owner's Lost And Found folder.
// Delete is treated like return in this case
// Deleting your own items makes them go to trash
//
InventoryFolderBase folder = null;
InventoryItemBase item = null;
if (DeRezAction.SaveToExistingUserInventoryItem == action)
{
item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID);
item = m_Scene.InventoryService.GetItem(item);
//item = userInfo.RootFolder.FindItem(
// objectGroup.RootPart.FromUserInventoryItemID);
if (null == item)
{
m_log.DebugFormat(
"[INVENTORY ACCESS MODULE]: Object {0} {1} scheduled for save to inventory has already been deleted.",
so.Name, so.UUID);
return null;
}
}
else
{
// Folder magic
//
if (action == DeRezAction.Delete)
{
// Deleting someone else's item
//
if (remoteClient == null ||
so.OwnerID != remoteClient.AgentId)
{
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
}
else
{
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
}
}
else if (action == DeRezAction.Return)
{
// Dump to lost + found unconditionally
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
}
if (folderID == UUID.Zero && folder == null)
{
if (action == DeRezAction.Delete)
{
// Deletes go to trash by default
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
}
else
{
if (remoteClient == null || so.RootPart.OwnerID != remoteClient.AgentId)
{
// Taking copy of another person's item. Take to
// Objects folder.
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object);
so.FromFolderID = UUID.Zero;
}
else
{
// Catch all. Use lost & found
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
}
}
}
// Override and put into where it came from, if it came
// from anywhere in inventory and the owner is taking it back.
//
if (action == DeRezAction.Take || action == DeRezAction.TakeCopy)
{
if (so.FromFolderID != UUID.Zero && so.RootPart.OwnerID == remoteClient.AgentId)
{
InventoryFolderBase f = new InventoryFolderBase(so.FromFolderID, userID);
folder = m_Scene.InventoryService.GetFolder(f);
if(folder.Type == 14 || folder.Type == 16)
{
// folder.Type = 6;
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object);
}
}
}
if (folder == null) // None of the above
{
folder = new InventoryFolderBase(folderID);
if (folder == null) // Nowhere to put it
{
return null;
}
}
item = new InventoryItemBase();
item.ID = UUID.Random();
item.InvType = (int)InventoryType.Object;
item.Folder = folder.ID;
item.Owner = userID;
}
return item;
}
public virtual SceneObjectGroup RezObject(
IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
{
// m_log.DebugFormat("[INVENTORY ACCESS MODULE]: RezObject for {0}, item {1}", remoteClient.Name, itemID);
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = m_Scene.InventoryService.GetItem(item);
if (item == null)
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: Could not find item {0} for {1} in RezObject()",
itemID, remoteClient.Name);
return null;
}
item.Owner = remoteClient.AgentId;
return RezObject(
remoteClient, item, item.AssetID,
RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection,
RezSelected, RemoveItem, fromTaskID, attachment);
}
public virtual SceneObjectGroup RezObject(
IClientAPI remoteClient, InventoryItemBase item, UUID assetID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
{
AssetBase rezAsset = m_Scene.AssetService.Get(assetID.ToString());
if (rezAsset == null)
{
if (item != null)
{
m_log.WarnFormat(
"[InventoryAccessModule]: Could not find asset {0} for item {1} {2} for {3} in RezObject()",
assetID, item.Name, item.ID, remoteClient.Name);
}
else
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: Could not find asset {0} for {1} in RezObject()",
assetID, remoteClient.Name);
}
return null;
}
SceneObjectGroup group = null;
List<SceneObjectGroup> objlist;
List<Vector3> veclist;
Vector3 bbox;
float offsetHeight;
byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0);
Vector3 pos;
bool single = m_Scene.GetObjectsToRez(rezAsset.Data, attachment, out objlist, out veclist, out bbox, out offsetHeight);
if (single)
{
pos = m_Scene.GetNewRezLocation(
RayStart, RayEnd, RayTargetID, Quaternion.Identity,
BypassRayCast, bRayEndIsIntersection, true, bbox, false);
pos.Z += offsetHeight;
}
else
{
pos = m_Scene.GetNewRezLocation(RayStart, RayEnd,
RayTargetID, Quaternion.Identity,
BypassRayCast, bRayEndIsIntersection, true,
bbox, false);
pos -= bbox / 2;
}
if (item != null && !DoPreRezWhenFromItem(remoteClient, item, objlist, pos, veclist, attachment))
return null;
for (int i = 0; i < objlist.Count; i++)
{
group = objlist[i];
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}",
// group.Name, group.LocalId, group.UUID,
// group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask,
// remoteClient.Name);
// Vector3 storedPosition = group.AbsolutePosition;
if (group.UUID == UUID.Zero)
{
m_log.Debug("[INVENTORY ACCESS MODULE]: Object has UUID.Zero! Position 3");
}
// if this was previously an attachment and is now being rezzed,
// save the old attachment info.
if (group.IsAttachment == false && group.RootPart.Shape.State != 0)
{
group.RootPart.AttachedPos = group.AbsolutePosition;
group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint;
}
foreach (SceneObjectPart part in group.Parts)
{
// Make the rezzer the owner, as this is not necessarily set correctly in the serialized asset.
part.LastOwnerID = part.OwnerID;
part.OwnerID = remoteClient.AgentId;
}
if (!attachment)
{
// If it's rezzed in world, select it. Much easier to
// find small items.
//
foreach (SceneObjectPart part in group.Parts)
{
part.CreateSelected = true;
}
}
group.ResetIDs();
if (attachment)
{
group.RootPart.Flags |= PrimFlags.Phantom;
group.IsAttachment = true;
}
// If we're rezzing an attachment then don't ask
// AddNewSceneObject() to update the client since
// we'll be doing that later on. Scheduling more than
// one full update during the attachment
// process causes some clients to fail to display the
// attachment properly.
m_Scene.AddNewSceneObject(group, true, false);
// if attachment we set it's asset id so object updates
// can reflect that, if not, we set it's position in world.
if (!attachment)
{
group.ScheduleGroupForFullUpdate();
group.AbsolutePosition = pos + veclist[i];
}
group.SetGroup(remoteClient.ActiveGroupId, remoteClient);
if (!attachment)
{
SceneObjectPart rootPart = group.RootPart;
if (rootPart.Shape.PCode == (byte)PCode.Prim)
group.ClearPartAttachmentData();
// Fire on_rez
group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1);
rootPart.ParentGroup.ResumeScripts();
rootPart.ScheduleFullUpdate();
}
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}",
// group.Name, group.LocalId, group.UUID,
// group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask,
// remoteClient.Name);
}
if (item != null)
DoPostRezWhenFromItem(item, attachment);
return group;
}
/// <summary>
/// Do pre-rez processing when the object comes from an item.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="item"></param>
/// <param name="objlist"></param>
/// <param name="pos"></param>
/// <param name="veclist">
/// List of vector position adjustments for a coalesced objects. For ordinary objects
/// this list will contain just Vector3.Zero. The order of adjustments must match the order of objlist
/// </param>
/// <param name="isAttachment"></param>
/// <returns>true if we can processed with rezzing, false if we need to abort</returns>
private bool DoPreRezWhenFromItem(
IClientAPI remoteClient, InventoryItemBase item, List<SceneObjectGroup> objlist,
Vector3 pos, List<Vector3> veclist, bool isAttachment)
{
UUID fromUserInventoryItemId = UUID.Zero;
// If we have permission to copy then link the rezzed object back to the user inventory
// item that it came from. This allows us to enable 'save object to inventory'
if (!m_Scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy)
== (uint)PermissionMask.Copy && (item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
fromUserInventoryItemId = item.ID;
}
}
else
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
// Brave new fullperm world
fromUserInventoryItemId = item.ID;
}
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup g = objlist[i];
if (!m_Scene.Permissions.CanRezObject(
g.PrimCount, remoteClient.AgentId, pos + veclist[i])
&& !isAttachment)
{
// The client operates in no fail mode. It will
// have already removed the item from the folder
// if it's no copy.
// Put it back if it's not an attachment
//
if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!isAttachment))
remoteClient.SendBulkUpdateInventory(item);
ILandObject land = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y);
remoteClient.SendAlertMessage(string.Format(
"Can't rez object '{0}' at <{1:F3}, {2:F3}, {3:F3}> on parcel '{4}' in region {5}.",
item.Name, pos.X, pos.Y, pos.Z, land != null ? land.LandData.Name : "Unknown", m_Scene.Name));
return false;
}
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup so = objlist[i];
SceneObjectPart rootPart = so.RootPart;
// Since renaming the item in the inventory does not
// affect the name stored in the serialization, transfer
// the correct name from the inventory to the
// object itself before we rez.
//
// Only do these for the first object if we are rezzing a coalescence.
if (i == 0)
{
rootPart.Name = item.Name;
rootPart.Description = item.Description;
rootPart.ObjectSaleType = item.SaleType;
rootPart.SalePrice = item.SalePrice;
}
so.FromFolderID = item.Folder;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}",
// rootPart.OwnerID, item.Owner, item.CurrentPermissions);
if ((rootPart.OwnerID != item.Owner) ||
(item.CurrentPermissions & 16) != 0)
{
//Need to kill the for sale here
rootPart.ObjectSaleType = 0;
rootPart.SalePrice = 10;
if (m_Scene.Permissions.PropagatePermissions())
{
foreach (SceneObjectPart part in so.Parts)
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
part.EveryoneMask = item.EveryOnePermissions;
part.NextOwnerMask = item.NextPermissions;
}
part.GroupMask = 0; // DO NOT propagate here
}
so.ApplyNextOwnerPermissions();
}
}
foreach (SceneObjectPart part in so.Parts)
{
part.FromUserInventoryItemID = fromUserInventoryItemId;
if ((part.OwnerID != item.Owner) ||
(item.CurrentPermissions & 16) != 0)
{
part.Inventory.ChangeInventoryOwner(item.Owner);
part.GroupMask = 0; // DO NOT propagate here
}
part.EveryoneMask = item.EveryOnePermissions;
part.NextOwnerMask = item.NextPermissions;
}
rootPart.TrimPermissions();
if (isAttachment)
so.FromItemID = item.ID;
}
return true;
}
/// <summary>
/// Do post-rez processing when the object comes from an item.
/// </summary>
/// <param name="item"></param>
/// <param name="isAttachment"></param>
private void DoPostRezWhenFromItem(InventoryItemBase item, bool isAttachment)
{
if (!m_Scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
// If this is done on attachments, no
// copy ones will be lost, so avoid it
//
if (!isAttachment)
{
List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
m_Scene.InventoryService.DeleteItems(item.Owner, uuids);
}
}
}
}
protected void AddUserData(SceneObjectGroup sog)
{
UserManagementModule.AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData);
foreach (SceneObjectPart sop in sog.Parts)
UserManagementModule.AddUser(sop.CreatorID, sop.CreatorData);
}
public virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver)
{
}
public virtual bool CanGetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID)
{
InventoryItemBase assetRequestItem = GetItem(remoteClient.AgentId, itemID);
if (assetRequestItem == null)
{
ILibraryService lib = m_Scene.RequestModuleInterface<ILibraryService>();
if (lib != null)
assetRequestItem = lib.LibraryRootFolder.FindItem(itemID);
if (assetRequestItem == null)
return false;
}
// At this point, we need to apply perms
// only to notecards and scripts. All
// other asset types are always available
//
if (assetRequestItem.AssetType == (int)AssetType.LSLText)
{
if (!m_Scene.Permissions.CanViewScript(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view script", false);
return false;
}
}
else if (assetRequestItem.AssetType == (int)AssetType.Notecard)
{
if (!m_Scene.Permissions.CanViewNotecard(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view notecard", false);
return false;
}
}
if (assetRequestItem.AssetID != requestID)
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: {0} requested asset {1} from item {2} but this does not match item's asset {3}",
Name, requestID, itemID, assetRequestItem.AssetID);
return false;
}
return true;
}
public virtual bool IsForeignUser(UUID userID, out string assetServerURL)
{
assetServerURL = string.Empty;
return false;
}
#endregion
#region Misc
/// <summary>
/// Create a new asset data structure.
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
/// <param name="invType"></param>
/// <param name="assetType"></param>
/// <param name="data"></param>
/// <returns></returns>
private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID)
{
AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID);
asset.Description = description;
asset.Data = (data == null) ? new byte[1] : data;
return asset;
}
protected virtual InventoryItemBase GetItem(UUID agentID, UUID itemID)
{
IInventoryService invService = m_Scene.RequestModuleInterface<IInventoryService>();
InventoryItemBase item = new InventoryItemBase(itemID, agentID);
item = invService.GetItem(item);
if (item != null && item.CreatorData != null && item.CreatorData != string.Empty)
UserManagementModule.AddUser(item.CreatorIdAsUuid, item.CreatorData);
return item;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AsUInt32()
{
var test = new VectorAs__AsUInt32();
// Validates basic functionality works
test.RunBasicScenario();
// Validates basic functionality works using the generic form, rather than the type-specific form of the method
test.RunGenericScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorAs__AsUInt32
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Vector256<UInt32> value;
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<byte> byteResult = value.AsByte();
ValidateResult(byteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<double> doubleResult = value.AsDouble();
ValidateResult(doubleResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<short> shortResult = value.AsInt16();
ValidateResult(shortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<int> intResult = value.AsInt32();
ValidateResult(intResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<long> longResult = value.AsInt64();
ValidateResult(longResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<sbyte> sbyteResult = value.AsSByte();
ValidateResult(sbyteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<float> floatResult = value.AsSingle();
ValidateResult(floatResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<ushort> ushortResult = value.AsUInt16();
ValidateResult(ushortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<uint> uintResult = value.AsUInt32();
ValidateResult(uintResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<ulong> ulongResult = value.AsUInt64();
ValidateResult(ulongResult, value);
}
public void RunGenericScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario));
Vector256<UInt32> value;
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<byte> byteResult = value.As<UInt32, byte>();
ValidateResult(byteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<double> doubleResult = value.As<UInt32, double>();
ValidateResult(doubleResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<short> shortResult = value.As<UInt32, short>();
ValidateResult(shortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<int> intResult = value.As<UInt32, int>();
ValidateResult(intResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<long> longResult = value.As<UInt32, long>();
ValidateResult(longResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<sbyte> sbyteResult = value.As<UInt32, sbyte>();
ValidateResult(sbyteResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<float> floatResult = value.As<UInt32, float>();
ValidateResult(floatResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<ushort> ushortResult = value.As<UInt32, ushort>();
ValidateResult(ushortResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<uint> uintResult = value.As<UInt32, uint>();
ValidateResult(uintResult, value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
Vector256<ulong> ulongResult = value.As<UInt32, ulong>();
ValidateResult(ulongResult, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Vector256<UInt32> value;
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object byteResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsByte))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<byte>)(byteResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object doubleResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsDouble))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<double>)(doubleResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object shortResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsInt16))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<short>)(shortResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object intResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsInt32))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<int>)(intResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object longResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsInt64))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<long>)(longResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object sbyteResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsSByte))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<sbyte>)(sbyteResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object floatResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsSingle))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<float>)(floatResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object ushortResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsUInt16))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<ushort>)(ushortResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object uintResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsUInt32))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<uint>)(uintResult), value);
value = Vector256.Create(TestLibrary.Generator.GetUInt32());
object ulongResult = typeof(Vector256)
.GetMethod(nameof(Vector256.AsUInt64))
.MakeGenericMethod(typeof(UInt32))
.Invoke(null, new object[] { value });
ValidateResult((Vector256<ulong>)(ulongResult), value);
}
private void ValidateResult<T>(Vector256<T> result, Vector256<UInt32> value, [CallerMemberName] string method = "")
where T : struct
{
UInt32[] resultElements = new UInt32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result);
UInt32[] valueElements = new UInt32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, typeof(T), method);
}
private void ValidateResult(UInt32[] resultElements, UInt32[] valueElements, Type targetType, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<UInt32>.As{targetType.Name}: {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Scriban.Helpers;
using Scriban.Runtime;
using Scriban.Syntax;
namespace Scriban.Parsing
{
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
partial class Parser
{
private void ParseScribanStatement(string identifier, ScriptStatement parent, bool parseEndOfStatementAfterEnd, ref ScriptStatement statement, ref bool hasEnd, ref bool nextStatement)
{
var startToken = Current;
switch (identifier)
{
case "end":
hasEnd = true;
statement = ParseEndStatement(parseEndOfStatementAfterEnd);
break;
case "wrap":
CheckNotInCase(parent, startToken);
statement = ParseWrapStatement();
break;
case "if":
CheckNotInCase(parent, startToken);
statement = ParseIfStatement(false, null);
break;
case "case":
CheckNotInCase(parent, startToken);
statement = ParseCaseStatement();
break;
case "when":
var whenStatement = ParseWhenStatement();
var whenParent = parent as ScriptConditionStatement;
if (parent is ScriptWhenStatement)
{
((ScriptWhenStatement)whenParent).Next = whenStatement;
}
else if (parent is ScriptCaseStatement)
{
statement = whenStatement;
}
else
{
nextStatement = false;
// unit test: TODO
LogError(startToken, "A `when` condition must be preceded by another `when`/`else`/`case` condition");
}
hasEnd = true;
break;
case "else":
var nextCondition = ParseElseStatement(false);
var parentCondition = parent as ScriptConditionStatement;
if (parent is ScriptIfStatement || parent is ScriptWhenStatement)
{
if (parent is ScriptIfStatement)
{
((ScriptIfStatement)parentCondition).Else = nextCondition;
}
else
{
((ScriptWhenStatement)parentCondition).Next = nextCondition;
}
}
else if (parent is ScriptForStatement forStatement)
{
forStatement.Else = (ScriptElseStatement)nextCondition;
}
else
{
nextStatement = false;
// unit test: 201-if-else-error3.txt
LogError(startToken, "A else condition must be preceded by another if/else/when condition or a for loop.");
}
hasEnd = true;
break;
case "for":
CheckNotInCase(parent, startToken);
if (PeekToken().Type == TokenType.Dot)
{
statement = ParseExpressionStatement();
}
else
{
statement = ParseForStatement<ScriptForStatement>();
}
break;
case "tablerow":
if (_isScientific) goto default;
CheckNotInCase(parent, startToken);
if (PeekToken().Type == TokenType.Dot)
{
statement = ParseExpressionStatement();
}
else
{
statement = ParseForStatement<ScriptTableRowStatement>();
}
break;
case "with":
CheckNotInCase(parent, startToken);
statement = ParseWithStatement();
break;
case "import":
CheckNotInCase(parent, startToken);
statement = ParseImportStatement();
break;
case "readonly":
CheckNotInCase(parent, startToken);
statement = ParseReadOnlyStatement();
break;
case "while":
CheckNotInCase(parent, startToken);
if (PeekToken().Type == TokenType.Dot)
{
statement = ParseExpressionStatement();
}
else
{
statement = ParseWhileStatement();
}
break;
case "break":
CheckNotInCase(parent, startToken);
var breakStatement = Open<ScriptBreakStatement>();
statement = breakStatement;
ExpectAndParseKeywordTo(breakStatement.BreakKeyword); // Parse break
ExpectEndOfStatement();
Close(statement);
// This has to be done at execution time, because of the wrap statement
//if (!IsInLoop())
//{
// LogError(statement, "Unexpected statement outside of a loop");
//}
break;
case "continue":
CheckNotInCase(parent, startToken);
var continueStatement = Open<ScriptContinueStatement>();
statement = continueStatement;
ExpectAndParseKeywordTo(continueStatement.ContinueKeyword); // Parse continue keyword
ExpectEndOfStatement();
Close(statement);
// This has to be done at execution time, because of the wrap statement
//if (!IsInLoop())
//{
// LogError(statement, "Unexpected statement outside of a loop");
//}
break;
case "func":
CheckNotInCase(parent, startToken);
statement = ParseFunctionStatement(false);
break;
case "ret":
CheckNotInCase(parent, startToken);
statement = ParseReturnStatement();
break;
case "capture":
CheckNotInCase(parent, startToken);
statement = ParseCaptureStatement();
break;
default:
CheckNotInCase(parent, startToken);
// Otherwise it is an expression statement
statement = ParseExpressionStatement();
break;
}
}
private ScriptEndStatement ParseEndStatement(bool parseEndOfStatementAfterEnd)
{
var endStatement = Open<ScriptEndStatement>();
ExpectAndParseKeywordTo(endStatement.EndKeyword);
if (parseEndOfStatementAfterEnd)
{
ExpectEndOfStatement();
}
return Close(endStatement);
}
private ScriptFunction ParseFunctionStatement(bool isAnonymous)
{
var scriptFunction = Open<ScriptFunction>();
var previousExpressionLevel = _expressionLevel;
try
{
// Reset expression level when parsing
_expressionLevel = 0;
if (isAnonymous)
{
scriptFunction.NameOrDoToken = ExpectAndParseKeywordTo(ScriptKeyword.Do());
}
else
{
scriptFunction.FuncToken = ExpectAndParseKeywordTo(ScriptKeyword.Func());
scriptFunction.NameOrDoToken = ExpectAndParseVariable(scriptFunction);
}
// If we have parenthesis, this is a function with explicit parameters
if (Current.Type == TokenType.OpenParen)
{
scriptFunction.OpenParen = ParseToken(TokenType.OpenParen);
var parameters = new ScriptList<ScriptParameter>();
bool hasTripleDot = false;
bool hasOptionals = false;
bool isFirst = true;
while (true)
{
// Parse any required comma (before each new non-first argument)
// Or closing parent (and we exit the loop)
if (Current.Type == TokenType.CloseParen)
{
scriptFunction.CloseParen = ParseToken(TokenType.CloseParen);
scriptFunction.Span.End = scriptFunction.CloseParen.Span.End;
break;
}
if (!isFirst)
{
if (Current.Type == TokenType.Comma)
{
PushTokenToTrivia();
NextToken();
FlushTriviasToLastTerminal();
}
else
{
LogError(Current, "Expecting a comma to separate arguments in a function call.");
}
}
isFirst = false;
// Else we expect an expression
if (IsStartOfExpression())
{
var parameter = Open<ScriptParameter>();
var arg = ExpectAndParseVariable(scriptFunction);
if (!(arg is ScriptVariableGlobal))
{
if (arg == null)
break;
LogError(arg.Span, "Expecting only a simple name parameter for a function");
}
parameter.Name = arg;
if (Current.Type == TokenType.Equal)
{
if (hasTripleDot)
{
LogError(arg.Span, "Cannot declare an optional parameter after a variable parameter (`...`).");
}
hasOptionals = true;
parameter.EqualOrTripleDotToken = ScriptToken.Equal();
ExpectAndParseTokenTo(parameter.EqualOrTripleDotToken, TokenType.Equal);
parameter.Span.End = parameter.EqualOrTripleDotToken.Span.End;
var defaultValue = ExpectAndParseExpression(parameter);
if (defaultValue is ScriptLiteral literal)
{
parameter.DefaultValue = literal;
parameter.Span.End = literal.Span.End;
}
else
{
LogError(arg.Span, "Expecting only a literal for an optional parameter value.");
}
}
else if (Current.Type == TokenType.TripleDot)
{
if (hasTripleDot)
{
LogError(arg.Span, "Cannot declare multiple variable parameters.");
}
hasTripleDot = true;
hasOptionals = true;
parameter.EqualOrTripleDotToken = ScriptToken.TripleDot();
ExpectAndParseTokenTo(parameter.EqualOrTripleDotToken, TokenType.TripleDot);
parameter.Span.End = parameter.EqualOrTripleDotToken.Span.End;
}
else if (hasOptionals)
{
LogError(arg.Span, "Cannot declare a normal parameter after an optional parameter.");
}
parameters.Add(parameter);
scriptFunction.Span.End = parameter.Span.End;
}
else
{
LogError(Current, "Expecting an expression for argument function calls instead of this token.");
break;
}
}
if (scriptFunction.CloseParen == null)
{
LogError(Current, "Expecting a closing parenthesis for a function call.");
}
// Setup parameters once they have been all parsed
scriptFunction.Parameters = parameters;
}
ExpectEndOfStatement();
// If the function is anonymous we don't expect an EOS after the `end`
scriptFunction.Body = ParseBlockStatement(scriptFunction, !isAnonymous);
}
finally
{
_expressionLevel = previousExpressionLevel;
}
return Close(scriptFunction);
}
private ScriptImportStatement ParseImportStatement()
{
var importStatement = Open<ScriptImportStatement>();
ExpectAndParseKeywordTo(importStatement.ImportKeyword); // Parse import keyword
importStatement.Expression = ExpectAndParseExpression(importStatement);
ExpectEndOfStatement();
return Close(importStatement);
}
private ScriptReadOnlyStatement ParseReadOnlyStatement()
{
var readOnlyStatement = Open<ScriptReadOnlyStatement>();
ExpectAndParseKeywordTo(readOnlyStatement.ReadOnlyKeyword); // Parse readonly keyword
readOnlyStatement.Variable = ExpectAndParseVariable(readOnlyStatement);
ExpectEndOfStatement();
return Close(readOnlyStatement);
}
private ScriptReturnStatement ParseReturnStatement()
{
var ret = Open<ScriptReturnStatement>();
ExpectAndParseKeywordTo(ret.RetKeyword); // Parse ret keyword
if (IsStartOfExpression())
{
ret.Expression = ParseExpression(ret);
}
ExpectEndOfStatement();
return Close(ret);
}
private ScriptWhileStatement ParseWhileStatement()
{
var whileStatement = Open<ScriptWhileStatement>();
ExpectAndParseKeywordTo(whileStatement.WhileKeyword); // Parse while keyword
// Parse the condition
// unit test: 220-while-error1.txt
whileStatement.Condition = ExpectAndParseExpression(whileStatement, allowAssignment: false);
if (ExpectEndOfStatement())
{
whileStatement.Body = ParseBlockStatement(whileStatement);
}
return Close(whileStatement);
}
private ScriptWithStatement ParseWithStatement()
{
var withStatement = Open<ScriptWithStatement>();
ExpectAndParseKeywordTo(withStatement.WithKeyword); // // Parse with keyword
withStatement.Name = ExpectAndParseExpression(withStatement);
if (ExpectEndOfStatement())
{
withStatement.Body = ParseBlockStatement(withStatement);
}
return Close(withStatement);
}
private ScriptWrapStatement ParseWrapStatement()
{
var wrapStatement = Open<ScriptWrapStatement>();
ExpectAndParseKeywordTo(wrapStatement.WrapKeyword); // Parse wrap keyword
wrapStatement.Target = ExpectAndParseExpression(wrapStatement);
if (ExpectEndOfStatement())
{
wrapStatement.Body = ParseBlockStatement(wrapStatement);
}
return Close(wrapStatement);
}
private void FixRawStatementAfterFrontMatter(ScriptPage page)
{
// In case of parsing a front matter, we don't want to include any \r\n after the end of the front-matter
// So we manipulate back the syntax tree for the expected raw statement (if any), otherwise we can early
// exit.
var rawStatement = page.Body.Statements.FirstOrDefault() as ScriptRawStatement;
if (rawStatement == null)
{
return;
}
rawStatement.Text = rawStatement.Text.TrimStart();
}
private static bool IsScribanKeyword(string text)
{
switch (text)
{
case "if":
case "else":
case "end":
case "for":
case "case":
case "when":
case "while":
case "break":
case "continue":
case "func":
case "import":
case "readonly":
case "with":
case "capture":
case "ret":
case "wrap":
case "do":
return true;
}
return false;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
public struct VT
{
public long[,] long2darr;
public long[, ,] long3darr;
public long[,] long2darr_b;
public long[, ,] long3darr_b;
public long[,] long2darr_c;
public long[, ,] long3darr_c;
}
public class CL
{
public long[,] long2darr = { { 0, -1 }, { 0, 0 } };
public long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
public long[,] long2darr_b = { { 0, 1 }, { 0, 0 } };
public long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
public long[,] long2darr_c = { { 0, 49 }, { 0, 0 } };
public long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
}
public class longMDArrTest
{
static long[,] long2darr = { { 0, -1 }, { 0, 0 } };
static long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
static long[,] long2darr_b = { { 0, 1 }, { 0, 0 } };
static long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
static long[,] long2darr_c = { { 0, 49 }, { 0, 0 } };
static long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
static long[][,] ja1 = new long[2][,];
static long[][, ,] ja2 = new long[2][, ,];
static long[][,] ja1_b = new long[2][,];
static long[][, ,] ja2_b = new long[2][, ,];
static long[][,] ja1_c = new long[2][,];
static long[][, ,] ja2_c = new long[2][, ,];
public static int Main()
{
bool pass = true;
VT vt1;
vt1.long2darr = new long[,] { { 0, -1 }, { 0, 0 } };
vt1.long3darr = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
vt1.long2darr_b = new long[,] { { 0, 1 }, { 0, 0 } };
vt1.long3darr_b = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
vt1.long2darr_c = new long[,] { { 0, 49 }, { 0, 0 } };
vt1.long3darr_c = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
CL cl1 = new CL();
ja1[0] = new long[,] { { 0, -1 }, { 0, 0 } };
ja2[1] = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
ja1_b[0] = new long[,] { { 0, 1 }, { 0, 0 } };
ja2_b[1] = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
ja1_c[0] = new long[,] { { 0, 49 }, { 0, 0 } };
ja2_c[1] = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
long result = -1;
// 2D
if (result != long2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.long2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.long2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja1[0][0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (result != long3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.long3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.long3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja2[1][1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToBool
bool Bool_result = true;
// 2D
if (Bool_result != Convert.ToBoolean(long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Bool_result != Convert.ToBoolean(long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToByte tests
byte Byte_result = 1;
// 2D
if (Byte_result != Convert.ToByte(long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Byte_result != Convert.ToByte(long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToChar tests
char Char_result = '1';
// 2D
if (Char_result != Convert.ToChar(long2darr_c[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr_c[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.long2darr_c[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.long2darr_c[0, 1] is: {0}", vt1.long2darr_c[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.long2darr_c[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.long2darr_c[0, 1] is: {0}", cl1.long2darr_c[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja1_c[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja1_c[0][0, 1] is: {0}", ja1_c[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Char_result != Convert.ToChar(long3darr_c[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("long3darr_c[1,0,1] is: {0}", long3darr_c[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.long3darr_c[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.long3darr_c[1,0,1] is: {0}", vt1.long3darr_c[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.long3darr_c[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.long3darr_c[1,0,1] is: {0}", cl1.long3darr_c[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja2_c[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja2_c[1][1,0,1] is: {0}", ja2_c[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToDecimal tests
decimal Decimal_result = -1;
// 2D
if (Decimal_result != Convert.ToDecimal(long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Decimal_result != Convert.ToDecimal(long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToDouble
double Double_result = -1;
// 2D
if (Double_result != Convert.ToDouble(long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Double_result != Convert.ToDouble(long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToSingle tests
float Single_result = -1;
// 2D
if (Single_result != Convert.ToSingle(long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Single_result != Convert.ToSingle(long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToInt32 tests
int Int32_result = -1;
// 2D
if (Int32_result != Convert.ToInt32(long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int32_result != Convert.ToInt32(long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToSByte tests
sbyte SByte_result = -1;
// 2D
if (SByte_result != Convert.ToSByte(long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (SByte_result != Convert.ToSByte(long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToInt16 tests
short Int16_result = -1;
// 2D
if (Int16_result != Convert.ToInt16(long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(vt1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(cl1.long2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int16_result != Convert.ToInt16(long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(vt1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(cl1.long3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToUInt32 tests
uint UInt32_result = 1;
// 2D
if (UInt32_result != Convert.ToUInt32(long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt32_result != Convert.ToUInt32(long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToUInt64 tests
ulong UInt64_result = 1;
// 2D
if (UInt64_result != Convert.ToUInt64(long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt64_result != Convert.ToUInt64(long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int64ToUInt16 tests
ushort UInt16_result = 1;
// 2D
if (UInt16_result != Convert.ToUInt16(long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.long2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt16_result != Convert.ToUInt16(long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.long3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (!pass)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
};
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Base class for the various types of formatting shapes.
/// </summary>
internal abstract class ViewGenerator
{
internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext,
PSPropertyExpressionFactory mshExpressionFactory,
TypeInfoDataBase db,
ViewDefinition view,
FormattingCommandLineParameters formatParameters)
{
Diagnostics.Assert(mshExpressionFactory != null, "mshExpressionFactory cannot be null");
Diagnostics.Assert(db != null, "db cannot be null");
Diagnostics.Assert(view != null, "view cannot be null");
errorContext = terminatingErrorContext;
expressionFactory = mshExpressionFactory;
parameters = formatParameters;
dataBaseInfo.db = db;
dataBaseInfo.view = view;
dataBaseInfo.applicableTypes = DisplayDataQuery.GetAllApplicableTypes(db, view.appliesTo);
InitializeHelper();
}
internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext,
PSPropertyExpressionFactory mshExpressionFactory,
PSObject so,
TypeInfoDataBase db,
FormattingCommandLineParameters formatParameters)
{
errorContext = terminatingErrorContext;
expressionFactory = mshExpressionFactory;
parameters = formatParameters;
dataBaseInfo.db = db;
InitializeHelper();
}
/// <summary>
/// Let the view prepare itself for RemoteObjects. Specific view generators can
/// use this call to customize display for remote objects like showing/hiding
/// computername property etc.
/// </summary>
/// <param name="so"></param>
internal virtual void PrepareForRemoteObjects(PSObject so)
{
}
private void InitializeHelper()
{
InitializeFormatErrorManager();
InitializeGroupBy();
InitializeAutoSize();
InitializeRepeatHeader();
}
private void InitializeFormatErrorManager()
{
FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy();
if (parameters != null && parameters.showErrorsAsMessages.HasValue)
{
formatErrorPolicy.ShowErrorsAsMessages = parameters.showErrorsAsMessages.Value;
}
else
{
formatErrorPolicy.ShowErrorsAsMessages = this.dataBaseInfo.db.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages;
}
if (parameters != null && parameters.showErrorsInFormattedOutput.HasValue)
{
formatErrorPolicy.ShowErrorsInFormattedOutput = parameters.showErrorsInFormattedOutput.Value;
}
else
{
formatErrorPolicy.ShowErrorsInFormattedOutput = this.dataBaseInfo.db.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput;
}
_errorManager = new FormatErrorManager(formatErrorPolicy);
}
private void InitializeGroupBy()
{
// first check if there is an override from the command line
if (parameters != null && parameters.groupByParameter != null)
{
// get the expression to use
PSPropertyExpression groupingKeyExpression = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
// set the label
string label = null;
object labelKey = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey);
if (labelKey != AutomationNull.Value)
{
label = labelKey as string;
}
_groupingManager = new GroupingInfoManager();
_groupingManager.Initialize(groupingKeyExpression, label);
return;
}
// check if we have a view to initialize from
if (this.dataBaseInfo.view != null)
{
GroupBy gb = this.dataBaseInfo.view.groupBy;
if (gb == null)
{
return;
}
if (gb.startGroup == null || gb.startGroup.expression == null)
{
return;
}
PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(gb.startGroup.expression, this.dataBaseInfo.view.loadingInfo);
_groupingManager = new GroupingInfoManager();
_groupingManager.Initialize(ex, null);
}
}
private void InitializeAutoSize()
{
// check the autosize flag first
if (parameters != null && parameters.autosize.HasValue)
{
_autosize = parameters.autosize.Value;
return;
}
// check if we have a view with autosize checked
if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null)
{
ControlBody controlBody = this.dataBaseInfo.view.mainControl as ControlBody;
if (controlBody != null && controlBody.autosize.HasValue)
{
_autosize = controlBody.autosize.Value;
}
}
}
private void InitializeRepeatHeader()
{
if (parameters != null)
{
_repeatHeader = parameters.repeatHeader;
}
}
internal virtual FormatStartData GenerateStartData(PSObject so)
{
FormatStartData startFormat = new FormatStartData();
if (_autosize)
{
startFormat.autosizeInfo = new AutosizeInfo();
}
return startFormat;
}
internal abstract FormatEntryData GeneratePayload(PSObject so, int enumerationLimit);
internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int enumerationLimit)
{
GroupStartData startGroup = new GroupStartData();
if (_groupingManager == null)
return startGroup;
object currentGroupingValue = _groupingManager.CurrentGroupingKeyPropertyValue;
if (currentGroupingValue == AutomationNull.Value)
return startGroup;
PSObject so = PSObjectHelper.AsPSObject(currentGroupingValue);
// we need to determine how to display the group header
ControlBase control = null;
TextToken labelTextToken = null;
if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.groupBy != null)
{
if (this.dataBaseInfo.view.groupBy.startGroup != null)
{
// NOTE: from the database constraints, only one of the
// two will be non null
control = this.dataBaseInfo.view.groupBy.startGroup.control;
labelTextToken = this.dataBaseInfo.view.groupBy.startGroup.labelTextToken;
}
}
startGroup.groupingEntry = new GroupingEntry();
if (control == null)
{
// we do not have a control, we auto generate a
// snippet of complex display using a label
StringFormatError formatErrorObject = null;
if (_errorManager.DisplayFormatErrorString)
{
// we send a format error object down to the formatting calls
// only if we want to show the formatting error strings
formatErrorObject = new StringFormatError();
}
string currentGroupingValueDisplay = PSObjectHelper.SmartToString(so, this.expressionFactory, enumerationLimit, formatErrorObject);
if (formatErrorObject != null && formatErrorObject.exception != null)
{
// if we did no thave any errors in the expression evaluation
// we might have errors in the formatting, if present
_errorManager.LogStringFormatError(formatErrorObject);
if (_errorManager.DisplayFormatErrorString)
{
currentGroupingValueDisplay = _errorManager.FormatErrorString;
}
}
FormatEntry fe = new FormatEntry();
startGroup.groupingEntry.formatValueList.Add(fe);
FormatTextField ftf = new FormatTextField();
// determine what the label should be. If we have a label from the
// database, let's use it, else fall back to the string provided
// by the grouping manager
string label;
if (labelTextToken != null)
label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(labelTextToken);
else
label = _groupingManager.GroupingKeyDisplayName;
ftf.text = StringUtil.Format(FormatAndOut_format_xxx.GroupStartDataIndentedAutoGeneratedLabel, label);
fe.formatValueList.Add(ftf);
FormatPropertyField fpf = new FormatPropertyField();
fpf.propertyValue = currentGroupingValueDisplay;
fe.formatValueList.Add(fpf);
}
else
{
// NOTE: we set a max depth to protect ourselves from infinite loops
const int maxTreeDepth = 50;
ComplexControlGenerator controlGenerator =
new ComplexControlGenerator(this.dataBaseInfo.db,
this.dataBaseInfo.view.loadingInfo,
this.expressionFactory,
this.dataBaseInfo.view.formatControlDefinitionHolder.controlDefinitionList,
this.ErrorManager,
enumerationLimit,
this.errorContext);
controlGenerator.GenerateFormatEntries(maxTreeDepth,
control, firstObjectInGroup, startGroup.groupingEntry.formatValueList);
}
return startGroup;
}
/// <summary>
/// Update the current value of the grouping key.
/// </summary>
/// <param name="so">Object to use for the update.</param>
/// <returns>True if the value of the key changed.</returns>
internal bool UpdateGroupingKeyValue(PSObject so)
{
if (_groupingManager == null)
return false;
return _groupingManager.UpdateGroupingKeyValue(so);
}
internal GroupEndData GenerateGroupEndData()
{
return new GroupEndData();
}
internal bool IsObjectApplicable(Collection<string> typeNames)
{
if (dataBaseInfo.view == null)
return true;
if (typeNames.Count == 0)
return false;
TypeMatch match = new TypeMatch(expressionFactory, dataBaseInfo.db, typeNames);
if (match.PerfectMatch(new TypeMatchItem(this, dataBaseInfo.applicableTypes)))
{
return true;
}
bool result = match.BestMatch != null;
// we were unable to find a best match so far..try
// to get rid of Deserialization prefix and see if a
// match can be found.
if (false == result)
{
Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames);
if (typesWithoutPrefix != null)
{
result = IsObjectApplicable(typesWithoutPrefix);
}
}
return result;
}
private GroupingInfoManager _groupingManager = null;
protected bool AutoSize
{
get { return _autosize; }
}
private bool _autosize = false;
protected bool RepeatHeader
{
get { return _repeatHeader; }
}
private bool _repeatHeader = false;
protected class DataBaseInfo
{
internal TypeInfoDataBase db = null;
internal ViewDefinition view = null;
internal AppliesTo applicableTypes = null;
}
protected TerminatingErrorContext errorContext;
protected FormattingCommandLineParameters parameters;
protected PSPropertyExpressionFactory expressionFactory;
protected DataBaseInfo dataBaseInfo = new DataBaseInfo();
protected List<MshResolvedExpressionParameterAssociation> activeAssociationList = null;
protected FormattingCommandLineParameters inputParameters = null;
protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PSPropertyExpression ex,
FieldFormattingDirective directive)
{
PSPropertyExpressionResult resolvedExpression;
return GetExpressionDisplayValue(so, enumerationLimit, ex, directive, out resolvedExpression);
}
protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PSPropertyExpression ex,
FieldFormattingDirective directive, out PSPropertyExpressionResult expressionResult)
{
StringFormatError formatErrorObject = null;
if (_errorManager.DisplayFormatErrorString)
{
// we send a format error object down to the formatting calls
// only if we want to show the formatting error strings
formatErrorObject = new StringFormatError();
}
string retVal = PSObjectHelper.GetExpressionDisplayValue(so, enumerationLimit, ex,
directive, formatErrorObject, expressionFactory, out expressionResult);
if (expressionResult != null)
{
// we obtained a result, check if there is an error
if (expressionResult.Exception != null)
{
_errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so);
if (_errorManager.DisplayErrorStrings)
{
retVal = _errorManager.ErrorString;
}
}
else if (formatErrorObject != null && formatErrorObject.exception != null)
{
// if we did no thave any errors in the expression evaluation
// we might have errors in the formatting, if present
_errorManager.LogStringFormatError(formatErrorObject);
if (_errorManager.DisplayErrorStrings)
{
retVal = _errorManager.FormatErrorString;
}
}
}
return retVal;
}
protected bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToken)
{
if (conditionToken == null)
return true;
PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(conditionToken, this.dataBaseInfo.view.loadingInfo);
PSPropertyExpressionResult expressionResult;
bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult);
if (expressionResult != null && expressionResult.Exception != null)
{
_errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so);
}
return retVal;
}
internal FormatErrorManager ErrorManager
{
get { return _errorManager; }
}
private FormatErrorManager _errorManager;
#region helpers
protected FormatPropertyField GenerateFormatPropertyField(List<FormatToken> formatTokenList, PSObject so, int enumerationLimit)
{
PSPropertyExpressionResult result;
return GenerateFormatPropertyField(formatTokenList, so, enumerationLimit, out result);
}
protected FormatPropertyField GenerateFormatPropertyField(List<FormatToken> formatTokenList, PSObject so, int enumerationLimit, out PSPropertyExpressionResult result)
{
result = null;
FormatPropertyField fpf = new FormatPropertyField();
if (formatTokenList.Count != 0)
{
FormatToken token = formatTokenList[0];
FieldPropertyToken fpt = token as FieldPropertyToken;
if (fpt != null)
{
PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo);
fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result);
}
else
{
TextToken tt = token as TextToken;
if (tt != null)
fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt);
}
}
else
{
fpf.propertyValue = string.Empty;
}
return fpf;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.Tests
{
public static class DateTimeTests
{
[Fact]
public static void MaxValue()
{
VerifyDateTime(DateTime.MaxValue, 9999, 12, 31, 23, 59, 59, 999, DateTimeKind.Unspecified);
}
[Fact]
public static void MinValue()
{
VerifyDateTime(DateTime.MinValue, 1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Long()
{
VerifyDateTime(new DateTime(999999999999999999), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Long_InvalidTicks_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MinValue.Ticks - 1)); // Ticks < DateTime.MinValue.Ticks
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MaxValue.Ticks + 1)); // Ticks > DateTime.MaxValue.Ticks
}
[Fact]
public static void Ctor_Long_DateTimeKind()
{
VerifyDateTime(new DateTime(999999999999999999, DateTimeKind.Utc), 3169, 11, 16, 9, 46, 39, 999, DateTimeKind.Utc);
}
[Fact]
public static void Ctor_Long_DateTimeKind_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MinValue.Ticks - 1, DateTimeKind.Utc)); // Ticks < DateTime.MinValue.Ticks
AssertExtensions.Throws<ArgumentOutOfRangeException>("ticks", () => new DateTime(DateTime.MaxValue.Ticks + 1, DateTimeKind.Utc)); // Ticks > DateTime.MaxValue.Ticks
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(0, DateTimeKind.Unspecified - 1)); // Invalid date time kind
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(0, DateTimeKind.Local + 1)); // Invalid date time kind
}
[Fact]
public static void Ctor_Int_Int_Int()
{
var dateTime = new DateTime(2012, 6, 11);
VerifyDateTime(dateTime, 2012, 6, 11, 0, 0, 0, 0, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Int_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1)); // Year < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1)); // Year > 9999
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1)); // Month < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1)); // Month > 12
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0)); // Day < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32)); // Day > days in month
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int()
{
var dateTime = new DateTime(2012, 12, 31, 13, 50, 10);
VerifyDateTime(dateTime, 2012, 12, 31, 13, 50, 10, 0, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1)); // Year < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1)); // Year > 9999
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1)); // Month < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1)); // Month > 12
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1)); // Day < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1)); // Day > days in month
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1)); // Hour < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1)); // Hour > 23
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1)); // Minute < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1)); // Minute > 59
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1)); // Second < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60)); // Second > 59
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Int_DateTimeKind()
{
var dateTime = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local);
VerifyDateTime(dateTime, 1986, 8, 15, 10, 20, 5, 0, DateTimeKind.Local);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_DateTimeKind_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year > 9999
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1, DateTimeKind.Utc)); // Month < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1, DateTimeKind.Utc)); // Month > 12
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1, DateTimeKind.Utc)); // Day < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1, DateTimeKind.Utc)); // Day > days in month
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1, DateTimeKind.Utc)); // Hour < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1, DateTimeKind.Utc)); // Hour > 23
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1, DateTimeKind.Utc)); // Minute < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1, DateTimeKind.Utc)); // Minute > 59
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1, DateTimeKind.Utc)); // Second < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60, DateTimeKind.Utc)); // Second > 59
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, DateTimeKind.Unspecified - 1)); // Invalid date time kind
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, DateTimeKind.Local + 1)); // Invalid date time kind
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Int()
{
var dateTime = new DateTime(1973, 10, 6, 14, 30, 0, 500);
VerifyDateTime(dateTime, 1973, 10, 6, 14, 30, 0, 500, DateTimeKind.Unspecified);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1, 1)); // Year < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1, 1)); // Year > 9999
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1, 1)); // Month < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1, 1)); // Month > 12
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1, 1)); // Day < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1, 1)); // Day > days in month
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1, 1)); // Hour < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1, 1)); // Hour > 23
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1, 1)); // Minute < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1, 1)); // Minute > 59
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1, 1)); // Second < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60, 1)); // Second > 59
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, -1)); // Milisecond < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, 1000)); // Millisecond > 999
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Int_Int_DateTimeKind()
{
var dateTime = new DateTime(1986, 8, 15, 10, 20, 5, 600, DateTimeKind.Local);
VerifyDateTime(dateTime, 1986, 8, 15, 10, 20, 5, 600, DateTimeKind.Local);
}
[Fact]
public static void Ctor_Int_Int_Int_Int_Int_Int_Int_DateTimeKind_Invalid()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(0, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year < 1
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(10000, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Year > 9999
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 0, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Month < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 13, 1, 1, 1, 1, 1, DateTimeKind.Utc)); // Month > 12
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 0, 1, 1, 1, 1, DateTimeKind.Utc)); // Day < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 32, 1, 1, 1, 1, DateTimeKind.Utc)); // Day > days in month
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, -1, 1, 1, 1, DateTimeKind.Utc)); // Hour < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 24, 1, 1, 1, DateTimeKind.Utc)); // Hour > 23
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, -1, 1, 1, DateTimeKind.Utc)); // Minute < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 60, 1, 1, DateTimeKind.Utc)); // Minute > 59
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, -1, 1, DateTimeKind.Utc)); // Second < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => new DateTime(1, 1, 1, 1, 1, 60, 1, DateTimeKind.Utc)); // Second > 59
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, -1, DateTimeKind.Utc)); // Millisecond < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("millisecond", () => new DateTime(1, 1, 1, 1, 1, 1, 1000, DateTimeKind.Utc)); // Millisecond > 999
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, DateTimeKind.Unspecified - 1)); // Invalid date time kind
AssertExtensions.Throws<ArgumentException>("kind", () => new DateTime(1, 1, 1, 1, 1, 1, 1, DateTimeKind.Local + 1)); // Invalid date time kind
}
[Theory]
[InlineData(2004, true)]
[InlineData(2005, false)]
public static void IsLeapYear(int year, bool expected)
{
Assert.Equal(expected, DateTime.IsLeapYear(year));
}
[Fact]
public static void IsLeapYear_InvalidYear_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.IsLeapYear(0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("year", () => DateTime.IsLeapYear(10000));
}
public static IEnumerable<object[]> Add_TimeSpan_TestData()
{
yield return new object[] { new DateTime(1000), new TimeSpan(10), new DateTime(1010) };
yield return new object[] { new DateTime(1000), TimeSpan.Zero, new DateTime(1000) };
yield return new object[] { new DateTime(1000), new TimeSpan(-10), new DateTime(990) };
}
[Theory]
[MemberData(nameof(Add_TimeSpan_TestData))]
public static void Add_TimeSpan(DateTime dateTime, TimeSpan timeSpan, DateTime expected)
{
Assert.Equal(expected, dateTime.Add(timeSpan));
}
[Fact]
public static void Add_TimeSpan_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.Add(TimeSpan.FromTicks(-1)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.Add(TimeSpan.FromTicks(11)));
}
public static IEnumerable<object[]> AddYears_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1996, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1976, 8, 15, 10, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddYears_TestData))]
public static void AddYears(DateTime dateTime, int years, DateTime expected)
{
Assert.Equal(expected, dateTime.AddYears(years));
}
[Fact]
public static void AddYears_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("years", () => DateTime.Now.AddYears(10001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("years", () => DateTime.Now.AddYears(-10001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MaxValue.AddYears(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MinValue.AddYears(-1));
}
public static IEnumerable<object[]> AddMonths_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 10, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 6, 15, 10, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddMonths_TestData))]
public static void AddMonths(DateTime dateTime, int months, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMonths(months));
}
[Fact]
public static void AddMonths_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.Now.AddMonths(120001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.Now.AddMonths(-120001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MaxValue.AddMonths(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTime.MinValue.AddMonths(-1));
}
public static IEnumerable<object[]> AddDays_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 2, new DateTime(1986, 8, 17, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -2, new DateTime(1986, 8, 13, 10, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddDays_TestData))]
public static void AddDays(DateTime dateTime, double days, DateTime expected)
{
Assert.Equal(expected, dateTime.AddDays(days));
}
[Fact]
public static void AddDays_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddDays(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddDays(-1));
}
public static IEnumerable<object[]> AddHours_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 3, new DateTime(1986, 8, 15, 13, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 7, 20, 5, 70) };
}
[Theory]
[MemberData(nameof(AddHours_TestData))]
public static void AddHours(DateTime dateTime, double hours, DateTime expected)
{
Assert.Equal(expected, dateTime.AddHours(hours));
}
[Fact]
public static void AddHours_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddHours(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddHours(-1));
}
public static IEnumerable<object[]> AddMinutes_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 5, new DateTime(1986, 8, 15, 10, 25, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -5, new DateTime(1986, 8, 15, 10, 15, 5, 70) };
}
[Theory]
[MemberData(nameof(AddMinutes_TestData))]
public static void AddMinutes(DateTime dateTime, double minutes, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMinutes(minutes));
}
[Fact]
public static void AddMinutes_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddMinutes(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddMinutes(-1));
}
public static IEnumerable<object[]> AddSeconds_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 30, new DateTime(1986, 8, 15, 10, 20, 35, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -3, new DateTime(1986, 8, 15, 10, 20, 2, 70) };
}
[Theory]
[MemberData(nameof(AddSeconds_TestData))]
public static void AddSeconds(DateTime dateTime, double seconds, DateTime expected)
{
Assert.Equal(expected, dateTime.AddSeconds(seconds));
}
[Fact]
public static void AddSeconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddSeconds(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddSeconds(-1));
}
public static IEnumerable<object[]> AddMilliseconds_TestData()
{
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 10, new DateTime(1986, 8, 15, 10, 20, 5, 80) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), 0, new DateTime(1986, 8, 15, 10, 20, 5, 70) };
yield return new object[] { new DateTime(1986, 8, 15, 10, 20, 5, 70), -10, new DateTime(1986, 8, 15, 10, 20, 5, 60) };
}
[Theory]
[MemberData(nameof(AddMilliseconds_TestData))]
public static void AddMilliseconds(DateTime dateTime, double milliseconds, DateTime expected)
{
Assert.Equal(expected, dateTime.AddMilliseconds(milliseconds));
}
[Fact]
public static void AddMilliseconds_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddMilliseconds(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddMilliseconds(-1));
}
public static IEnumerable<object[]> AddTicks_TestData()
{
yield return new object[] { new DateTime(1000), 10, new DateTime(1010) };
yield return new object[] { new DateTime(1000), 0, new DateTime(1000) };
yield return new object[] { new DateTime(1000), -10, new DateTime(990) };
}
[Theory]
[MemberData(nameof(AddTicks_TestData))]
public static void AddTicks(DateTime dateTime, long ticks, DateTime expected)
{
Assert.Equal(expected, dateTime.AddTicks(ticks));
}
[Fact]
public static void AddTicks_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MaxValue.AddTicks(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTime.MinValue.AddTicks(-1));
}
[Fact]
public static void DayOfWeekTest()
{
var dateTime = new DateTime(2012, 6, 18);
Assert.Equal(DayOfWeek.Monday, dateTime.DayOfWeek);
}
[Fact]
public static void DayOfYear()
{
var dateTime = new DateTime(2012, 6, 18);
Assert.Equal(170, dateTime.DayOfYear);
}
[Fact]
public static void TimeOfDay()
{
var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0);
TimeSpan ts = dateTime.TimeOfDay;
DateTime newDate = dateTime.Subtract(ts);
Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks);
Assert.Equal(dateTime.Ticks, newDate.Add(ts).Ticks);
}
[Fact]
public static void Today()
{
DateTime today = DateTime.Today;
DateTime now = DateTime.Now;
VerifyDateTime(today, now.Year, now.Month, now.Day, 0, 0, 0, 0, DateTimeKind.Local);
today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc);
Assert.Equal(DateTimeKind.Utc, today.Kind);
Assert.False(today.IsDaylightSavingTime());
}
[Fact]
public static void Conversion()
{
DateTime today = DateTime.Today;
long dateTimeRaw = today.ToBinary();
Assert.Equal(today, DateTime.FromBinary(dateTimeRaw));
dateTimeRaw = today.ToUniversalTime().ToBinary();
Assert.Equal(today.ToUniversalTime(), DateTime.FromBinary(dateTimeRaw));
dateTimeRaw = today.ToFileTime();
Assert.Equal(today, DateTime.FromFileTime(dateTimeRaw));
dateTimeRaw = today.ToFileTimeUtc();
Assert.Equal(today, DateTime.FromFileTimeUtc(dateTimeRaw).ToLocalTime());
}
public static IEnumerable<object[]> Subtract_TimeSpan_TestData()
{
var dateTime = new DateTime(2012, 6, 18, 10, 5, 1, 0, DateTimeKind.Utc);
yield return new object[] { dateTime, new TimeSpan(10, 5, 1), new DateTime(2012, 6, 18, 0, 0, 0, 0, DateTimeKind.Utc) };
yield return new object[] { dateTime, new TimeSpan(-10, -5, -1), new DateTime(2012, 6, 18, 20, 10, 2, 0, DateTimeKind.Utc) };
}
[Theory]
[MemberData(nameof(Subtract_TimeSpan_TestData))]
public static void Subtract_TimeSpan(DateTime dateTime, TimeSpan timeSpan, DateTime expected)
{
Assert.Equal(expected, dateTime - timeSpan);
Assert.Equal(expected, dateTime.Subtract(timeSpan));
}
public static IEnumerable<object[]> Subtract_DateTime_TestData()
{
var dateTime1 = new DateTime(1996, 6, 3, 22, 15, 0, DateTimeKind.Utc);
var dateTime2 = new DateTime(1996, 12, 6, 13, 2, 0, DateTimeKind.Utc);
var dateTime3 = new DateTime(1996, 10, 12, 8, 42, 0, DateTimeKind.Utc);
yield return new object[] { dateTime2, dateTime1, new TimeSpan(185, 14, 47, 0) };
yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) };
yield return new object[] { dateTime1, dateTime2, new TimeSpan(-185, -14, -47, 0) };
}
[Theory]
[MemberData(nameof(Subtract_DateTime_TestData))]
public static void Subtract_DateTime(DateTime dateTime1, DateTime dateTime2, TimeSpan expected)
{
Assert.Equal(expected, dateTime1 - dateTime2);
Assert.Equal(expected, dateTime1.Subtract(dateTime2));
}
[Fact]
public static void Subtract_DateTime_Invalid()
{
DateTime date1 = DateTime.MinValue.ToLocalTime();
Assert.Throws<ArgumentOutOfRangeException>(() => date1.Subtract(new TimeSpan(365, 0, 0, 0)));
DateTime date2 = DateTime.MaxValue.ToLocalTime();
Assert.Throws<ArgumentOutOfRangeException>(() => date2.Subtract(new TimeSpan(-365, 0, 0, 0)));
}
[Fact]
public static void Parse_String()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_String_FormatProvider()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString, null);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_String_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString();
DateTime result = DateTime.Parse(expectedString, null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString());
}
[Fact]
public static void Parse_Japanese()
{
var expected = new DateTime(2012, 12, 21, 10, 8, 6);
var cultureInfo = new CultureInfo("ja-JP");
string expectedString = string.Format(cultureInfo, "{0}", expected);
Assert.Equal(expected, DateTime.Parse(expectedString, cultureInfo));
}
[Fact]
public static void Parse_NullString_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
}
[Fact]
public static void TryParse_String()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_U()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("u");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void TryParse_String_FormatProvider_DateTimeStyles_G()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime result;
Assert.True(DateTime.TryParse(expectedString, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET framework has a bug and incorrectly parses this date")]
public static void TryParse_TimeDesignators_NetCore()
{
DateTime result;
Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(5, result.Hour);
Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(4, result.Month);
Assert.Equal(21, result.Day);
Assert.Equal(17, result.Hour);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr fixed a bug where the .NET framework incorrectly parses this date")]
public static void TryParse_TimeDesignators_Netfx()
{
DateTime result;
Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(DateTime.Now.Month, result.Month);
Assert.Equal(DateTime.Now.Day, result.Day);
Assert.Equal(4, result.Hour);
Assert.Equal(0, result.Minute);
Assert.Equal(0, result.Second);
Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result));
Assert.Equal(DateTime.Now.Month, result.Month);
Assert.Equal(DateTime.Now.Day, result.Day);
Assert.Equal(16, result.Hour);
Assert.Equal(0, result.Minute);
Assert.Equal(0, result.Second);
}
[Fact]
public static void ParseExact_String_String_FormatProvider()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("G");
DateTime result = DateTime.ParseExact(expectedString, "G", null);
Assert.Equal(expectedString, result.ToString("G"));
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_U()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("u");
DateTime result = DateTime.ParseExact(expectedString, "u", null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString("u"));
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_G()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime result = DateTime.ParseExact(expectedString, "g", null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString("g"));
}
[Theory]
[MemberData(nameof(Format_String_TestData_O))]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_O(DateTime dt, string expected)
{
string actual = dt.ToString("o");
Assert.Equal(expected, actual);
DateTime result = DateTime.ParseExact(actual, "o", null, DateTimeStyles.None);
Assert.Equal(expected, result.ToString("o"));
}
public static IEnumerable<object[]> Format_String_TestData_O()
{
yield return new object[] { DateTime.MaxValue, "9999-12-31T23:59:59.9999999" };
yield return new object[] { DateTime.MinValue, "0001-01-01T00:00:00.0000000" };
yield return new object[] { new DateTime(1906, 8, 15, 7, 24, 5, 300), "1906-08-15T07:24:05.3000000" };
}
[Theory]
[MemberData(nameof(Format_String_TestData_R))]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R(DateTime dt, string expected)
{
string actual = dt.ToString("r");
Assert.Equal(expected, actual);
DateTime result = DateTime.ParseExact(actual, "r", null, DateTimeStyles.None);
Assert.Equal(expected, result.ToString("r"));
}
public static IEnumerable<object[]> Format_String_TestData_R()
{
yield return new object[] { DateTime.MaxValue, "Fri, 31 Dec 9999 23:59:59 GMT" };
yield return new object[] { DateTime.MinValue, "Mon, 01 Jan 0001 00:00:00 GMT" };
yield return new object[] { new DateTime(1906, 8, 15, 7, 24, 5, 300), "Wed, 15 Aug 1906 07:24:05 GMT" };
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("r");
DateTime result = DateTime.ParseExact(expectedString, "r", null, DateTimeStyles.None);
Assert.Equal(expectedString, result.ToString("r"));
}
[Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_CustomFormatProvider()
{
var formatter = new MyFormatter();
string dateBefore = DateTime.Now.ToString();
DateTime dateAfter = DateTime.ParseExact(dateBefore, "G", formatter, DateTimeStyles.AdjustToUniversal);
Assert.Equal(dateBefore, dateAfter.ToString());
}
[Fact]
public static void ParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTime result = DateTime.ParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal);
Assert.Equal(expectedString, result.ToString("g"));
}
[Fact]
public static void TryParseExact_String_String_FormatProvider_DateTimeStyles_NullFormatProvider()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
DateTime resulted;
Assert.True(DateTime.TryParseExact(expectedString, "g", null, DateTimeStyles.AdjustToUniversal, out resulted));
Assert.Equal(expectedString, resulted.ToString("g"));
}
[Fact]
public static void TryParseExact_String_StringArray_FormatProvider_DateTimeStyles()
{
DateTime expected = DateTime.MaxValue;
string expectedString = expected.ToString("g");
var formats = new string[] { "g" };
DateTime result;
Assert.True(DateTime.TryParseExact(expectedString, formats, null, DateTimeStyles.AdjustToUniversal, out result));
Assert.Equal(expectedString, result.ToString("g"));
}
public static void ParseExact_EscapedSingleQuotes()
{
var formatInfo = DateTimeFormatInfo.GetInstance(new CultureInfo("mt-MT"));
const string format = @"dddd, d' ta\' 'MMMM yyyy";
DateTime expected = new DateTime(1999, 2, 28, 17, 00, 01);
string formatted = expected.ToString(format, formatInfo);
DateTime actual = DateTime.ParseExact(formatted, format, formatInfo);
Assert.Equal(expected.Date, actual.Date);
}
[Theory]
[InlineData("fi-FI")]
[InlineData("nb-NO")]
[InlineData("nb-SJ")]
[InlineData("sr-Cyrl-XK")]
[InlineData("sr-Latn-ME")]
[InlineData("sr-Latn-RS")]
[InlineData("sr-Latn-XK")]
public static void Parse_SpecialCultures(string cultureName)
{
// Test DateTime parsing with cultures which has the date separator and time separator are same
CultureInfo cultureInfo;
try
{
cultureInfo = new CultureInfo(cultureName);
}
catch (CultureNotFoundException)
{
// Ignore un-supported culture in current platform
return;
}
var dateTime = new DateTime(2015, 11, 20, 11, 49, 50);
string dateString = dateTime.ToString(cultureInfo.DateTimeFormat.ShortDatePattern, cultureInfo);
DateTime parsedDate;
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
if (cultureInfo.DateTimeFormat.ShortDatePattern.Contains("yyyy") || HasDifferentDateTimeSeparators(cultureInfo.DateTimeFormat))
{
Assert.Equal(dateTime.Date, parsedDate);
}
else
{
// When the date separator and time separator are the same, DateTime.TryParse cannot
// tell the difference between a short date like dd.MM.yy and a short time
// like HH.mm.ss. So it assumes that if it gets 03.04.11, that must be a time
// and uses the current date to construct the date time.
DateTime now = DateTime.Now;
Assert.Equal(new DateTime(now.Year, now.Month, now.Day, dateTime.Day, dateTime.Month, dateTime.Year % 100), parsedDate);
}
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongDatePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime.Date, parsedDate);
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.FullDateTimePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime, parsedDate);
dateString = dateTime.ToString(cultureInfo.DateTimeFormat.LongTimePattern, cultureInfo);
Assert.True(DateTime.TryParse(dateString, cultureInfo, DateTimeStyles.None, out parsedDate));
Assert.Equal(dateTime.TimeOfDay, parsedDate.TimeOfDay);
}
private static bool HasDifferentDateTimeSeparators(DateTimeFormatInfo dateTimeFormat)
{
// Since .NET Core doesn't expose DateTimeFormatInfo DateSeparator and TimeSeparator properties,
// this method gets the separators using DateTime.ToString by passing in the invariant separators.
// The invariant separators will then get turned into the culture's separators by ToString,
// which are then compared.
var dateTime = new DateTime(2015, 11, 24, 17, 57, 29);
string separators = dateTime.ToString("/@:", dateTimeFormat);
int delimiterIndex = separators.IndexOf('@');
string dateSeparator = separators.Substring(0, delimiterIndex);
string timeSeparator = separators.Substring(delimiterIndex + 1);
return dateSeparator != timeSeparator;
}
[Fact]
public static void GetDateTimeFormats()
{
var allStandardFormats = new char[]
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
var dateTime = new DateTime(2009, 7, 28, 5, 23, 15);
var formats = new List<string>();
foreach (char format in allStandardFormats)
{
string[] dates = dateTime.GetDateTimeFormats(format);
Assert.True(dates.Length > 0);
DateTime parsedDate;
Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate));
formats.AddRange(dates);
}
List<string> actualFormats = dateTime.GetDateTimeFormats().ToList();
Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t));
actualFormats = dateTime.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList();
Assert.Equal(formats.OrderBy(t => t), actualFormats.OrderBy(t => t));
}
[Fact]
public static void GetDateTimeFormats_FormatSpecifier_InvalidFormat()
{
var dateTime = new DateTime(2009, 7, 28, 5, 23, 15);
Assert.Throws<FormatException>(() => dateTime.GetDateTimeFormats('x')); // No such format
}
private static void VerifyDateTime(DateTime dateTime, int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
{
Assert.Equal(year, dateTime.Year);
Assert.Equal(month, dateTime.Month);
Assert.Equal(day, dateTime.Day);
Assert.Equal(hour, dateTime.Hour);
Assert.Equal(minute, dateTime.Minute);
Assert.Equal(second, dateTime.Second);
Assert.Equal(millisecond, dateTime.Millisecond);
Assert.Equal(kind, dateTime.Kind);
}
private class MyFormatter : IFormatProvider
{
public object GetFormat(Type formatType)
{
return typeof(IFormatProvider) == formatType ? this : null;
}
}
[Fact]
public static void InvalidDateTimeStyles()
{
string strDateTime = "Thursday, August 31, 2006 1:14";
string[] formats = new string[] { "f" };
IFormatProvider provider = new CultureInfo("en-US");
DateTimeStyles style = DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal;
AssertExtensions.Throws<ArgumentException>("style", () => DateTime.ParseExact(strDateTime, formats, provider, style));
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Timers;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework.Servers.HttpServer;
using Aurora.Framework;
using System.Security.Authentication;
namespace Aurora.Simulation.Base
{
public class SimulationBase : ISimulationBase
{
protected string m_startupCommandsFile;
protected string m_shutdownCommandsFile;
protected string m_TimerScriptFileName = "disabled";
protected int m_TimerScriptTime = 20;
protected IHttpServer m_BaseHTTPServer;
protected Timer m_TimerScriptTimer;
protected ConfigurationLoader m_configurationLoader;
/// <value>
/// The config information passed into the Aurora server.
/// </value>
protected IConfigSource m_config;
protected IConfigSource m_original_config;
public IConfigSource ConfigSource
{
get { return m_config; }
set { m_config = value; }
}
/// <summary>
/// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
/// </summary>
protected string m_version;
public string Version
{
get { return m_version; }
}
protected IRegistryCore m_applicationRegistry = new RegistryCore();
public IRegistryCore ApplicationRegistry
{
get { return m_applicationRegistry; }
}
protected AuroraEventManager m_eventManager = new AuroraEventManager();
public AuroraEventManager EventManager
{
get { return m_eventManager; }
}
/// <summary>
/// Time at which this server was started
/// </summary>
protected DateTime m_StartupTime;
public DateTime StartupTime
{
get { return m_StartupTime; }
}
protected List<IApplicationPlugin> m_applicationPlugins = new List<IApplicationPlugin>();
public IHttpServer HttpServer
{
get { return m_BaseHTTPServer; }
}
protected Dictionary<uint, BaseHttpServer> m_Servers =
new Dictionary<uint, BaseHttpServer>();
protected uint m_Port;
public uint DefaultPort
{
get { return m_Port; }
}
protected string[] m_commandLineParameters = null;
public string[] CommandLineParameters
{
get { return m_commandLineParameters; }
}
protected string m_pidFile = String.Empty;
/// <summary>
/// Do the initial setup for the application
/// </summary>
/// <param name="originalConfig"></param>
/// <param name="configSource"></param>
/// <param name="cmdParams"></param>
/// <param name="configLoader"></param>
public virtual void Initialize(IConfigSource originalConfig, IConfigSource configSource, string[] cmdParams, ConfigurationLoader configLoader)
{
m_commandLineParameters = cmdParams;
m_StartupTime = DateTime.Now;
m_version = VersionInfo.Version + " (" + Util.GetRuntimeInformation() + ")";
m_original_config = originalConfig;
m_config = configSource;
m_configurationLoader = configLoader;
// This thread will go on to become the console listening thread
if (System.Threading.Thread.CurrentThread.Name != "ConsoleThread")
System.Threading.Thread.CurrentThread.Name = "ConsoleThread";
//Register the interface
ApplicationRegistry.RegisterModuleInterface<ISimulationBase>(this);
Configuration(configSource);
InitializeModules();
RegisterConsoleCommands();
}
/// <summary>
/// Read the configuration
/// </summary>
/// <param name="configSource"></param>
public virtual void Configuration(IConfigSource configSource)
{
IConfig startupConfig = m_config.Configs["Startup"];
int stpMaxThreads = 15;
if (startupConfig != null)
{
m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt");
m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt");
m_TimerScriptFileName = startupConfig.GetString("timer_Script", "disabled");
m_TimerScriptTime = startupConfig.GetInt("timer_time", m_TimerScriptTime);
string pidFile = startupConfig.GetString("PIDFile", String.Empty);
if (pidFile != String.Empty)
CreatePIDFile(pidFile);
}
IConfig SystemConfig = m_config.Configs["System"];
if (SystemConfig != null)
{
string asyncCallMethodStr = SystemConfig.GetString("AsyncCallMethod", String.Empty);
FireAndForgetMethod asyncCallMethod;
if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse(asyncCallMethodStr, out asyncCallMethod))
Util.FireAndForgetMethod = asyncCallMethod;
stpMaxThreads = SystemConfig.GetInt("MaxPoolThreads", 15);
}
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
Util.InitThreadPool(stpMaxThreads);
}
/// <summary>
/// Performs initialisation of the application, such as loading the HTTP server and modules
/// </summary>
public virtual void Startup()
{
MainConsole.Instance.Warn("====================================================================");
MainConsole.Instance.Warn(string.Format("====================== STARTING AURORA ({0}) ======================",
(IntPtr.Size == 4 ? "x86" : "x64")));
MainConsole.Instance.Warn("====================================================================");
MainConsole.Instance.Warn("[AuroraStartup]: Version: " + Version + "\n");
SetUpHTTPServer();
StartModules();
//Has to be after Scene Manager startup
AddPluginCommands();
}
public virtual ISimulationBase Copy()
{
return new SimulationBase();
}
/// <summary>
/// Run the console now that we are all done with startup
/// </summary>
public virtual void Run()
{
while (true)
{
try
{
//Start the prompt
if (MainConsole.Instance != null)
{
MainConsole.Instance.ReadConsole();
}
}
catch (Exception ex)
{
//Only error that ever could occur is the restart one
MainConsole.Instance.InfoFormat("[Console]: Exception {0}", ex.Message);
MainConsole.Instance.InfoFormat("[Console]: App {0}", ex.Source);
MainConsole.Instance.InfoFormat("[Console]: tgt {0}", ex.TargetSite);
Shutdown(true);
throw;
}
}
}
public virtual void AddPluginCommands()
{
}
/// <summary>
/// Get an HTTPServer on the given port. It will create one if one does not exist
/// </summary>
/// <param name="port"></param>
/// <returns></returns>
public IHttpServer GetHttpServer(uint port)
{
return GetHttpServer(port, false, "", "", SslProtocols.None);
}
public IHttpServer GetHttpServer (uint port, bool secure, string certPath, string certPass, SslProtocols sslProtocol)
{
if ((port == m_Port || port == 0) && HttpServer != null)
return HttpServer;
BaseHttpServer server;
if(m_Servers.TryGetValue(port, out server) && server.Secure == secure)
return server;
string hostName =
m_config.Configs["Network"].GetString("HostName", "http" + (secure ? "s" : "") + "://" + Utilities.GetExternalIp());
//Clean it up a bit
if (hostName.StartsWith("http://") || hostName.StartsWith("https://"))
hostName = hostName.Replace("https://", "").Replace("http://", "");
if (hostName.EndsWith ("/"))
hostName = hostName.Remove (hostName.Length - 1, 1);
server = new BaseHttpServer(port, hostName, secure);
try
{
if(secure)//Set these params now
server.SetSecureParams(certPath, certPass, sslProtocol);
server.Start();
}
catch(Exception)
{
//Remove the server from the list
m_Servers.Remove (port);
//Then pass the exception upwards
throw;
}
return (m_Servers[port] = server);
}
/// <summary>
/// Set up the base HTTP server
/// </summary>
public virtual void SetUpHTTPServer()
{
m_Port = m_config.Configs["Network"].GetUInt("http_listener_port", 9000);
bool useHTTPS = m_config.Configs["Network"].GetBoolean("use_https", false);
string certPath = m_config.Configs["Network"].GetString("https_cert_path", "");
string certPass = m_config.Configs["Network"].GetString("https_cert_pass", "");
string sslProtocol = m_config.Configs["Network"].GetString("https_ssl_protocol", "Default");
SslProtocols protocols;
try
{
protocols = (SslProtocols)Enum.Parse(typeof(SslProtocols), sslProtocol);
}
catch
{
protocols = SslProtocols.Tls;
}
m_BaseHTTPServer = GetHttpServer(m_Port, useHTTPS, certPath, certPass, protocols);
MainServer.Instance = m_BaseHTTPServer;
}
public virtual void InitializeModules()
{
m_applicationPlugins = AuroraModuleLoader.PickupModules<IApplicationPlugin>();
foreach (IApplicationPlugin plugin in m_applicationPlugins)
{
plugin.PreStartup(this);
}
}
/// <summary>
/// Start the application modules
/// </summary>
public virtual void StartModules()
{
foreach (IApplicationPlugin plugin in m_applicationPlugins)
{
plugin.Initialize(this);
}
foreach (IApplicationPlugin plugin in m_applicationPlugins)
{
plugin.PostInitialise();
}
foreach (IApplicationPlugin plugin in m_applicationPlugins)
{
plugin.Start();
}
foreach (IApplicationPlugin plugin in m_applicationPlugins)
{
plugin.PostStart();
}
}
/// <summary>
/// Close all the Application Plugins
/// </summary>
public virtual void CloseModules()
{
foreach (IApplicationPlugin plugin in m_applicationPlugins)
{
plugin.Close();
}
}
/// <summary>
/// Run the commands given now that startup is complete
/// </summary>
public void RunStartupCommands()
{
//Draw the file on the console
PrintFileToConsole("startuplogo.txt");
//Run Startup Commands
if (!String.IsNullOrEmpty(m_startupCommandsFile))
RunCommandScript(m_startupCommandsFile);
// Start timer script (run a script every xx seconds)
if (m_TimerScriptFileName != "disabled")
{
Timer newtimername = new Timer {Enabled = true, Interval = m_TimerScriptTime*60*1000};
newtimername.Elapsed += RunAutoTimerScript;
}
}
/// <summary>
/// Opens a file and uses it as input to the console command parser.
/// </summary>
/// <param name="fileName">name of file to use as input to the console</param>
private void PrintFileToConsole(string fileName)
{
if (File.Exists(fileName))
{
StreamReader readFile = File.OpenText(fileName);
string currentLine;
while ((currentLine = readFile.ReadLine()) != null)
{
MainConsole.Instance.Info("[!]" + currentLine);
}
}
}
/// <summary>
/// Timer to run a specific text file as console commands.
/// Configured in in the main .ini file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RunAutoTimerScript(object sender, EventArgs e)
{
RunCommandScript(m_TimerScriptFileName);
}
#region Console Commands
/// <summary>
/// Register standard set of region console commands
/// </summary>
public virtual void RegisterConsoleCommands()
{
if (MainConsole.Instance == null)
return;
MainConsole.Instance.Commands.AddCommand("quit", "quit", "Quit the application", HandleQuit);
MainConsole.Instance.Commands.AddCommand("shutdown", "shutdown", "Quit the application", HandleQuit);
MainConsole.Instance.Commands.AddCommand("show info", "show info", "Show server information (e.g. startup path)", HandleShowInfo);
MainConsole.Instance.Commands.AddCommand("show version", "show version", "Show server version", HandleShowVersion);
MainConsole.Instance.Commands.AddCommand("reload config", "reload config", "Reloads .ini file configuration", HandleConfigRefresh);
MainConsole.Instance.Commands.AddCommand("set timer script interval", "set timer script interval", "Set the interval for the timer script (in minutes).", HandleTimerScriptTime);
MainConsole.Instance.Commands.AddCommand("force GC", "force GC", "Forces garbage collection.", HandleForceGC);
MainConsole.Instance.Commands.AddCommand("run configurator", "run configurator", "Runs Aurora.Configurator.", runConfig);
}
private void HandleQuit(string[] args)
{
Shutdown(true);
}
/// <summary>
/// Run an optional startup list of commands
/// </summary>
/// <param name="fileName"></param>
public virtual void RunCommandScript(string fileName)
{
if (File.Exists(fileName))
{
MainConsole.Instance.Info("[COMMANDFILE]: Running " + fileName);
List<string> commands = new List<string>();
using (StreamReader readFile = File.OpenText(fileName))
{
string currentCommand;
while ((currentCommand = readFile.ReadLine()) != null)
{
if (currentCommand != String.Empty)
{
commands.Add(currentCommand);
}
}
}
foreach (string currentCommand in commands)
{
MainConsole.Instance.Info("[COMMANDFILE]: Running '" + currentCommand + "'");
MainConsole.Instance.RunCommand(currentCommand);
}
}
}
public virtual void HandleForceGC(string[] cmd)
{
GC.Collect();
MainConsole.Instance.Warn("Garbage collection finished");
}
public virtual void runConfig(string[] cmd)
{
BaseApplication.Configure(true);
}
public virtual void HandleTimerScriptTime(string[] cmd)
{
if (cmd.Length != 5)
{
MainConsole.Instance.Warn("[CONSOLE]: Timer Interval command did not have enough parameters.");
return;
}
MainConsole.Instance.Warn("[CONSOLE]: Set Timer Interval to " + cmd[4]);
m_TimerScriptTime = int.Parse(cmd[4]);
m_TimerScriptTimer.Enabled = false;
m_TimerScriptTimer.Interval = m_TimerScriptTime * 60 * 1000;
m_TimerScriptTimer.Enabled = true;
}
public virtual void HandleConfigRefresh(string[] cmd)
{
//Rebuild the configs
m_config = m_configurationLoader.LoadConfigSettings (m_original_config);
foreach (IApplicationPlugin plugin in m_applicationPlugins)
plugin.ReloadConfiguration(m_config);
string hostName =
m_config.Configs["Network"].GetString("HostName", "http://127.0.0.1");
//Clean it up a bit
// these are doing nothing??
hostName.Replace("http://", "");
hostName.Replace("https://", "");
if(hostName.EndsWith("/"))
hostName = hostName.Remove(hostName.Length - 1, 1);
foreach(IHttpServer server in m_Servers.Values)
{
server.HostName = hostName;
}
MainConsole.Instance.Info ("Finished reloading configuration.");
}
public virtual void HandleShowInfo (string[] cmd)
{
MainConsole.Instance.Info ("Version: " + m_version);
MainConsole.Instance.Info ("Startup directory: " + Environment.CurrentDirectory);
}
public virtual void HandleShowVersion (string[] cmd)
{
MainConsole.Instance.Info (
String.Format (
"Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion));
}
#endregion
/// <summary>
/// Should be overriden and referenced by descendents if they need to perform extra shutdown processing
/// Performs any last-minute sanity checking and shuts down the region server
/// </summary>
public virtual void Shutdown(bool close)
{
try
{
try
{
RemovePIDFile();
if (m_shutdownCommandsFile != String.Empty)
{
RunCommandScript(m_shutdownCommandsFile);
}
}
catch
{
//It doesn't matter, just shut down
}
try
{
//Close out all the modules
CloseModules();
}
catch
{
//Just shut down already
}
try
{
//Close the thread pool
Util.CloseThreadPool();
}
catch
{
//Just shut down already
}
try
{
//Stop the HTTP server(s)
foreach (BaseHttpServer server in m_Servers.Values)
{
server.Stop();
}
}
catch
{
//Again, just shut down
}
if (close)
MainConsole.Instance.Info("[SHUTDOWN]: Terminating");
MainConsole.Instance.Info("[SHUTDOWN]: Shutdown processing on main thread complete. " + (close ? " Exiting..." : ""));
if (close)
Environment.Exit(0);
}
catch
{
}
}
/// <summary>
/// Write the PID file to the hard drive
/// </summary>
/// <param name="path"></param>
protected void CreatePIDFile(string path)
{
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
FileStream fs = File.Create(path);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
fs.Close();
m_pidFile = path;
}
catch (Exception)
{
}
}
/// <summary>
/// Delete the PID file now that we are done running
/// </summary>
protected void RemovePIDFile()
{
if (m_pidFile != String.Empty)
{
try
{
File.Delete(m_pidFile);
m_pidFile = String.Empty;
}
catch (Exception)
{
}
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.IO;
using System.Reflection;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class DefaultMigrationConventionsTests
{
[Test]
public void GetPrimaryKeyNamePrefixesTableNameWithPKAndUnderscore()
{
DefaultMigrationConventions.GetPrimaryKeyName("Foo").ShouldBe("PK_Foo");
}
[Test]
public void GetForeignKeyNameReturnsValidForeignKeyNameForSimpleForeignKey()
{
var foreignKey = new ForeignKeyDefinition
{
ForeignTable = "Users", ForeignColumns = new[] { "GroupId" },
PrimaryTable = "Groups", PrimaryColumns = new[] { "Id" }
};
DefaultMigrationConventions.GetForeignKeyName(foreignKey).ShouldBe("FK_Users_GroupId_Groups_Id");
}
[Test]
public void GetForeignKeyNameReturnsValidForeignKeyNameForComplexForeignKey()
{
var foreignKey = new ForeignKeyDefinition
{
ForeignTable = "Users", ForeignColumns = new[] { "ColumnA", "ColumnB" },
PrimaryTable = "Groups", PrimaryColumns = new[] { "ColumnC", "ColumnD" }
};
DefaultMigrationConventions.GetForeignKeyName(foreignKey).ShouldBe("FK_Users_ColumnA_ColumnB_Groups_ColumnC_ColumnD");
}
[Test]
public void GetIndexNameReturnsValidIndexNameForSimpleIndex()
{
var index = new IndexDefinition
{
TableName = "Bacon",
Columns =
{
new IndexColumnDefinition { Name = "BaconName", Direction = Direction.Ascending }
}
};
DefaultMigrationConventions.GetIndexName(index).ShouldBe("IX_Bacon_BaconName");
}
[Test]
public void GetIndexNameReturnsValidIndexNameForComplexIndex()
{
var index = new IndexDefinition
{
TableName = "Bacon",
Columns =
{
new IndexColumnDefinition { Name = "BaconName", Direction = Direction.Ascending },
new IndexColumnDefinition { Name = "BaconSpice", Direction = Direction.Descending }
}
};
DefaultMigrationConventions.GetIndexName(index).ShouldBe("IX_Bacon_BaconName_BaconSpice");
}
[Test]
public void TypeIsMigrationReturnsTrueIfTypeExtendsMigrationAndHasMigrationAttribute()
{
DefaultMigrationConventions.TypeIsMigration(typeof(DefaultConventionMigrationFake))
.ShouldBeTrue();
}
[Test]
public void TypeIsMigrationReturnsFalseIfTypeDoesNotExtendMigration()
{
DefaultMigrationConventions.TypeIsMigration(typeof(object))
.ShouldBeFalse();
}
[Test]
public void TypeIsMigrationReturnsFalseIfTypeDoesNotHaveMigrationAttribute()
{
DefaultMigrationConventions.TypeIsMigration(typeof(MigrationWithoutAttributeFake))
.ShouldBeFalse();
}
[Test]
public void GetMaintenanceStageReturnsCorrectStage()
{
DefaultMigrationConventions.GetMaintenanceStage(typeof (MaintenanceAfterEach))
.ShouldBe(MigrationStage.AfterEach);
}
[Test]
public void MigrationInfoShouldRetainMigration()
{
var migrationType = typeof(DefaultConventionMigrationFake);
var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migrationType);
migrationinfo.Migration.GetType().ShouldBeSameAs(migrationType);
}
[Test]
public void MigrationInfoShouldExtractVersion()
{
var migrationType = typeof(DefaultConventionMigrationFake);
var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migrationType);
migrationinfo.Version.ShouldBe(123);
}
[Test]
public void MigrationInfoShouldExtractTransactionBehavior()
{
var migrationType = typeof(DefaultConventionMigrationFake);
var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migrationType);
migrationinfo.TransactionBehavior.ShouldBe(TransactionBehavior.None);
}
[Test]
public void MigrationInfoShouldExtractTraits()
{
var migrationType = typeof(DefaultConventionMigrationFake);
var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migrationType);
migrationinfo.Trait("key").ShouldBe("test");
}
[Test]
[Category("Integration")]
public void WorkingDirectoryConventionDefaultsToAssemblyFolder()
{
var defaultWorkingDirectory = DefaultMigrationConventions.GetWorkingDirectory();
defaultWorkingDirectory.ShouldNotBeNull();
defaultWorkingDirectory.Contains("bin").ShouldBeTrue();
}
[Test]
public void TypeHasTagsReturnTrueIfTypeHasTagsAttribute()
{
DefaultMigrationConventions.TypeHasTags(typeof(TaggedWithUk))
.ShouldBeTrue();
}
[Test]
public void TypeHasTagsReturnFalseIfTypeDoesNotHaveTagsAttribute()
{
DefaultMigrationConventions.TypeHasTags(typeof(HasNoTagsFake))
.ShouldBeFalse();
}
[Test]
public void TypeHasTagsReturnTrueIfBaseTypeDoesHaveTagsAttribute()
{
DefaultMigrationConventions.TypeHasTags(typeof(ConcretehasTagAttribute))
.ShouldBeTrue();
}
public class TypeHasMatchingTags
{
[Test]
[Category("Tagging")]
public void WhenTypeHasTagAttributeButNoTagsPassedInReturnsFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new string[] { })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasTagAttributeWithNoTagNamesReturnsFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(HasTagAttributeWithNoTagNames), new string[] { })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasOneTagThatDoesNotMatchSingleThenTagReturnsFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "IE" })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasOneTagThatDoesMatchSingleTagThenReturnsTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "UK" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasOneTagThatPartiallyMatchesTagThenReturnsFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "UK2" })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasOneTagThatDoesMatchMultipleTagsThenReturnsFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "UK", "Production" })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasTagsInTwoAttributeThatDoesMatchSingleTagThenReturnsTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes), new[] { "UK" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasTagsInTwoAttributesThatDoesMatchMultipleTagsThenReturnsTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes), new[] { "UK", "Production" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasTagsInOneAttributeThatDoesMatchMultipleTagsThenReturnsTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInOneTagsAttribute), new[] { "UK", "Production" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasTagsInTwoAttributesThatDontNotMatchMultipleTagsThenReturnsFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes), new[] { "UK", "IE" })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenBaseTypeHasTagsThenConcreteTypeReturnsTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(ConcretehasTagAttribute), new[] { "UK" })
.ShouldBeTrue();
}
//new
[Test]
[Category("Tagging")]
public void WhenTypeHasSingleTagWithSingleTagNameAndBehaviorOfAnyAndHasMatchingTagNamesThenReturnTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUkAndAnyBehavior), new[] { "UK", "IE" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasSingleTagWithSingleTagNameAndBehaviorOfAnyButNoMatchingTagNamesThenReturnFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUkAndAnyBehavior), new[] { "Chrome", "IE" })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasSingleTagWithMultipleTagNamesAndBehaviorOfAnyWithSomeMatchingTagNamesThenReturnTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingAndAnyBehaviorInOneTagsAttribute), new[] { "UK", "Staging", "IE" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasSingleTagWithMultipleTagNamesAndBehaviorOfAnyWithNoMatchingTagNamesThenReturnFalse()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingAndAnyBehaviorInOneTagsAttribute), new[] { "IE", "Chrome" })
.ShouldBeFalse();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasMultipleTagsWithMultipleTagNamesAndAllTagsHaveBehaviorOfAnyWithAllHavingAMatchingTagNameThenReturnTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributesWithAnyBehaviorOnBoth), new[] { "UK", "Staging" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasMultipleTagsWithMultipleTagNamesAndAllTagsHaveBehaviorOfAnyWithOneTagNotHavingAMatchingTagNameThenReturnTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributesWithAnyBehaviorOnBoth), new[] { "UK", "IE" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasMultipleTagsWithMultipleTagNamesAndOneHasBehaviorOfAnyAndOtherHasBehaviorOfAllWithAllTagNamesMatchingThenReturnTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndAllBehaviorAndProductionAndStagingAndAnyBehaviorInTwoTagsAttributes), new[] { "UK", "Staging" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasMultipleTagsWithMultipleTagNamesAndOneHasBehaviorOfAnyAndOtherHasBehaviorOfAllWithoutAllTagNamesMatchingThenReturnTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndAllBehaviorAndProductionAndStagingAndAnyBehaviorInTwoTagsAttributes), new[] { "UK", "Staging", "IE" })
.ShouldBeTrue();
}
[Test]
[Category("Tagging")]
public void WhenTypeHasMultipleTagsWithMultipleTagNamesAndOneHasBehaviorOfAnyWithoutAnyMatchingTagNamesAndOtherHasBehaviorOfAllWithTagNamesMatchingThenReturnTrue()
{
DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndAllBehaviorAndProductionAndStagingAndAnyBehaviorInTwoTagsAttributes), new[] { "BE", "UK" })
.ShouldBeTrue();
}
}
[FluentMigrator.Migration(20130508175300)]
class AutoScriptMigrationFake : AutoScriptMigration { }
[Test]
public void GetAutoScriptUpName()
{
var type = typeof(AutoScriptMigrationFake);
var databaseType = "sqlserver";
DefaultMigrationConventions.GetAutoScriptUpName(type, databaseType)
.ShouldBe("Scripts.Up.20130508175300_AutoScriptMigrationFake_sqlserver.sql");
}
[Test]
public void GetAutoScriptDownName()
{
var type = typeof(AutoScriptMigrationFake);
var databaseType = "sqlserver";
DefaultMigrationConventions.GetAutoScriptDownName(type, databaseType)
.ShouldBe("Scripts.Down.20130508175300_AutoScriptMigrationFake_sqlserver.sql");
}
}
[Tags("BE", "UK", "Staging", "Production")]
public class TaggedWithBeAndUkAndProductionAndStagingInOneTagsAttribute
{
}
[Tags(TagBehavior.RequireAny, "BE", "UK", "Staging", "Production")]
public class TaggedWithBeAndUkAndProductionAndStagingAndAnyBehaviorInOneTagsAttribute
{
}
[Tags("BE", "UK")]
[Tags("Staging", "Production")]
public class TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes
{
}
[Tags(TagBehavior.RequireAny, "BE", "UK")]
[Tags(TagBehavior.RequireAny, "Staging", "Production")]
public class TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributesWithAnyBehaviorOnBoth
{
}
[Tags(TagBehavior.RequireAll,"BE", "UK", "Staging")]
[Tags(TagBehavior.RequireAny, "Staging", "Production")]
public class TaggedWithBeAndUkAndAllBehaviorAndProductionAndStagingAndAnyBehaviorInTwoTagsAttributes
{
}
[Tags("UK")]
public class TaggedWithUk
{
}
[Tags(TagBehavior.RequireAny, "UK")]
public class TaggedWithUkAndAnyBehavior
{
}
[Tags]
public class HasTagAttributeWithNoTagNames
{
}
public class HasNoTagsFake
{
}
[Tags("UK")]
public abstract class BaseHasTagAttribute : Migration
{ }
public class ConcretehasTagAttribute : BaseHasTagAttribute
{
public override void Up(){}
public override void Down(){}
}
[Migration(123, TransactionBehavior.None)]
[MigrationTrait("key", "test")]
internal class DefaultConventionMigrationFake : Migration
{
public override void Up() { }
public override void Down() { }
}
internal class MigrationWithoutAttributeFake : Migration
{
public override void Up() { }
public override void Down() { }
}
[Maintenance(MigrationStage.AfterEach)]
internal class MaintenanceAfterEach : Migration
{
public override void Up() { }
public override void Down() { }
}
}
| |
//
// Json.cs: MonoTouch.Dialog support for creating UIs from Json description files
//
// Author:
// Miguel de Icaza
//
// See the JSON.md file for documentation
//
// TODO: Json to load entire view controllers
//
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Json;
using System.Net;
using System.Reflection;
#if XAMCORE_2_0
using Foundation;
using UIKit;
using CoreGraphics;
using NSAction = global::System.Action;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
#endif
#if !XAMCORE_2_0
using nint = global::System.Int32;
using nuint = global::System.UInt32;
using nfloat = global::System.Single;
using CGSize = global::System.Drawing.SizeF;
using CGPoint = global::System.Drawing.PointF;
using CGRect = global::System.Drawing.RectangleF;
#endif
namespace MonoTouch.Dialog {
public class JsonElement : RootElement {
JsonElement jsonParent;
Dictionary<string,Element> map;
const int CSIZE = 16;
const int SPINNER_TAG = 1000;
public string Url;
bool loading;
UIActivityIndicatorView StartSpinner (UITableViewCell cell)
{
var cvb = cell.ContentView.Bounds;
var spinner = new UIActivityIndicatorView (new CGRect (cvb.Width-CSIZE/2, (cvb.Height-CSIZE)/2, CSIZE, CSIZE)) {
Tag = SPINNER_TAG,
ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray,
};
cell.ContentView.AddSubview (spinner);
spinner.StartAnimating ();
cell.Accessory = UITableViewCellAccessory.None;
return spinner;
}
void RemoveSpinner (UITableViewCell cell, UIActivityIndicatorView spinner)
{
spinner.StopAnimating ();
spinner.RemoveFromSuperview ();
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
}
public override UITableViewCell GetCell (UITableView tv)
{
var cell = base.GetCell (tv);
if (Url == null)
return cell;
var spinner = cell.ViewWithTag (SPINNER_TAG) as UIActivityIndicatorView;
if (loading){
if (spinner == null)
StartSpinner (cell);
else
if (spinner != null)
RemoveSpinner (cell, spinner);
}
return cell;
}
#if XAMCORE_2_0
class ConnectionDelegate : NSUrlConnectionDataDelegate {
#else
class ConnectionDelegate : NSUrlConnectionDelegate {
#endif
Action<Stream,NSError> callback;
NSMutableData buffer;
public ConnectionDelegate (Action<Stream,NSError> callback)
{
this.callback = callback;
buffer = new NSMutableData ();
}
public override void ReceivedResponse(NSUrlConnection connection, NSUrlResponse response)
{
buffer.Length = 0;
}
public override void FailedWithError(NSUrlConnection connection, NSError error)
{
callback (null, error);
}
public override void ReceivedData(NSUrlConnection connection, NSData data)
{
buffer.AppendData (data);
}
public override void FinishedLoading(NSUrlConnection connection)
{
callback (buffer.AsStream (), null);
}
}
public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path)
{
if (Url == null){
base.Selected (dvc, tableView, path);
return;
}
tableView.DeselectRow (path, false);
if (loading)
return;
var cell = GetActiveCell ();
var spinner = StartSpinner (cell);
loading = true;
var request = new NSUrlRequest (new NSUrl (Url), NSUrlRequestCachePolicy.UseProtocolCachePolicy, 60);
var connection = new NSUrlConnection (request, new ConnectionDelegate ((data,error) => {
loading = false;
spinner.StopAnimating ();
spinner.RemoveFromSuperview ();
if (error == null){
try {
var obj = JsonValue.Load (new StreamReader (data)) as JsonObject;
if (obj != null){
var root = JsonElement.FromJson (obj);
var newDvc = new DialogViewController (root, true) {
Autorotate = true
};
PrepareDialogViewController (newDvc);
dvc.ActivateController (newDvc);
return;
}
} catch (Exception ee){
Console.WriteLine (ee);
}
}
var alert = new UIAlertView ("Error", "Unable to download data", null, "Ok");
alert.Show ();
}));
}
public JsonElement (string caption, string url) : base (caption)
{
Url = url;
}
public JsonElement (string caption, int section, int element, string url) : base (caption, section, element)
{
Url = url;
}
public JsonElement (string caption, Group group, string url) : base (caption, group)
{
Url = url;
}
public static JsonElement FromFile (string file, object arg)
{
using (var reader = File.OpenRead (file))
return FromJson (JsonObject.Load (reader) as JsonObject, arg);
}
public static JsonElement FromFile (string file)
{
return FromFile (file, null);
}
public static JsonElement FromJson (JsonObject json)
{
return FromJson (null, json, null);
}
public static JsonElement FromJson (JsonObject json, object data)
{
return FromJson (null, json, data);
}
public static JsonElement FromJson (JsonElement parent, JsonObject json, object data)
{
if (json == null)
return null;
var title = GetString (json, "title") ?? "";
var group = GetString (json, "group");
var url = GetString (json, "url");
var radioSelected = GetString (json, "radioselected");
JsonElement root;
if (group == null){
if (radioSelected == null)
root = new JsonElement (title, url);
else
root = new JsonElement (title, new RadioGroup (int.Parse (radioSelected)), url);
} else {
if (radioSelected == null)
root = new JsonElement (title, new Group (group), url);
else {
// It does not seem that we group elements together, notice when I add
// the return, and then change my mind, I have to undo *twice* instead of once.
root = new JsonElement (title, new RadioGroup (group, int.Parse (radioSelected)), url);
}
}
root.jsonParent = parent;
root.LoadSections (GetArray (json, "sections"), data);
return root;
}
void AddMapping (string id, Element element)
{
if (jsonParent != null){
jsonParent.AddMapping (id, element);
return;
}
if (map == null)
map = new Dictionary<string, Element> ();
map.Add (id, element);
}
//
// Retrieves the element name "key"
//
public Element this [string key] {
get {
if (jsonParent != null)
return jsonParent [key];
if (map == null)
return null;
Element res;
if (map.TryGetValue (key, out res))
return res;
return null;
}
}
static void Error (string msg)
{
Console.WriteLine (msg);
}
static void Error (string fmt, params object [] args)
{
Error (String.Format (fmt, args));
}
static string GetString (JsonValue obj, string key)
{
if (obj.ContainsKey (key))
if (obj [key].JsonType == JsonType.String)
return (string) obj [key];
return null;
}
static JsonArray GetArray (JsonObject obj, string key)
{
if (obj.ContainsKey (key))
if (obj [key].JsonType == JsonType.Array)
return (JsonArray) obj [key];
return null;
}
static bool GetBoolean (JsonObject obj, string key)
{
try {
return (bool) obj [key];
} catch {
return false;
}
}
void LoadSections (JsonArray array, object data)
{
if (array == null)
return;
int n = array.Count;
for (int i = 0; i < n; i++){
var jsonSection = array [i];
var header = GetString (jsonSection, "header");
var footer = GetString (jsonSection, "footer");
var id = GetString (jsonSection, "id");
var section = new Section (header, footer);
if (jsonSection.ContainsKey ("elements"))
LoadSectionElements (section, jsonSection ["elements"] as JsonArray, data);
Add (section);
if (id != null)
AddMapping (id, section);
}
}
static string bundlePath;
static string ExpandPath (string path)
{
if (path != null && path.Length > 1 && path [0] == '~' && path [1] == '/'){
if (bundlePath == null)
bundlePath = NSBundle.MainBundle.BundlePath;
return Path.Combine (bundlePath, path.Substring (2));
}
return path;
}
static Element LoadBoolean (JsonObject json)
{
var caption = GetString (json, "caption");
bool bvalue = GetBoolean (json, "value");
var group = GetString (json, "group");
var onImagePath = ExpandPath (GetString (json, "on"));
var offImagePath = ExpandPath (GetString (json, "off"));
if (onImagePath != null && offImagePath != null){
var onImage = UIImage.FromFile (onImagePath);
var offImage = UIImage.FromFile (offImagePath);
return new BooleanImageElement (caption, bvalue, onImage, offImage);
} else
return new BooleanElement (caption, bvalue, group);
}
static UIKeyboardType ToKeyboardType (string kbdType)
{
switch (kbdType){
case "numbers": return UIKeyboardType.NumberPad;
case "default": return UIKeyboardType.Default;
case "ascii": return UIKeyboardType.ASCIICapable;
case "numbers-and-punctuation": return UIKeyboardType.NumbersAndPunctuation;
case "decimal": return UIKeyboardType.DecimalPad;
case "email": return UIKeyboardType.EmailAddress;
case "name": return UIKeyboardType.NamePhonePad;
case "twitter": return UIKeyboardType.Twitter;
case "url": return UIKeyboardType.Url;
default:
Console.WriteLine ("Unknown keyboard type: {0}, valid values are numbers, default, ascii, numbers-and-punctuation, decimal, email, name, twitter and url", kbdType);
break;
}
return UIKeyboardType.Default;
}
static UIReturnKeyType ToReturnKeyType (string returnKeyType)
{
switch (returnKeyType){
case "default": return UIReturnKeyType.Default;
case "done": return UIReturnKeyType.Done;
case "emergencycall": return UIReturnKeyType.EmergencyCall;
case "go": return UIReturnKeyType.Go;
case "google": return UIReturnKeyType.Google;
case "join": return UIReturnKeyType.Join;
case "next": return UIReturnKeyType.Next;
case "route": return UIReturnKeyType.Route;
case "search": return UIReturnKeyType.Search;
case "send": return UIReturnKeyType.Send;
case "yahoo": return UIReturnKeyType.Yahoo;
default:
Console.WriteLine ("Unknown return key type `{0}', valid values are default, done, emergencycall, go, google, join, next, route, search, send and yahoo");
break;
}
return UIReturnKeyType.Default;
}
static UITextAutocapitalizationType ToAutocapitalization (string auto)
{
switch (auto){
case "sentences": return UITextAutocapitalizationType.Sentences;
case "none": return UITextAutocapitalizationType.None;
case "words": return UITextAutocapitalizationType.Words;
case "all": return UITextAutocapitalizationType.AllCharacters;
default:
Console.WriteLine ("Unknown autocapitalization value: `{0}', allowed values are sentences, none, words and all");
break;
}
return UITextAutocapitalizationType.Sentences;
}
static UITextAutocorrectionType ToAutocorrect (JsonValue value)
{
if (value.JsonType == JsonType.Boolean)
return ((bool) value) ? UITextAutocorrectionType.Yes : UITextAutocorrectionType.No;
if (value.JsonType == JsonType.String){
var s = ((string) value);
if (s == "yes")
return UITextAutocorrectionType.Yes;
return UITextAutocorrectionType.No;
}
return UITextAutocorrectionType.Default;
}
static Element LoadEntry (JsonObject json, bool isPassword)
{
var caption = GetString (json, "caption");
var value = GetString (json, "value");
var placeholder = GetString (json, "placeholder");
var element = new EntryElement (caption, placeholder, value, isPassword);
if (json.ContainsKey ("keyboard"))
element.KeyboardType = ToKeyboardType (GetString (json, "keyboard"));
if (json.ContainsKey ("return-key"))
element.ReturnKeyType = ToReturnKeyType (GetString (json, "return-key"));
if (json.ContainsKey ("capitalization"))
element.AutocapitalizationType = ToAutocapitalization (GetString (json, "capitalization"));
if (json.ContainsKey ("autocorrect"))
element.AutocorrectionType = ToAutocorrect (json ["autocorrect"]);
return element;
}
static UITableViewCellAccessory ToAccessory (string accesory)
{
switch (accesory){
case "checkmark": return UITableViewCellAccessory.Checkmark;
case "detail-disclosure": return UITableViewCellAccessory.DetailDisclosureButton;
case "disclosure-indicator": return UITableViewCellAccessory.DisclosureIndicator;
}
return UITableViewCellAccessory.None;
}
static int FromHex (char c)
{
if (c >= '0' && c <= '9')
return c-'0';
if (c >= 'a' && c <= 'f')
return c-'a'+10;
if (c >= 'A' && c <= 'F')
return c-'A'+10;
Console.WriteLine ("Unexpected `{0}' in hex value for color", c);
return 0;
}
static void ColorError (string text)
{
Console.WriteLine ("Unknown color specification {0}, expecting #rgb, #rgba, #rrggbb or #rrggbbaa formats", text);
}
static UIColor ParseColor (string text)
{
int tl = text.Length;
if (tl > 1 && text [0] == '#'){
int r, g, b, a;
if (tl == 4 || tl == 5){
r = FromHex (text [1]);
g = FromHex (text [2]);
b = FromHex (text [3]);
a = tl == 5 ? FromHex (text [4]) : 15;
r = r << 4 | r;
g = g << 4 | g;
b = b << 4 | b;
a = a << 4 | a;
} else if (tl == 7 || tl == 9){
r = FromHex (text [1]) << 4 | FromHex (text [2]);
g = FromHex (text [3]) << 4 | FromHex (text [4]);
b = FromHex (text [5]) << 4 | FromHex (text [6]);
a = tl == 9 ? FromHex (text [7]) << 4 | FromHex (text [8]) : 255;
} else {
ColorError (text);
return UIColor.Black;
}
return UIColor.FromRGBA (r, g, b, a);
}
ColorError (text);
return UIColor.Black;
}
static UILineBreakMode ToLinebreakMode (string mode)
{
switch (mode){
case "character-wrap": return UILineBreakMode.CharacterWrap;
case "clip": return UILineBreakMode.Clip;
case "head-truncation": return UILineBreakMode.HeadTruncation;
case "middle-truncation": return UILineBreakMode.MiddleTruncation;
case "tail-truncation": return UILineBreakMode.TailTruncation;
case "word-wrap": return UILineBreakMode.WordWrap;
default:
Console.WriteLine ("Unexpeted linebreak mode `{0}', valid values include: character-wrap, clip, head-truncation, middle-truncation, tail-truncation and word-wrap", mode);
return UILineBreakMode.Clip;
}
}
// Parses a font in the format:
// Name[-SIZE]
// if -SIZE is omitted, then the value is SystemFontSize
//
static UIFont ToFont (string kvalue)
{
int q = kvalue.LastIndexOf ("-");
string fname = kvalue;
nfloat fsize = 0;
if (q != -1) {
nfloat.TryParse (kvalue.Substring (q+1), out fsize);
fname = kvalue.Substring (0, q);
}
if (fsize <= 0)
fsize = UIFont.SystemFontSize;
var f = UIFont.FromName (fname, fsize);
if (f == null)
return UIFont.SystemFontOfSize (12);
return f;
}
static UITableViewCellStyle ToCellStyle (string style)
{
switch (style){
case "default": return UITableViewCellStyle.Default;
case "subtitle": return UITableViewCellStyle.Subtitle;
case "value1": return UITableViewCellStyle.Value1;
case "value2": return UITableViewCellStyle.Value2;
default:
Console.WriteLine ("unknown cell style `{0}', valid values are default, subtitle, value1 and value2", style);
break;
}
return UITableViewCellStyle.Default;
}
static UITextAlignment ToAlignment (string align)
{
switch (align){
case "center": return UITextAlignment.Center;
case "left": return UITextAlignment.Left;
case "right": return UITextAlignment.Right;
default:
Console.WriteLine ("Unknown alignment `{0}'. valid values are left, center, right", align);
return UITextAlignment.Left;
}
}
//
// Creates one of the various StringElement classes, based on the
// properties set. It tries to load the most memory efficient one
// StringElement, if not, it fallsback to MultilineStringElement or
// StyledStringElement
//
static Element LoadString (JsonObject json, object data)
{
string value = null;
string caption = value;
string background = null;
NSAction ontap = null;
NSAction onaccessorytap = null;
int? lines = null;
UITableViewCellAccessory? accessory = null;
UILineBreakMode? linebreakmode = null;
UITextAlignment? alignment = null;
UIColor textcolor = null, detailcolor = null;
UIFont font = null;
UIFont detailfont = null;
UITableViewCellStyle style = UITableViewCellStyle.Value1;
foreach (var kv in json){
string kvalue = (string) kv.Value;
switch (kv.Key){
case "caption":
caption = kvalue;
break;
case "value":
value = kvalue;
break;
case "background":
background = kvalue;
break;
case "style":
style = ToCellStyle (kvalue);
break;
case "ontap": case "onaccessorytap":
string sontap = kvalue;
int p = sontap.LastIndexOf ('.');
if (p == -1)
break;
NSAction d = delegate {
string cname = sontap.Substring (0, p);
string mname = sontap.Substring (p+1);
foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()){
Type type = a.GetType (cname);
if (type != null){
var mi = type.GetMethod (mname, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (mi != null)
mi.Invoke (null, new object [] { data });
break;
}
}
};
if (kv.Key == "ontap")
ontap = d;
else
onaccessorytap = d;
break;
case "lines":
int res;
if (int.TryParse (kvalue, out res))
lines = res;
break;
case "accessory":
accessory = ToAccessory (kvalue);
break;
case "textcolor":
textcolor = ParseColor (kvalue);
break;
case "linebreak":
linebreakmode = ToLinebreakMode (kvalue);
break;
case "font":
font = ToFont (kvalue);
break;
case "subtitle":
value = kvalue;
style = UITableViewCellStyle.Subtitle;
break;
case "detailfont":
detailfont = ToFont (kvalue);
break;
case "alignment":
alignment = ToAlignment (kvalue);
break;
case "detailcolor":
detailcolor = ParseColor (kvalue);
break;
case "type":
break;
default:
Console.WriteLine ("Unknown attribute: '{0}'", kv.Key);
break;
}
}
if (caption == null)
caption = "";
if (font != null || style != UITableViewCellStyle.Value1 || detailfont != null || linebreakmode.HasValue || textcolor != null || accessory.HasValue || onaccessorytap != null || background != null || detailcolor != null){
StyledStringElement styled;
if (lines.HasValue){
styled = new StyledMultilineElement (caption, value, style);
styled.Lines = lines.Value;
} else {
styled = new StyledStringElement (caption, value, style);
}
if (ontap != null)
styled.Tapped += ontap;
if (onaccessorytap != null)
styled.AccessoryTapped += onaccessorytap;
if (font != null)
styled.Font = font;
if (detailfont != null)
styled.SubtitleFont = detailfont;
if (detailcolor != null)
styled.DetailColor = detailcolor;
if (textcolor != null)
styled.TextColor = textcolor;
if (accessory.HasValue)
styled.Accessory = accessory.Value;
if (linebreakmode.HasValue)
styled.LineBreakMode = linebreakmode.Value;
if (background != null){
if (background.Length > 1 && background [0] == '#')
styled.BackgroundColor = ParseColor (background);
else
styled.BackgroundUri = new Uri (background);
}
if (alignment.HasValue)
styled.Alignment = alignment.Value;
return styled;
} else {
StringElement se;
if (lines == 0)
se = new MultilineElement (caption, value);
else
se = new StringElement (caption, value);
if (alignment.HasValue)
se.Alignment = alignment.Value;
if (ontap != null)
se.Tapped += ontap;
return se;
}
}
static Element LoadRadio (JsonObject json, object data)
{
var caption = GetString (json, "caption");
var group = GetString (json, "group");
if (group != null)
return new RadioElement (caption, group);
else
return new RadioElement (caption);
}
static Element LoadCheckbox (JsonObject json, object data)
{
var caption = GetString (json, "caption");
var group = GetString (json, "group");
var value = GetBoolean (json, "value");
return new CheckboxElement (caption, value, group);
}
static Element LoadDateTime (JsonObject json, string type)
{
var caption = GetString (json, "caption");
var date = GetString (json, "value");
DateTime datetime;
if (!DateTime.TryParse (date, out datetime))
return null;
switch (type){
case "date":
return new DateElement (caption, datetime);
case "time":
return new TimeElement (caption, datetime);
case "datetime":
return new DateTimeElement (caption, datetime);
default:
return null;
}
}
static Element LoadHtmlElement (JsonObject json)
{
var caption = GetString (json, "caption");
var url = GetString (json, "url");
return new HtmlElement (caption, url);
}
void LoadSectionElements (Section section, JsonArray array, object data)
{
if (array == null)
return;
for (int i = 0; i < array.Count; i++){
Element element = null;
try {
var json = array [i] as JsonObject;
if (json == null)
continue;
var type = GetString (json, "type");
switch (type){
case "bool": case "boolean":
element = LoadBoolean (json);
break;
case "entry": case "password":
element = LoadEntry (json, type == "password");
break;
case "string":
element = LoadString (json, data);
break;
case "root":
element = FromJson (this, json, data);
break;
case "radio":
element = LoadRadio (json, data);
break;
case "checkbox":
element = LoadCheckbox (json, data);
break;
case "datetime":
case "date":
case "time":
element = LoadDateTime (json, type);
break;
case "html":
element = LoadHtmlElement (json);
break;
default:
Error ("json element at {0} contain an unknown type `{1}', json {2}", i, type, json);
break;
}
if (element != null){
var id = GetString (json, "id");
if (id != null)
AddMapping (id, element);
}
} catch (Exception e) {
Console.WriteLine ("Error processing Json {0}, exception {1}", array, e);
}
if (element != null)
section.Add (element);
}
}
}
}
| |
// 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.ServiceModel;
using Infrastructure.Common;
using Xunit;
public class NegotiateStream_Tcp_Tests : ConditionalWcfTest
{
// The tests are as follows:
//
// NegotiateStream_*_AmbientCredentials
// Windows: This should pass by default without any code changes
// Linux: This should not pass by default
// Run 'kinit user@DC.DOMAIN.COM' before running this test to use ambient credentials
// ('DC.DOMAIN.COM' must be in capital letters)
// If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all
// prior Kerberos tickets
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword
// Windows: Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// Linux: Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all
// prior Kerberos tickets
//
// NegotiateStream_*_With_ExplicitSpn
// Windows: Set the NegotiateTestSPN TestProperties to match a valid SPN for the server
// Linux: Set the NegotiateTestSPN TestProperties to match a valid SPN for the server
//
// By default, the SPN is the same as the host's fully qualified domain name, for example,
// 'host.domain.com'
// On a Windows host, one has to register the SPN using 'setspn', or run the process as LOCAL SYSTEM
// This can be done by setting the PSEXEC_PATH environment variable to point to the folder containing
// psexec.exe prior to starting the WCF self-host service.
//
// NegotiateStream_*_With_Upn
// Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server in the form of
// 'user@DOMAIN.COM'
// Linux: This scenario is not yet supported - dotnet/corefx#6606
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Spn
// Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server
// Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// Linux: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server
// Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Upn
// Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server
// Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// Linux: This scenario is not yet supported - dotnet/corefx#6606
// These tests are used for testing NegotiateStream (SecurityMode.Transport)
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Ambient_Credentials_Available),
nameof(WindowsOrSelfHosted))]
[OuterLoop]
public static void NegotiateStream_Tcp_AmbientCredentials()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Explicit_Credentials_Available),
nameof(Domain_Available),
nameof(WindowsOrSelfHosted))]
[OuterLoop]
// Test Requirements \\
// The following environment variables must be set...
// "NegotiateTestRealm"
// "NegotiateTestDomain"
// "ExplicitUserName"
// "ExplicitPassword"
// "ServiceUri" (server running as machine context)
public static void NegotiateStream_Tcp_With_ExplicitUserNameAndPassword()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(binding,
new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address));
factory.Credentials.Windows.ClientCredential.Domain = GetDomain();
factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName();
factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword();
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(SPN_Available),
nameof(WindowsOrSelfHosted))]
[OuterLoop]
// Test Requirements \\
// The following environment variables must be set...
// "NegotiateTestRealm"
// "NegotiateTestSpn" (host/<servername>)
// "ServiceUri" (server running as machine context)
public static void NegotiateStream_Tcp_With_ExplicitSpn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new SpnEndpointIdentity(GetSPN())
));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(SPN_Available),
nameof(WindowsOrSelfHosted))]
[OuterLoop]
public static void NegotiateStream_Tcp_With_SPN()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new SpnEndpointIdentity(GetSPN())
));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Explicit_Credentials_Available),
nameof(Domain_Available),
nameof(SPN_Available),
nameof(WindowsOrSelfHosted))]
[OuterLoop]
// Test Requirements \\
// The following environment variables must be set...
// "NegotiateTestRealm"
// "NegotiateTestDomain"
// "ExplicitUserName"
// "ExplicitPassword"
// "NegotiateTestSpn" (host/<servername>)
// "ServiceUri" (server running as machine context)
public static void NegotiateStream_Tcp_With_ExplicitUserNameAndPassword_With_Spn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new SpnEndpointIdentity(GetSPN())
));
factory.Credentials.Windows.ClientCredential.Domain = GetDomain();
factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName();
factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword();
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Issue(2147, OS = OSID.OSX | OSID.AnyUnix)]
[Condition(nameof(Windows_Authentication_Available),
nameof(Explicit_Credentials_Available),
nameof(Domain_Available),
nameof(UPN_Available))]
[OuterLoop]
public static void NegotiateStream_Tcp_With_ExplicitUserNameAndPassword_With_Upn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
NetTcpBinding binding = new NetTcpBinding();
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Tcp_DefaultBinding_Address),
new UpnEndpointIdentity(GetUPN())
));
factory.Credentials.Windows.ClientCredential.Domain = GetDomain();
factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName();
factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword();
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
| |
using System;
using System.Collections;
using Tanis.Collections;
namespace Games.Pathfinding.AStar2DTest
{
/// <summary>
/// A node class for doing pathfinding on a 2-dimensional map
/// </summary>
public class AStarNode2D : AStarNode
{
#region Properties
/// <summary>
/// The X-coordinate of the node
/// </summary>
public int X
{
get
{
return FX;
}
}
private int FX;
/// <summary>
/// The Y-coordinate of the node
/// </summary>
public int Y
{
get
{
return FY;
}
}
private int FY;
#endregion
#region Constructors
/// <summary>
/// Constructor for a node in a 2-dimensional map
/// </summary>
/// <param name="AParent">Parent of the node</param>
/// <param name="AGoalNode">Goal node</param>
/// <param name="ACost">Accumulative cost</param>
/// <param name="AX">X-coordinate</param>
/// <param name="AY">Y-coordinate</param>
public AStarNode2D(AStarNode AParent,AStarNode AGoalNode,double ACost,int AX, int AY) : base(AParent,AGoalNode,ACost)
{
FX = AX;
FY = AY;
}
#endregion
#region Private Methods
/// <summary>
/// Adds a successor to a list if it is not impassible or the parent node
/// </summary>
/// <param name="ASuccessors">List of successors</param>
/// <param name="AX">X-coordinate</param>
/// <param name="AY">Y-coordinate</param>
private void AddSuccessor(ArrayList ASuccessors,int AX,int AY)
{
int CurrentCost = MainClass.GetMap(AX,AY);
if(CurrentCost == -1)
{
return;
}
AStarNode2D NewNode = new AStarNode2D(this,GoalNode,Cost + CurrentCost,AX,AY);
if(NewNode.IsSameState(Parent))
{
return;
}
ASuccessors.Add(NewNode);
}
#endregion
#region Overidden Methods
/// <summary>
/// Determines wheather the current node is the same state as the on passed.
/// </summary>
/// <param name="ANode">AStarNode to compare the current node to</param>
/// <returns>Returns true if they are the same state</returns>
public override bool IsSameState(AStarNode ANode)
{
if(ANode == null)
{
return false;
}
return ((((AStarNode2D)ANode).X == FX) &&
(((AStarNode2D)ANode).Y == FY));
}
/// <summary>
/// Calculates the estimated cost for the remaining trip to the goal.
/// </summary>
public override void Calculate()
{
if(GoalNode != null)
{
double xd = FX - ((AStarNode2D)GoalNode).X;
double yd = FY - ((AStarNode2D)GoalNode).Y;
// "Euclidean distance" - Used when search can move at any angle.
//GoalEstimate = Math.Sqrt((xd*xd) + (yd*yd));
// "Manhattan Distance" - Used when search can only move vertically and
// horizontally.
//GoalEstimate = Math.Abs(xd) + Math.Abs(yd);
// "Diagonal Distance" - Used when the search can move in 8 directions.
GoalEstimate = Math.Max(Math.Abs(xd),Math.Abs(yd));
}
else
{
GoalEstimate = 0;
}
}
/// <summary>
/// Gets all successors nodes from the current node and adds them to the successor list
/// </summary>
/// <param name="ASuccessors">List in which the successors will be added</param>
public override void GetSuccessors(ArrayList ASuccessors)
{
ASuccessors.Clear();
AddSuccessor(ASuccessors,FX-1,FY );
AddSuccessor(ASuccessors,FX-1,FY-1);
AddSuccessor(ASuccessors,FX ,FY-1);
AddSuccessor(ASuccessors,FX+1,FY-1);
AddSuccessor(ASuccessors,FX+1,FY );
AddSuccessor(ASuccessors,FX+1,FY+1);
AddSuccessor(ASuccessors,FX ,FY+1);
AddSuccessor(ASuccessors,FX-1,FY+1);
}
/// <summary>
/// Prints information about the current node
/// </summary>
public override void PrintNodeInfo()
{
Console.WriteLine("X:\t{0}\tY:\t{1}\tCost:\t{2}\tEst:\t{3}\tTotal:\t{4}",FX,FY,Cost,GoalEstimate,TotalCost);
}
#endregion
}
/// <summary>
/// Test class for doing A* pathfinding on a 2D map.
/// </summary>
class MainClass
{
#region Test Maps
static int[,] Map = {
{ 1,-1, 1, 1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 1, 1, 1 },
{ 1,-1, 1,-1, 1,-1, 1, 2, 1, 1 },
{ 1, 1, 1,-1, 1, 1, 2, 3, 2, 1 }
};
// static int[,] Map = {
// { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1,-1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1,-1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1,-1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1,-1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1,-1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1,-1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1,-1, 1 },
// { 1,-1,-1,-1,-1,-1,-1,-1,-1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
// };
// static int[,] Map = {
// { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
// { 1, 1, 1, 1, 1, 2, 1, 1, 1, 1 },
// { 1, 1, 1, 1, 2, 3, 2, 1, 1, 1 },
// { 1, 1, 1, 2, 3, 4, 3, 2, 1, 1 },
// { 1, 1, 2, 3, 4, 5, 4, 3, 2, 1 },
// { 1, 1, 1, 2, 3, 4, 3, 2, 1, 1 },
// { 1, 1, 1, 1, 2, 3, 2, 1, 1, 1 },
// { 1, 1, 1, 1, 1, 2, 1, 1, 1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
// { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
// };
#endregion
#region Public Methods
/// <summary>
/// Gets movement cost from the 2-dimensional map
/// </summary>
/// <param name="x">X-coordinate</param>
/// <param name="y">Y-coordinate</param>
/// <returns>Returns movement cost at the specified point in the map</returns>
static public int GetMap(int x,int y)
{
if((x < 0) || (x > 9))
return(-1);
if((y < 0) || (y > 9))
return(-1);
return(Map[y,x]);
}
/// <summary>
/// Prints the solution
/// </summary>
/// <param name="ASolution">The list that holds the solution</param>
static public void PrintSolution(ArrayList ASolution)
{
for(int j=0;j<10;j++)
{
for(int i=0;i<10;i++)
{
bool solution = false;
foreach(AStarNode2D n in ASolution)
{
AStarNode2D tmp = new AStarNode2D(null,null,0,i,j);
solution = n.IsSameState(tmp);
if(solution)
break;
}
if(solution)
Console.Write("S ");
else
if(MainClass.GetMap(i,j) == -1)
Console.Write("X ");
else
Console.Write(". ");
}
Console.WriteLine("");
}
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Starting...");
Games.Pathfinding.AStar astar = new Games.Pathfinding.AStar();
AStarNode2D GoalNode = new AStarNode2D(null,null,0,9,9);
AStarNode2D StartNode = new AStarNode2D(null,GoalNode,0,0,0);
StartNode.GoalNode = GoalNode;
astar.FindPath(StartNode,GoalNode);
PrintSolution(astar.Solution);
Console.ReadLine();
}
#endregion
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using System.Xml;
using Microsoft.CSharp;
using log4net;
using FluorineFx.Exceptions;
using FluorineFx.Configuration;
using FluorineFx.Util;
namespace FluorineFx.IO.Bytecode.CodeDom
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
class AMF0ReflectionOptimizer
{
private static readonly ILog log = LogManager.GetLogger(typeof(AMF0ReflectionOptimizer));
private CompilerParameters _cp = new CompilerParameters();
protected Type _mappedClass;
protected AMFReader _reader;
protected Layouter _layouter;
public AMF0ReflectionOptimizer(Type type, AMFReader reader)
{
_mappedClass = type;
_reader = reader;
_layouter = new Layouter();
}
public IReflectionOptimizer Generate(object instance)
{
try
{
InitCompiler();
return Build(GenerateCode(instance));
}
catch (Exception)
{
return null;
}
}
private void InitCompiler()
{
_cp.GenerateInMemory = true;
if( FluorineConfiguration.Instance.OptimizerSettings.Debug )
{
_cp.GenerateInMemory = false;
_cp.IncludeDebugInformation = true;
}
_cp.TreatWarningsAsErrors = false;
#if ! DEBUG
_cp.CompilerOptions = "/optimize";
#endif
AddAssembly(Assembly.GetExecutingAssembly().Location);
Assembly classAssembly = _mappedClass.Assembly;
AddAssembly(classAssembly.Location);
foreach (AssemblyName referencedName in classAssembly.GetReferencedAssemblies())
{
Assembly referencedAssembly = Assembly.Load(referencedName);
AddAssembly(referencedAssembly.Location);
}
foreach (AssemblyName referencedName in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
{
Assembly referencedAssembly = Assembly.Load(referencedName);
AddAssembly(referencedAssembly.Location);
}
}
/// <summary>
/// Add an assembly to the list of ReferencedAssemblies
/// required to build the class
/// </summary>
/// <param name="name"></param>
private void AddAssembly(string name)
{
if (name.StartsWith("System.")) return;
if (!_cp.ReferencedAssemblies.Contains(name))
{
_cp.ReferencedAssemblies.Add(name);
}
}
private IReflectionOptimizer Build(string code)
{
CodeDomProvider provider = new CSharpCodeProvider();
CompilerResults res;
if( FluorineConfiguration.Instance.OptimizerSettings.Debug )
{
string file = Path.Combine(Path.GetTempPath(), _mappedClass.FullName.Replace('.', '_').Replace("+", "__") ) + ".cs";
StreamWriter sw = File.CreateText( file);
sw.Write(code);
sw.Close();
log.Debug(__Res.GetString(__Res.Optimizer_FileLocation, _mappedClass.FullName, file));
_cp.TempFiles = new TempFileCollection(Path.GetTempPath());
_cp.TempFiles.KeepFiles = true;
#if !(NET_1_1)
res = provider.CompileAssemblyFromFile( _cp, file );
#else
ICodeCompiler compiler = provider.CreateCompiler();
res = compiler.CompileAssemblyFromFile( _cp, file );
#endif
}
else
{
#if !(NET_1_1)
res = provider.CompileAssemblyFromSource( _cp, new string[] {code});
#else
ICodeCompiler compiler = provider.CreateCompiler();
res = compiler.CompileAssemblyFromSource( _cp, code );
#endif
}
if (res.Errors.HasErrors)
{
foreach (CompilerError e in res.Errors)
{
log.Error(__Res.GetString(__Res.Compiler_Error, e.Line, e.Column, e.ErrorText));
}
throw new InvalidOperationException(res.Errors[0].ErrorText);
}
Assembly assembly = res.CompiledAssembly;
System.Type[] types = assembly.GetTypes();
IReflectionOptimizer optimizer = (IReflectionOptimizer)assembly.CreateInstance(types[0].FullName, false, BindingFlags.CreateInstance, null, null, null, null);
return optimizer;
}
protected virtual string GetHeader()
{
return
"using System;\n" +
"using System.Reflection;\n" +
"using FluorineFx;\n" +
"using FluorineFx.AMF3;\n" +
"using FluorineFx.IO;\n" +
"using FluorineFx.Exceptions;\n" +
"using FluorineFx.Configuration;\n" +
"using FluorineFx.IO.Bytecode;\n" +
"using log4net;\n" +
"namespace FluorineFx.Bytecode.CodeDom {\n";
}
protected virtual string GetClassDefinition()
{
return
@"public class {0} : IReflectionOptimizer {{
public {0}() {{
}}
public object CreateInstance() {{
return new {1}();
}}
public object ReadData(AMFReader reader, ClassDefinition classDefinition) {{
";
}
protected virtual string GenerateCode(object instance)
{
_layouter.Append(GetHeader());
_layouter.AppendFormat(GetClassDefinition(), _mappedClass.FullName.Replace('.', '_').Replace("+", "__"), _mappedClass.FullName);
_layouter.Begin();
_layouter.Begin();
_layouter.AppendFormat("{0} instance = new {0}();", _mappedClass.FullName);
_layouter.Append("reader.AddReference(instance);");
Type type = instance.GetType();
string key = _reader.ReadString();
_layouter.Append("byte typeCode = 0;");
_layouter.Append("string key = null;");
for (byte typeCode = _reader.ReadByte(); typeCode != AMF0TypeCode.EndOfObject; typeCode = _reader.ReadByte())
{
_layouter.Append("key = reader.ReadString();");
_layouter.Append("typeCode = reader.ReadByte();");
object value = _reader.ReadData(typeCode);
_reader.SetMember(instance, key, value);
MemberInfo[] memberInfos = type.GetMember(key);
if (memberInfos != null && memberInfos.Length > 0)
GeneratePropertySet(memberInfos[0]);
else
{
//Log this error (do not throw exception), otherwise our current AMF stream becomes unreliable
log.Warn(__Res.GetString(__Res.Optimizer_Warning));
string msg = __Res.GetString(__Res.Reflection_MemberNotFound, string.Format("{0}.{1}", _mappedClass.FullName, key));
log.Warn(msg);
_layouter.AppendFormat("//{0}", msg);
_layouter.Append("reader.ReadData(typeCode);");
}
key = _reader.ReadString();
}
_layouter.Append("key = reader.ReadString();");
_layouter.Append("typeCode = reader.ReadByte();");
_layouter.Append("if( typeCode != AMF0TypeCode.EndOfObject ) throw new UnexpectedAMF();");
_layouter.Append("return instance;");
_layouter.End();
_layouter.Append("}");
_layouter.End();
_layouter.Append("}"); // Close class
_layouter.Append("}"); // Close namespace
return _layouter.ToString();
}
protected bool DoTypeCheck()
{
return FluorineConfiguration.Instance.OptimizerSettings.TypeCheck;
}
private void GeneratePropertySet(MemberInfo memberInfo)
{
Type memberType = null;
if( memberInfo is PropertyInfo )
{
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
memberType = propertyInfo.PropertyType;
}
if( memberInfo is FieldInfo )
{
FieldInfo fieldInfo = memberInfo as FieldInfo;
memberType = fieldInfo.FieldType;
}
_layouter.AppendFormat("//Setting member {0}", memberInfo.Name);
//The primitive types are: Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char, Double, Single
if( memberType.IsPrimitive || memberType == typeof(decimal) )
{
switch(Type.GetTypeCode(memberType))
{
case TypeCode.Byte:
case TypeCode.Decimal:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
_layouter.Append("if( typeCode == AMF0TypeCode.Number )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = ({1})reader.ReadDouble();", memberInfo.Name, memberType.FullName);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
break;
case TypeCode.Boolean:
_layouter.Append("if( typeCode == AMF0TypeCode.Boolean )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadBoolean();", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
break;
case TypeCode.Char:
_layouter.Append("if( typeCode == AMF0TypeCode.String )");
_layouter.Append("{");
_layouter.Begin();
_layouter.AppendFormat("string str{0} = reader.ReadString();", memberInfo.Name);
_layouter.AppendFormat("if( str{0} != null && str{0} != string.Empty )", memberInfo.Name);
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = str{0}[0];", memberInfo.Name);
_layouter.End();
_layouter.End();
_layouter.Append("}");
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
break;
}
return;
}
if( memberType.IsEnum )
{
_layouter.Append("if( typeCode == AMF0TypeCode.String )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = ({1})Enum.Parse(typeof({1}), reader.ReadString(), true);", memberInfo.Name, memberType.FullName);
_layouter.End();
_layouter.Append("else if( typeCode == AMF0TypeCode.Number )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = ({1})Enum.ToObject(typeof({1}), Convert.ToInt32(reader.ReadDouble()));", memberInfo.Name, memberType.FullName);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
return;
}
if( memberType == typeof(DateTime) )
{
_layouter.Append("if( typeCode == AMF0TypeCode.DateTime )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadDateTime();", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
return;
}
if (memberType == typeof(Guid))
{
_layouter.Append("if( typeCode == AMF0TypeCode.String )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = new Guid(reader.ReadString());", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
return;
}
if( memberType.IsValueType )
{
//structs are not handled
throw new FluorineException("Struct value types are not supported");
}
if( memberType == typeof(string) )
{
_layouter.Append("if( typeCode == AMF0TypeCode.String )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadString();", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF0TypeCode.LongString )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = reader.ReadLongString();", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF0TypeCode.Null )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF0TypeCode.Undefined )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
return;
}
if( memberType == typeof(XmlDocument) )
{
_layouter.Append("if( typeCode == AMF0TypeCode.Xml )");
_layouter.Append("{");
_layouter.Begin();
_layouter.AppendFormat("string xml{0} = reader.ReadLongString();", memberInfo.Name);
_layouter.AppendFormat("System.Xml.XmlDocument xmlDocument{0} = new System.Xml.XmlDocument();", memberInfo.Name);
_layouter.AppendFormat("xmlDocument{0}.LoadXml(xml{0});", memberInfo.Name);
_layouter.AppendFormat("instance.{0} = xmlDocument{0};", memberInfo.Name);
_layouter.End();
_layouter.Append("}");
_layouter.Append("else if( typeCode == AMF0TypeCode.Null )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else if( typeCode == AMF0TypeCode.Undefined )");
_layouter.Begin();
_layouter.AppendFormat("instance.{0} = null;", memberInfo.Name);
_layouter.End();
_layouter.Append("else");
_layouter.Begin();
if (DoTypeCheck())
GenerateThrowUnexpectedAMFException(memberInfo);
else
_layouter.Append("reader.ReadData(typeCode);");
_layouter.End();
return;
}
_layouter.AppendFormat("instance.{0} = ({1})TypeHelper.ChangeType(reader.ReadData(typeCode), typeof({1}));", memberInfo.Name, TypeHelper.GetCSharpName(memberType));
}
protected void GenerateElseThrowUnexpectedAMFException(MemberInfo memberInfo)
{
_layouter.Append("else");
_layouter.Begin();
_layouter.AppendFormat("throw new UnexpectedAMF(\"Unexpected data for member {0}\");", memberInfo.Name);
_layouter.End();
}
protected void GenerateThrowUnexpectedAMFException(MemberInfo memberInfo)
{
_layouter.AppendFormat("throw new UnexpectedAMF(\"Unexpected data for member {0}\");", memberInfo.Name);
}
protected void GenerateThrowUnexpectedAMFException(string message)
{
_layouter.AppendFormat("throw new UnexpectedAMF(\"{0}\");", message);
}
}
}
| |
namespace Microsoft.PythonTools.Options {
partial class PythonGeneralOptionsControl {
/// <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.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this._showOutputWindowForVirtualEnvCreate = new System.Windows.Forms.CheckBox();
this._showOutputWindowForPackageInstallation = new System.Windows.Forms.CheckBox();
this._autoAnalysis = new System.Windows.Forms.CheckBox();
this._updateSearchPathsForLinkedFiles = new System.Windows.Forms.CheckBox();
this._indentationInconsistentLabel = new System.Windows.Forms.Label();
this._indentationInconsistentCombo = new System.Windows.Forms.ComboBox();
this._surveyNewsCheckLabel = new System.Windows.Forms.Label();
this._surveyNewsCheckCombo = new System.Windows.Forms.ComboBox();
this._elevatePip = new System.Windows.Forms.CheckBox();
this._elevateEasyInstall = new System.Windows.Forms.CheckBox();
this._unresolvedImportWarning = new System.Windows.Forms.CheckBox();
this._clearGlobalPythonPath = new System.Windows.Forms.CheckBox();
this.tableLayoutPanel3.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.AutoSize = true;
this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel3.ColumnCount = 2;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel3.Controls.Add(this._showOutputWindowForVirtualEnvCreate, 0, 0);
this.tableLayoutPanel3.Controls.Add(this._showOutputWindowForPackageInstallation, 0, 1);
this.tableLayoutPanel3.Controls.Add(this._autoAnalysis, 0, 4);
this.tableLayoutPanel3.Controls.Add(this._updateSearchPathsForLinkedFiles, 0, 6);
this.tableLayoutPanel3.Controls.Add(this._indentationInconsistentLabel, 0, 8);
this.tableLayoutPanel3.Controls.Add(this._indentationInconsistentCombo, 1, 8);
this.tableLayoutPanel3.Controls.Add(this._surveyNewsCheckLabel, 0, 9);
this.tableLayoutPanel3.Controls.Add(this._surveyNewsCheckCombo, 1, 9);
this.tableLayoutPanel3.Controls.Add(this._elevatePip, 0, 2);
this.tableLayoutPanel3.Controls.Add(this._elevateEasyInstall, 0, 3);
this.tableLayoutPanel3.Controls.Add(this._unresolvedImportWarning, 0, 7);
this.tableLayoutPanel3.Controls.Add(this._clearGlobalPythonPath, 0, 5);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel3.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel3.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 11;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel3.Size = new System.Drawing.Size(381, 290);
this.tableLayoutPanel3.TabIndex = 0;
//
// _showOutputWindowForVirtualEnvCreate
//
this._showOutputWindowForVirtualEnvCreate.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._showOutputWindowForVirtualEnvCreate, 2);
this._showOutputWindowForVirtualEnvCreate.Location = new System.Drawing.Point(6, 3);
this._showOutputWindowForVirtualEnvCreate.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._showOutputWindowForVirtualEnvCreate.Name = "_showOutputWindowForVirtualEnvCreate";
this._showOutputWindowForVirtualEnvCreate.Size = new System.Drawing.Size(294, 17);
this._showOutputWindowForVirtualEnvCreate.TabIndex = 0;
this._showOutputWindowForVirtualEnvCreate.Text = "Show Output window when creating &virtual environments";
this._showOutputWindowForVirtualEnvCreate.UseVisualStyleBackColor = true;
//
// _showOutputWindowForPackageInstallation
//
this._showOutputWindowForPackageInstallation.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._showOutputWindowForPackageInstallation, 2);
this._showOutputWindowForPackageInstallation.Location = new System.Drawing.Point(6, 26);
this._showOutputWindowForPackageInstallation.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._showOutputWindowForPackageInstallation.Name = "_showOutputWindowForPackageInstallation";
this._showOutputWindowForPackageInstallation.Size = new System.Drawing.Size(307, 17);
this._showOutputWindowForPackageInstallation.TabIndex = 1;
this._showOutputWindowForPackageInstallation.Text = "Show Output window when &installing or removing packages";
this._showOutputWindowForPackageInstallation.UseVisualStyleBackColor = true;
//
// _autoAnalysis
//
this._autoAnalysis.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._autoAnalysis.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._autoAnalysis, 2);
this._autoAnalysis.Location = new System.Drawing.Point(6, 95);
this._autoAnalysis.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._autoAnalysis.Name = "_autoAnalysis";
this._autoAnalysis.Size = new System.Drawing.Size(259, 17);
this._autoAnalysis.TabIndex = 4;
this._autoAnalysis.Text = "&Automatically generate completion DB on first use";
this._autoAnalysis.UseVisualStyleBackColor = true;
//
// _updateSearchPathsForLinkedFiles
//
this._updateSearchPathsForLinkedFiles.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._updateSearchPathsForLinkedFiles.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._updateSearchPathsForLinkedFiles, 2);
this._updateSearchPathsForLinkedFiles.Location = new System.Drawing.Point(6, 141);
this._updateSearchPathsForLinkedFiles.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._updateSearchPathsForLinkedFiles.Name = "_updateSearchPathsForLinkedFiles";
this._updateSearchPathsForLinkedFiles.Size = new System.Drawing.Size(241, 17);
this._updateSearchPathsForLinkedFiles.TabIndex = 5;
this._updateSearchPathsForLinkedFiles.Text = "&Update search paths when adding linked files";
this._updateSearchPathsForLinkedFiles.UseVisualStyleBackColor = true;
//
// _indentationInconsistentLabel
//
this._indentationInconsistentLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._indentationInconsistentLabel.AutoEllipsis = true;
this._indentationInconsistentLabel.AutoSize = true;
this._indentationInconsistentLabel.Location = new System.Drawing.Point(6, 191);
this._indentationInconsistentLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._indentationInconsistentLabel.Name = "_indentationInconsistentLabel";
this._indentationInconsistentLabel.Size = new System.Drawing.Size(167, 13);
this._indentationInconsistentLabel.TabIndex = 7;
this._indentationInconsistentLabel.Text = "&Report inconsistent indentation as";
this._indentationInconsistentLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _indentationInconsistentCombo
//
this._indentationInconsistentCombo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._indentationInconsistentCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._indentationInconsistentCombo.FormattingEnabled = true;
this._indentationInconsistentCombo.Items.AddRange(new object[] {
"Errors",
"Warnings",
"Don\'t"});
this._indentationInconsistentCombo.Location = new System.Drawing.Point(185, 187);
this._indentationInconsistentCombo.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._indentationInconsistentCombo.Name = "_indentationInconsistentCombo";
this._indentationInconsistentCombo.Size = new System.Drawing.Size(190, 21);
this._indentationInconsistentCombo.TabIndex = 8;
//
// _surveyNewsCheckLabel
//
this._surveyNewsCheckLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._surveyNewsCheckLabel.AutoSize = true;
this._surveyNewsCheckLabel.Location = new System.Drawing.Point(6, 218);
this._surveyNewsCheckLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._surveyNewsCheckLabel.Name = "_surveyNewsCheckLabel";
this._surveyNewsCheckLabel.Size = new System.Drawing.Size(117, 13);
this._surveyNewsCheckLabel.TabIndex = 9;
this._surveyNewsCheckLabel.Text = "&Check for survey/news";
this._surveyNewsCheckLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _surveyNewsCheckCombo
//
this._surveyNewsCheckCombo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._surveyNewsCheckCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._surveyNewsCheckCombo.DropDownWidth = 172;
this._surveyNewsCheckCombo.FormattingEnabled = true;
this._surveyNewsCheckCombo.Items.AddRange(new object[] {
"Never",
"Once a day",
"Once a week",
"Once a month"});
this._surveyNewsCheckCombo.Location = new System.Drawing.Point(185, 214);
this._surveyNewsCheckCombo.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._surveyNewsCheckCombo.Name = "_surveyNewsCheckCombo";
this._surveyNewsCheckCombo.Size = new System.Drawing.Size(190, 21);
this._surveyNewsCheckCombo.TabIndex = 10;
//
// _elevatePip
//
this._elevatePip.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._elevatePip, 2);
this._elevatePip.Location = new System.Drawing.Point(6, 49);
this._elevatePip.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._elevatePip.Name = "_elevatePip";
this._elevatePip.Size = new System.Drawing.Size(170, 17);
this._elevatePip.TabIndex = 2;
this._elevatePip.Text = "Always run &pip as administrator";
this._elevatePip.UseVisualStyleBackColor = true;
//
// _elevateEasyInstall
//
this._elevateEasyInstall.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._elevateEasyInstall, 2);
this._elevateEasyInstall.Location = new System.Drawing.Point(6, 72);
this._elevateEasyInstall.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._elevateEasyInstall.Name = "_elevateEasyInstall";
this._elevateEasyInstall.Size = new System.Drawing.Size(210, 17);
this._elevateEasyInstall.TabIndex = 3;
this._elevateEasyInstall.Text = "Always run &easy_install as administrator";
this._elevateEasyInstall.UseVisualStyleBackColor = true;
//
// _unresolvedImportWarning
//
this._unresolvedImportWarning.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._unresolvedImportWarning.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._unresolvedImportWarning, 2);
this._unresolvedImportWarning.Location = new System.Drawing.Point(6, 164);
this._unresolvedImportWarning.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._unresolvedImportWarning.Name = "_unresolvedImportWarning";
this._unresolvedImportWarning.Size = new System.Drawing.Size(242, 17);
this._unresolvedImportWarning.TabIndex = 6;
this._unresolvedImportWarning.Text = "&Warn when imported module cannot be found";
this._unresolvedImportWarning.UseVisualStyleBackColor = true;
//
// _clearGlobalPythonPath
//
this._clearGlobalPythonPath.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._clearGlobalPythonPath.AutoSize = true;
this.tableLayoutPanel3.SetColumnSpan(this._clearGlobalPythonPath, 2);
this._clearGlobalPythonPath.Location = new System.Drawing.Point(6, 118);
this._clearGlobalPythonPath.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._clearGlobalPythonPath.Name = "_clearGlobalPythonPath";
this._clearGlobalPythonPath.Size = new System.Drawing.Size(238, 17);
this._clearGlobalPythonPath.TabIndex = 5;
this._clearGlobalPythonPath.Text = "&Ignore system-wide PYTHONPATH variables";
this._clearGlobalPythonPath.UseVisualStyleBackColor = true;
//
// PythonGeneralOptionsControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel3);
this.Margin = new System.Windows.Forms.Padding(6, 8, 6, 8);
this.Name = "PythonGeneralOptionsControl";
this.Size = new System.Drawing.Size(381, 290);
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.Label _surveyNewsCheckLabel;
private System.Windows.Forms.ComboBox _surveyNewsCheckCombo;
private System.Windows.Forms.CheckBox _showOutputWindowForVirtualEnvCreate;
private System.Windows.Forms.CheckBox _showOutputWindowForPackageInstallation;
private System.Windows.Forms.CheckBox _autoAnalysis;
private System.Windows.Forms.CheckBox _updateSearchPathsForLinkedFiles;
private System.Windows.Forms.Label _indentationInconsistentLabel;
private System.Windows.Forms.ComboBox _indentationInconsistentCombo;
private System.Windows.Forms.CheckBox _elevatePip;
private System.Windows.Forms.CheckBox _elevateEasyInstall;
private System.Windows.Forms.CheckBox _unresolvedImportWarning;
private System.Windows.Forms.CheckBox _clearGlobalPythonPath;
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class Return : GotoExpressionTests
{
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void JustReturnValue(object value, bool useInterpreter)
{
Type type = value.GetType();
LabelTarget target = Expression.Label(type);
Expression block = Expression.Block(
Expression.Return(target, Expression.Constant(value)),
Expression.Label(target, Expression.Default(type))
);
Expression equals = Expression.Equal(Expression.Constant(value), block);
Assert.True(Expression.Lambda<Func<bool>>(equals).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ReturnToMiddle(bool useInterpreter)
{
// The behaviour is that return jumps to a label, but does not necessarily leave a block.
LabelTarget target = Expression.Label(typeof(int));
Expression block = Expression.Block(
Expression.Return(target, Expression.Constant(1)),
Expression.Label(target, Expression.Constant(2)),
Expression.Constant(3)
);
Assert.Equal(3, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void ReturnJumps(object value, bool useInterpreter)
{
Type type = value.GetType();
LabelTarget target = Expression.Label(type);
Expression block = Expression.Block(
Expression.Return(target, Expression.Constant(value)),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value), block)).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(TypesData))]
public void NonVoidTargetReturnHasNoValue(Type type)
{
LabelTarget target = Expression.Label(type);
Assert.Throws<ArgumentException>("target", () => Expression.Return(target));
}
[Theory]
[MemberData(nameof(TypesData))]
public void NonVoidTargetReturnHasNoValueTypeExplicit(Type type)
{
LabelTarget target = Expression.Label(type);
Assert.Throws<ArgumentException>("target", () => Expression.Return(target, type));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ReturnVoidNoValue(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression block = Expression.Block(
Expression.Return(target),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target)
);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ReturnExplicitVoidNoValue(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression block = Expression.Block(
Expression.Return(target, typeof(void)),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target)
);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[MemberData(nameof(TypesData))]
public void NullValueOnNonVoidReturn(Type type)
{
Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(type)));
Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(type), default(Expression)));
Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(type), null, type));
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void ExplicitNullTypeWithValue(object value)
{
Assert.Throws<ArgumentException>("target", () => Expression.Return(Expression.Label(value.GetType()), default(Type)));
}
[Fact]
public void UnreadableLabel()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
LabelTarget target = Expression.Label(typeof(string));
Assert.Throws<ArgumentException>("value", () => Expression.Return(target, value));
Assert.Throws<ArgumentException>("value", () => Expression.Return(target, value, typeof(string)));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void CanAssignAnythingToVoid(object value, bool useInterpreter)
{
LabelTarget target = Expression.Label();
BlockExpression block = Expression.Block(
Expression.Return(target, Expression.Constant(value)),
Expression.Label(target)
);
Assert.Equal(typeof(void), block.Type);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[MemberData(nameof(NonObjectAssignableConstantValueData))]
public void CannotAssignValueTypesToObject(object value)
{
Assert.Throws<ArgumentException>(null, () => Expression.Return(Expression.Label(typeof(object)), Expression.Constant(value)));
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValueData))]
public void ExplicitTypeAssigned(object value, bool useInterpreter)
{
LabelTarget target = Expression.Label(typeof(object));
BlockExpression block = Expression.Block(
Expression.Return(target, Expression.Constant(value), typeof(object)),
Expression.Label(target, Expression.Default(typeof(object)))
);
Assert.Equal(typeof(object), block.Type);
Assert.Equal(value, Expression.Lambda<Func<object>>(block).Compile(useInterpreter)());
}
[Fact]
public void ReturnQuotesIfNecessary()
{
LabelTarget target = Expression.Label(typeof(Expression<Func<int>>));
BlockExpression block = Expression.Block(
Expression.Return(target, Expression.Lambda<Func<int>>(Expression.Constant(0))),
Expression.Label(target, Expression.Default(typeof(Expression<Func<int>>)))
);
Assert.Equal(typeof(Expression<Func<int>>), block.Type);
}
[Fact]
public void UpdateSameIsSame()
{
LabelTarget target = Expression.Label(typeof(int));
Expression value = Expression.Constant(0);
GotoExpression ret = Expression.Return(target, value);
Assert.Same(ret, ret.Update(target, value));
Assert.Same(ret, NoOpVisitor.Instance.Visit(ret));
}
[Fact]
public void UpdateDiferentValueIsDifferent()
{
LabelTarget target = Expression.Label(typeof(int));
GotoExpression ret = Expression.Return(target, Expression.Constant(0));
Assert.NotSame(ret, ret.Update(target, Expression.Constant(0)));
}
[Fact]
public void UpdateDifferentTargetIsDifferent()
{
Expression value = Expression.Constant(0);
GotoExpression ret = Expression.Return(Expression.Label(typeof(int)), value);
Assert.NotSame(ret, ret.Update(Expression.Label(typeof(int)), value));
}
[Fact]
public void OpenGenericType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(List<>)));
}
[Fact]
public static void TypeContainsGenericParameters()
{
Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(List<>.Enumerator)));
Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(List<>).MakeGenericType(typeof(List<>))));
}
[Fact]
public void PointerType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(int).MakePointerType()));
}
[Fact]
public void ByRefType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Return(Expression.Label(typeof(void)), typeof(int).MakeByRefType()));
}
}
}
| |
// 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.ObjectModel;
using System.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed partial class CSharpFormatter : Formatter
{
private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name)
{
if (typeToDisplayOpt != null)
{
// We're showing the type of a value, so "dynamic" does not apply.
bool unused;
int index1 = 0;
int index2 = 0;
AppendQualifiedTypeName(
builder,
typeToDisplayOpt,
null,
ref index1,
null,
ref index2,
escapeKeywordIdentifiers: true,
sawInvalidIdentifier: out unused);
builder.Append('.');
AppendIdentifierEscapingPotentialKeywords(builder, name, sawInvalidIdentifier: out unused);
}
else
{
builder.Append(name);
}
}
internal override string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options)
{
Debug.Assert(lmrType.IsArray);
Type originalLmrType = lmrType;
// Strip off all array types. We'll process them at the end.
while (lmrType.IsArray)
{
lmrType = lmrType.GetElementType();
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('{');
// We're showing the type of a value, so "dynamic" does not apply.
bool unused;
builder.Append(GetTypeName(new TypeAndCustomInfo(DkmClrType.Create(appDomain, lmrType)), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused)); // NOTE: call our impl directly, since we're coupled anyway.
var numSizes = sizes.Count;
builder.Append('[');
for (int i = 0; i < numSizes; i++)
{
if (i > 0)
{
builder.Append(", ");
}
var lowerBound = lowerBounds[i];
var size = sizes[i];
if (lowerBound == 0)
{
builder.Append(FormatLiteral(size, options));
}
else
{
builder.Append(FormatLiteral(lowerBound, options));
builder.Append("..");
builder.Append(FormatLiteral(size + lowerBound - 1, options));
}
}
builder.Append(']');
lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled).
while (lmrType.IsArray)
{
builder.Append('[');
builder.Append(',', lmrType.GetArrayRank() - 1);
builder.Append(']');
lmrType = lmrType.GetElementType();
}
builder.Append('}');
return pooled.ToStringAndFree();
}
internal override string GetArrayIndexExpression(int[] indices)
{
Debug.Assert(indices != null);
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('[');
bool any = false;
foreach (var index in indices)
{
if (any)
{
builder.Append(", ");
}
builder.Append(index);
any = true;
}
builder.Append(']');
return pooled.ToStringAndFree();
}
internal override string GetCastExpression(string argument, string type, bool parenthesizeArgument, bool parenthesizeEntireExpression)
{
Debug.Assert(!string.IsNullOrEmpty(argument));
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
if (parenthesizeEntireExpression)
{
builder.Append('(');
}
var castExpressionFormat = parenthesizeArgument ? "({0})({1})" : "({0}){1}";
builder.AppendFormat(castExpressionFormat, type, argument);
if (parenthesizeEntireExpression)
{
builder.Append(')');
}
return pooled.ToStringAndFree();
}
internal override string GetTupleExpression(string[] values)
{
Debug.Assert(values != null);
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('(');
bool any = false;
foreach (var value in values)
{
if (any)
{
builder.Append(", ");
}
builder.Append(value);
any = true;
}
builder.Append(')');
return pooled.ToStringAndFree();
}
internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
var usedFields = ArrayBuilder<EnumField>.GetInstance();
FillUsedEnumFields(usedFields, fields, underlyingValue);
if (usedFields.Count == 0)
{
return null;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first.
{
AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name);
if (i > 0)
{
builder.Append(" | ");
}
}
usedFields.Free();
return pooled.ToStringAndFree();
}
internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
foreach (var field in fields)
{
// First match wins (deterministic since sorted).
if (underlyingValue == field.Value)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name);
return pooled.ToStringAndFree();
}
}
return null;
}
internal override string GetObjectCreationExpression(string type, string arguments)
{
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append("new ");
builder.Append(type);
builder.Append('(');
builder.Append(arguments);
builder.Append(')');
return pooled.ToStringAndFree();
}
internal override string FormatLiteral(char c, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(c, options);
}
internal override string FormatLiteral(int value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters));
}
internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatPrimitive(value, options);
}
internal override string FormatString(string str, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(str, options);
}
}
}
| |
using System;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans.Internal
{
/// <summary>
/// This class is a convenient utility class to execute a certain asynchronous function with retries,
/// allowing to specify custom retry filters and policies.
/// </summary>
public static class AsyncExecutorWithRetries
{
public static readonly int INFINITE_RETRIES = -1;
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
public static Task ExecuteWithRetries(
Func<int, Task> action,
int maxNumErrorTries,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime,
IBackoffProvider onErrorBackOff)
{
Func<int, Task<bool>> function = async (int i) => { await action(i); return true; };
return ExecuteWithRetriesHelper<bool>(
function,
0,
0,
maxNumErrorTries,
maxExecutionTime,
DateTime.UtcNow,
null,
retryExceptionFilter,
null,
onErrorBackOff);
}
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
public static Task<T> ExecuteWithRetries<T>(
Func<int, Task<T>> function,
int maxNumErrorTries,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime,
IBackoffProvider onErrorBackOff)
{
return ExecuteWithRetries<T>(
function,
0,
maxNumErrorTries,
null,
retryExceptionFilter,
maxExecutionTime,
null,
onErrorBackOff);
}
/// <summary>
/// Execute a given function a number of times, based on retry configuration parameters.
/// </summary>
/// <param name="function">Function to execute</param>
/// <param name="maxNumSuccessTries">Maximal number of successful execution attempts.
/// ExecuteWithRetries will try to re-execute the given function again if directed so by retryValueFilter.
/// Set to -1 for unlimited number of success retries, until retryValueFilter is satisfied.
/// Set to 0 for only one success attempt, which will cause retryValueFilter to be ignored and the given function executed only once until first success.</param>
/// <param name="maxNumErrorTries">Maximal number of execution attempts due to errors.
/// Set to -1 for unlimited number of error retries, until retryExceptionFilter is satisfied.</param>
/// <param name="retryValueFilter">Filter function to indicate if successful execution should be retied.
/// Set to null to disable successful retries.</param>
/// <param name="retryExceptionFilter">Filter function to indicate if error execution should be retied.
/// Set to null to disable error retries.</param>
/// <param name="maxExecutionTime">The maximal execution time of the ExecuteWithRetries function.</param>
/// <param name="onSuccessBackOff">The backoff provider object, which determines how much to wait between success retries.</param>
/// <param name="onErrorBackOff">The backoff provider object, which determines how much to wait between error retries</param>
/// <returns></returns>
public static Task<T> ExecuteWithRetries<T>(
Func<int, Task<T>> function,
int maxNumSuccessTries,
int maxNumErrorTries,
Func<T, int, bool> retryValueFilter,
Func<Exception, int, bool> retryExceptionFilter,
TimeSpan maxExecutionTime = default(TimeSpan),
IBackoffProvider onSuccessBackOff = null,
IBackoffProvider onErrorBackOff = null)
{
return ExecuteWithRetriesHelper<T>(
function,
0,
maxNumSuccessTries,
maxNumErrorTries,
maxExecutionTime,
DateTime.UtcNow,
retryValueFilter,
retryExceptionFilter,
onSuccessBackOff,
onErrorBackOff);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static async Task<T> ExecuteWithRetriesHelper<T>(
Func<int, Task<T>> function,
int callCounter,
int maxNumSuccessTries,
int maxNumErrorTries,
TimeSpan maxExecutionTime,
DateTime startExecutionTime,
Func<T, int, bool> retryValueFilter = null,
Func<Exception, int, bool> retryExceptionFilter = null,
IBackoffProvider onSuccessBackOff = null,
IBackoffProvider onErrorBackOff = null)
{
T result = default(T);
ExceptionDispatchInfo lastExceptionInfo = null;
bool retry;
do
{
retry = false;
if (maxExecutionTime != Constants.INFINITE_TIMESPAN && maxExecutionTime != default(TimeSpan))
{
DateTime now = DateTime.UtcNow;
if (now - startExecutionTime > maxExecutionTime)
{
if (lastExceptionInfo == null)
{
throw new TimeoutException(
$"ExecuteWithRetries has exceeded its max execution time of {maxExecutionTime}. Now is {LogFormatter.PrintDate(now)}, started at {LogFormatter.PrintDate(startExecutionTime)}, passed {now - startExecutionTime}");
}
lastExceptionInfo.Throw();
}
}
int counter = callCounter;
try
{
callCounter++;
result = await function(counter);
lastExceptionInfo = null;
if (callCounter < maxNumSuccessTries || maxNumSuccessTries == INFINITE_RETRIES) // -1 for infinite retries
{
if (retryValueFilter != null)
retry = retryValueFilter(result, counter);
}
if (retry)
{
TimeSpan? delay = onSuccessBackOff?.Next(counter);
if (delay.HasValue)
{
await Task.Delay(delay.Value);
}
}
}
catch (Exception exc)
{
retry = false;
if (callCounter < maxNumErrorTries || maxNumErrorTries == INFINITE_RETRIES)
{
if (retryExceptionFilter != null)
retry = retryExceptionFilter(exc, counter);
}
if (!retry)
{
throw;
}
lastExceptionInfo = ExceptionDispatchInfo.Capture(exc);
TimeSpan? delay = onErrorBackOff?.Next(counter);
if (delay.HasValue)
{
await Task.Delay(delay.Value);
}
}
} while (retry);
return result;
}
}
// Allow multiple implementations of the backoff algorithm.
// For instance, ConstantBackoff variation that always waits for a fixed timespan,
// or a RateLimitingBackoff that keeps makes sure that some minimum time period occurs between calls to some API
// (especially useful if you use the same instance for multiple potentially simultaneous calls to ExecuteWithRetries).
// Implementations should be imutable.
// If mutable state is needed, extend the next function to pass the state from the caller.
// example: TimeSpan Next(int attempt, object state, out object newState);
public interface IBackoffProvider
{
TimeSpan Next(int attempt);
}
public class FixedBackoff : IBackoffProvider
{
private readonly TimeSpan fixedDelay;
public FixedBackoff(TimeSpan delay)
{
fixedDelay = delay;
}
public TimeSpan Next(int attempt)
{
return fixedDelay;
}
}
internal class ExponentialBackoff : IBackoffProvider
{
private readonly TimeSpan minDelay;
private readonly TimeSpan maxDelay;
private readonly TimeSpan step;
public ExponentialBackoff(TimeSpan minDelay, TimeSpan maxDelay, TimeSpan step)
{
if (minDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be a positive number.");
if (maxDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("maxDelay", maxDelay, "ExponentialBackoff max delay must be a positive number.");
if (step <= TimeSpan.Zero) throw new ArgumentOutOfRangeException("step", step, "ExponentialBackoff step must be a positive number.");
if (minDelay >= maxDelay) throw new ArgumentOutOfRangeException("minDelay", minDelay, "ExponentialBackoff min delay must be greater than max delay.");
this.minDelay = minDelay;
this.maxDelay = maxDelay;
this.step = step;
}
public TimeSpan Next(int attempt)
{
TimeSpan currMax;
try
{
long multiple = checked(1 << attempt);
currMax = minDelay + step.Multiply(multiple); // may throw OverflowException
if (currMax <= TimeSpan.Zero)
throw new OverflowException();
}
catch (OverflowException)
{
currMax = maxDelay;
}
currMax = StandardExtensions.Min(currMax, maxDelay);
if (minDelay >= currMax) throw new ArgumentOutOfRangeException($"minDelay {minDelay}, currMax = {currMax}");
return ThreadSafeRandom.NextTimeSpan(minDelay, currMax);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Buffers.Text
{
public static partial class Utf16Formatter
{
#region Constants
private const char Seperator = ',';
// Invariant formatting uses groups of 3 for each number group seperated by commas.
// ex. 1,234,567,890
private const int GroupSize = 3;
#endregion Constants
private static bool TryFormatDecimalInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int charsNeeded = digitCount + (int)((value >> 63) & 1);
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer);
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
int idx = 0;
if (value < 0)
{
Unsafe.Add(ref utf16Bytes, idx++) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (value == long.MinValue)
{
if (!TryFormatDecimalUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten))
return false;
bytesWritten += sizeof(char); // Add the minus sign
return true;
}
value = -value;
}
if (precision != StandardFormat.NoPrecision)
{
int leadingZeros = (int)precision - digitCount;
while (leadingZeros-- > 0)
Unsafe.Add(ref utf16Bytes, idx++) = '0';
}
idx += FormattingHelpers.WriteDigits(value, digitCount, ref utf16Bytes, idx);
bytesWritten = idx * sizeof(char);
return true;
}
private static bool TryFormatDecimalUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten);
// Remove a single digit from the number. This will get it below long.MaxValue
// Then we call the faster long version and follow-up with writing the last
// digit. This ends up being faster by a factor of 2 than to just do the entire
// operation using the unsigned versions.
value = FormattingHelpers.DivMod(value, 10, out ulong lastDigit);
if (precision != StandardFormat.NoPrecision && precision > 0)
precision -= 1;
if (!TryFormatDecimalInt64((long)value, precision, buffer, out bytesWritten))
return false;
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer.Slice(bytesWritten));
if (span.Length < sizeof(char))
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
FormattingHelpers.WriteDigits(lastDigit, 1, ref utf16Bytes, 0);
bytesWritten += sizeof(char);
return true;
}
private static bool TryFormatNumericInt64(long value, byte precision, Span<byte> buffer, out int bytesWritten)
{
int digitCount = FormattingHelpers.CountDigits(value);
int groupSeperators = (int)FormattingHelpers.DivMod(digitCount, GroupSize, out long firstGroup);
if (firstGroup == 0)
{
firstGroup = 3;
groupSeperators--;
}
int trailingZeros = (precision == StandardFormat.NoPrecision) ? 2 : precision;
int charsNeeded = (int)((value >> 63) & 1) + digitCount + groupSeperators;
int idx = charsNeeded;
if (trailingZeros > 0)
charsNeeded += trailingZeros + 1; // +1 for period.
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer);
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
long v = value;
if (v < 0)
{
Unsafe.Add(ref utf16Bytes, 0) = Minus;
// Abs(long.MinValue) == long.MaxValue + 1, so we need to re-route to unsigned to handle value
if (v == long.MinValue)
{
if (!TryFormatNumericUInt64((ulong)long.MaxValue + 1, precision, buffer.Slice(2), out bytesWritten))
return false;
bytesWritten += sizeof(char); // Add the minus sign
return true;
}
v = -v;
}
// Write out the trailing zeros
if (trailingZeros > 0)
{
Unsafe.Add(ref utf16Bytes, idx) = Period;
FormattingHelpers.WriteDigits(0, trailingZeros, ref utf16Bytes, idx + 1);
}
// Starting from the back, write each group of digits except the first group
while (digitCount > 3)
{
idx -= 3;
v = FormattingHelpers.DivMod(v, 1000, out long groupValue);
FormattingHelpers.WriteDigits(groupValue, 3, ref utf16Bytes, idx);
Unsafe.Add(ref utf16Bytes, --idx) = Seperator;
digitCount -= 3;
}
// Write the first group of digits.
FormattingHelpers.WriteDigits(v, (int)firstGroup, ref utf16Bytes, idx - (int)firstGroup);
bytesWritten = charsNeeded * sizeof(char);
return true;
}
private static bool TryFormatNumericUInt64(ulong value, byte precision, Span<byte> buffer, out int bytesWritten)
{
if (value <= long.MaxValue)
return TryFormatNumericInt64((long)value, precision, buffer, out bytesWritten);
// The ulong path is much slower than the long path here, so we are doing the last group
// inside this method plus the zero padding but routing to the long version for the rest.
value = FormattingHelpers.DivMod(value, 1000, out ulong lastGroup);
if (!TryFormatNumericInt64((long)value, 0, buffer, out bytesWritten))
return false;
if (precision == StandardFormat.NoPrecision)
precision = 2;
// Since this method routes entirely to the long version if the number is smaller than
// long.MaxValue, we are guaranteed to need to write 3 more digits here before the set
// of trailing zeros.
int extraChars = 4; // 3 digits + group seperator
if (precision > 0)
extraChars += precision + 1; // +1 for period.
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer.Slice(bytesWritten));
if (span.Length < extraChars)
{
bytesWritten = 0;
return false;
}
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
var idx = 0;
// Write the last group
Unsafe.Add(ref utf16Bytes, idx++) = Seperator;
idx += FormattingHelpers.WriteDigits(lastGroup, 3, ref utf16Bytes, idx);
// Write out the trailing zeros
if (precision > 0)
{
Unsafe.Add(ref utf16Bytes, idx++) = Period;
idx += FormattingHelpers.WriteDigits(0, precision, ref utf16Bytes, idx);
}
bytesWritten += extraChars * sizeof(char);
return true;
}
private static bool TryFormatHexUInt64(ulong value, byte precision, bool useLower, Span<byte> buffer, out int bytesWritten)
{
const string HexTableLower = "0123456789abcdef";
const string HexTableUpper = "0123456789ABCDEF";
var digits = 1;
var v = value;
if (v > 0xFFFFFFFF)
{
digits += 8;
v >>= 0x20;
}
if (v > 0xFFFF)
{
digits += 4;
v >>= 0x10;
}
if (v > 0xFF)
{
digits += 2;
v >>= 0x8;
}
if (v > 0xF) digits++;
int paddingCount = (precision == StandardFormat.NoPrecision) ? 0 : precision - digits;
if (paddingCount < 0) paddingCount = 0;
int charsNeeded = digits + paddingCount;
Span<char> span = MemoryMarshal.Cast<byte, char>(buffer);
if (span.Length < charsNeeded)
{
bytesWritten = 0;
return false;
}
string hexTable = useLower ? HexTableLower : HexTableUpper;
ref char utf16Bytes = ref MemoryMarshal.GetReference(span);
int idx = charsNeeded;
for (v = value; digits-- > 0; v >>= 4)
Unsafe.Add(ref utf16Bytes, --idx) = hexTable[(int)(v & 0xF)];
while (paddingCount-- > 0)
Unsafe.Add(ref utf16Bytes, --idx) = '0';
bytesWritten = charsNeeded * sizeof(char);
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public abstract class ImmutableDictionaryBuilderTestBase : ImmutablesTestBase
{
[Fact]
public void Add()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
builder.Add(new KeyValuePair<string, int>("six", 6));
Assert.Equal(5, builder["five"]);
Assert.Equal(6, builder["six"]);
Assert.False(builder.ContainsKey("four"));
}
/// <summary>
/// Verifies that "adding" an entry to the dictionary that already exists
/// with exactly the same key and value will *not* throw an exception.
/// </summary>
/// <remarks>
/// The BCL Dictionary type would throw in this circumstance.
/// But in an immutable world, not only do we not care so much since the result is the same.
/// </remarks>
[Fact]
public void AddExactDuplicate()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
builder.Add("five", 5);
Assert.Equal(1, builder.Count);
}
[Fact]
public void AddExistingKeyWithDifferentValue()
{
var builder = this.GetBuilder<string, int>();
builder.Add("five", 5);
Assert.Throws<ArgumentException>(() => builder.Add("five", 6));
}
[Fact]
public void Indexer()
{
var builder = this.GetBuilder<string, int>();
// Set and set again.
builder["five"] = 5;
Assert.Equal(5, builder["five"]);
builder["five"] = 5;
Assert.Equal(5, builder["five"]);
// Set to a new value.
builder["five"] = 50;
Assert.Equal(50, builder["five"]);
// Retrieve an invalid value.
Assert.Throws<KeyNotFoundException>(() => builder["foo"]);
}
[Fact]
public void ContainsPair()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5);
var builder = this.GetBuilder(map);
Assert.True(builder.Contains(new KeyValuePair<string, int>("five", 5)));
}
[Fact]
public void RemovePair()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
Assert.True(builder.Remove(new KeyValuePair<string, int>("five", 5)));
Assert.False(builder.Remove(new KeyValuePair<string, int>("foo", 1)));
Assert.Equal(1, builder.Count);
Assert.Equal(6, builder["six"]);
}
[Fact]
public void RemoveKey()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
builder.Remove("five");
Assert.Equal(1, builder.Count);
Assert.Equal(6, builder["six"]);
}
[Fact]
public void CopyTo()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5);
var builder = this.GetBuilder(map);
var array = new KeyValuePair<string, int>[2]; // intentionally larger than source.
builder.CopyTo(array, 1);
Assert.Equal(new KeyValuePair<string, int>(), array[0]);
Assert.Equal(new KeyValuePair<string, int>("five", 5), array[1]);
Assert.Throws<ArgumentNullException>(() => builder.CopyTo(null, 0));
}
[Fact]
public void IsReadOnly()
{
var builder = this.GetBuilder<string, int>();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Keys()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
CollectionAssertAreEquivalent(new[] { "five", "six" }, builder.Keys);
CollectionAssertAreEquivalent(new[] { "five", "six" }, ((IReadOnlyDictionary<string, int>)builder).Keys.ToArray());
}
[Fact]
public void Values()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
CollectionAssertAreEquivalent(new[] { 5, 6 }, builder.Values);
CollectionAssertAreEquivalent(new[] { 5, 6 }, ((IReadOnlyDictionary<string, int>)builder).Values.ToArray());
}
[Fact]
public void TryGetValue()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
int value;
Assert.True(builder.TryGetValue("five", out value) && value == 5);
Assert.True(builder.TryGetValue("six", out value) && value == 6);
Assert.False(builder.TryGetValue("four", out value));
Assert.Equal(0, value);
}
[Fact]
public void TryGetKey()
{
var builder = Empty<int>(StringComparer.OrdinalIgnoreCase)
.Add("a", 1).ToBuilder();
string actualKey;
Assert.True(TryGetKeyHelper(builder, "a", out actualKey));
Assert.Equal("a", actualKey);
Assert.True(TryGetKeyHelper(builder, "A", out actualKey));
Assert.Equal("a", actualKey);
Assert.False(TryGetKeyHelper(builder, "b", out actualKey));
Assert.Equal("b", actualKey);
}
[Fact]
public void EnumerateTest()
{
var map = this.GetEmptyImmutableDictionary<string, int>().Add("five", 5).Add("six", 6);
var builder = this.GetBuilder(map);
using (var enumerator = builder.GetEnumerator())
{
Assert.True(enumerator.MoveNext());
Assert.True(enumerator.MoveNext());
Assert.False(enumerator.MoveNext());
}
var manualEnum = builder.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
while (manualEnum.MoveNext()) { }
Assert.False(manualEnum.MoveNext());
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
}
[Fact]
public void IDictionaryMembers()
{
var builder = this.GetBuilder<string, int>();
var dictionary = (IDictionary)builder;
dictionary.Add("a", 1);
Assert.True(dictionary.Contains("a"));
Assert.Equal(1, dictionary["a"]);
Assert.Equal(new[] { "a" }, dictionary.Keys.Cast<string>().ToArray());
Assert.Equal(new[] { 1 }, dictionary.Values.Cast<int>().ToArray());
dictionary["a"] = 2;
Assert.Equal(2, dictionary["a"]);
dictionary.Remove("a");
Assert.False(dictionary.Contains("a"));
Assert.False(dictionary.IsFixedSize);
Assert.False(dictionary.IsReadOnly);
}
[Fact]
public void IDictionaryEnumerator()
{
var builder = this.GetBuilder<string, int>();
var dictionary = (IDictionary)builder;
dictionary.Add("a", 1);
var enumerator = dictionary.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Entry, enumerator.Current);
Assert.Equal(enumerator.Key, enumerator.Entry.Key);
Assert.Equal(enumerator.Value, enumerator.Entry.Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key);
Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void ICollectionMembers()
{
var builder = this.GetBuilder<string, int>();
var collection = (ICollection)builder;
collection.CopyTo(new object[0], 0);
builder.Add("b", 2);
Assert.True(builder.ContainsKey("b"));
var array = new object[builder.Count + 1];
collection.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new object[] { null, new DictionaryEntry("b", 2), }, array);
Assert.False(collection.IsSynchronized);
Assert.NotNull(collection.SyncRoot);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
protected abstract bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey);
/// <summary>
/// Gets the Builder for a given dictionary instance.
/// </summary>
/// <typeparam name="TKey">The type of key.</typeparam>
/// <typeparam name="TValue">The type of value.</typeparam>
/// <returns>The builder.</returns>
protected abstract IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis = null);
/// <summary>
/// Gets an empty immutable dictionary.
/// </summary>
/// <typeparam name="TKey">The type of key.</typeparam>
/// <typeparam name="TValue">The type of value.</typeparam>
/// <returns>The immutable dictionary.</returns>
protected abstract IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>();
protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer);
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace Hydra.Framework.ImageProcessing.Analysis.Filters
{
//
//**********************************************************************
/// <summary>
/// Merge filter - get MAX of two pixels
/// </summary>
//**********************************************************************
//
public sealed class Merge
: IFilter
{
#region Private Member Variables
//
//**********************************************************************
/// <summary>
/// Overlay Image bitmap
/// </summary>
//**********************************************************************
//
private Bitmap overlayImage_m;
//
//**********************************************************************
/// <summary>
/// Overlay Image Position
/// </summary>
//**********************************************************************
//
private Point overlayPos_m = new Point(0, 0);
#endregion
#region Properties
//
//**********************************************************************
/// <summary>
/// Gets or sets the overlay image property.
/// </summary>
/// <value>The overlay image.</value>
//**********************************************************************
//
public Bitmap OverlayImage
{
get
{
return overlayImage_m;
}
set
{
overlayImage_m = value;
}
}
//
//**********************************************************************
/// <summary>
/// Gets or sets the overlay position property.
/// </summary>
/// <value>The overlay pos.</value>
//**********************************************************************
//
public Point OverlayPos
{
get
{
return overlayPos_m;
}
set
{
overlayPos_m = value;
}
}
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:Merge"/> class.
/// </summary>
//**********************************************************************
//
public Merge()
{
}
//
//**********************************************************************
/// <summary>
/// Initialises a new instance of the <see cref="T:Merge"/> class.
/// </summary>
/// <param name="overlayImage">The overlay image.</param>
//**********************************************************************
//
public Merge(Bitmap overlayImage)
{
this.overlayImage_m = overlayImage;
}
#endregion
#region Public Methods
//
//**********************************************************************
/// <summary>
/// Apply filter
/// Output image will have the same dimension as source image
/// </summary>
/// <param name="srcImg">The SRC img.</param>
/// <returns></returns>
//**********************************************************************
//
public Bitmap Apply(Bitmap srcImg)
{
//
// source image and overlay must have the same pixel format
//
if (srcImg.PixelFormat != overlayImage_m.PixelFormat)
throw new ArgumentException();
//
// get source image size
//
int width = srcImg.Width;
int height = srcImg.Height;
//
// overlay position and dimension
//
int ovrX = overlayPos_m.X;
int ovrY = overlayPos_m.Y;
int ovrW = overlayImage_m.Width;
int ovrH = overlayImage_m.Height;
PixelFormat fmt = (srcImg.PixelFormat == PixelFormat.Format8bppIndexed) ?
PixelFormat.Format8bppIndexed : PixelFormat.Format24bppRgb;
//
// lock source bitmap data
//
BitmapData srcData = srcImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, fmt);
//
// create new image
//
Bitmap dstImg = (fmt == PixelFormat.Format8bppIndexed) ?
Hydra.Framework.ImageProcessing.Analysis.Image.CreateGrayscaleImage(width, height) :
new Bitmap(width, height, fmt);
//
// lock destination bitmap data
//
BitmapData dstData = dstImg.LockBits(
new Rectangle(0, 0, width, height),
ImageLockMode.ReadWrite, fmt);
//
// lock overlay image
//
BitmapData ovrData = overlayImage_m.LockBits(
new Rectangle(0, 0, ovrW, ovrH),
ImageLockMode.ReadOnly, fmt);
int pixelSize = (fmt == PixelFormat.Format8bppIndexed) ? 1 : 3;
int stride = srcData.Stride;
int offset = stride - pixelSize * width;
int ovrOffset = ovrData.Stride;
//
// do the job (Warning Unsafe Code)
//
unsafe
{
byte * src = (byte *) srcData.Scan0.ToPointer();
byte * dst = (byte *) dstData.Scan0.ToPointer();
byte * ovr = (byte *) ovrData.Scan0.ToPointer();
//
// inverse overlay position
//
ovrX = -ovrX;
ovrY = -ovrY;
//
// skip all overlay line, which are outside
//
if (ovrY > 0)
ovr += ovrData.Stride * ovrY;
if ((width == ovrW) && (height == ovrH) && (ovrX == 0) && (ovrY == 0))
{
//
// for each line
//
for (int y = 0; y < height; y++)
{
//
// for each pixel
//
for (int x = 0; x < width; x++)
{
//
// get max
//
for (int i = 0; i < pixelSize; i++, src++, dst++, ovr++)
{
*dst = (*src > *ovr) ? *src : *ovr;
}
}
src += offset;
dst += offset;
ovr += offset;
}
}
else
{
if (ovrX > 0)
ovr += (ovrX * pixelSize);
//
// overlay offset
//
if (ovrX >= 0)
ovrOffset -= pixelSize * Math.Min(ovrW - ovrX, width);
else
ovrOffset -= pixelSize * Math.Min(ovrW, width + ovrX);
//
// for each line
//
for (int y = 0; y < height; y++)
{
if ((ovrY + y < 0) || (ovrY + y >= ovrH))
{
//
// fast copy line
//
Win32.memcpy(dst, src, stride);
dst += stride;
src += stride;
}
else
{
//
// for each pixel
//
for (int x = 0; x < width; x++)
{
if ((ovrX + x < 0) || (ovrX + x >= ovrW))
{
//
// copy
//
for (int i = 0; i < pixelSize; i++, src++, dst++)
{
*dst = *src;
}
}
else
{
//
// get max
//
for (int i = 0; i < pixelSize; i++, src++, dst++, ovr++)
{
*dst = (*src > *ovr) ? *src : *ovr;
}
}
}
src += offset;
dst += offset;
ovr += ovrOffset;
}
}
}
}
//
// unlock all images
//
dstImg.UnlockBits(dstData);
srcImg.UnlockBits(srcData);
overlayImage_m.UnlockBits(ovrData);
return dstImg;
}
#endregion
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// gRPC server. A single server can server arbitrary number of services and can listen on more than one ports.
/// </summary>
public class Server
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly ServiceDefinitionCollection serviceDefinitions;
readonly ServerPortCollection ports;
readonly GrpcEnvironment environment;
readonly List<ChannelOption> options;
readonly ServerSafeHandle handle;
readonly object myLock = new object();
readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>();
readonly List<ServerPort> serverPortList = new List<ServerPort>();
readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>();
readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>();
bool startRequested;
bool shutdownRequested;
/// <summary>
/// Create a new server.
/// </summary>
/// <param name="options">Channel options.</param>
public Server(IEnumerable<ChannelOption> options = null)
{
this.serviceDefinitions = new ServiceDefinitionCollection(this);
this.ports = new ServerPortCollection(this);
this.environment = GrpcEnvironment.AddRef();
this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options))
{
this.handle = ServerSafeHandle.NewServer(environment.CompletionQueue, channelArgs);
}
}
/// <summary>
/// Services that will be exported by the server once started. Register a service with this
/// server by adding its definition to this collection.
/// </summary>
public ServiceDefinitionCollection Services
{
get
{
return serviceDefinitions;
}
}
/// <summary>
/// Ports on which the server will listen once started. Register a port with this
/// server by adding its definition to this collection.
/// </summary>
public ServerPortCollection Ports
{
get
{
return ports;
}
}
/// <summary>
/// To allow awaiting termination of the server.
/// </summary>
public Task ShutdownTask
{
get
{
return shutdownTcs.Task;
}
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
startRequested = true;
handle.Start();
AllowOneRpc();
}
}
/// <summary>
/// Requests server shutdown and when there are no more calls being serviced,
/// cleans up used resources. The returned task finishes when shutdown procedure
/// is complete.
/// </summary>
public async Task ShutdownAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(startRequested);
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
handle.ShutdownAndNotify(HandleServerShutdown, environment);
await shutdownTcs.Task.ConfigureAwait(false);
DisposeHandle();
await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false);
}
/// <summary>
/// Requests server shutdown while cancelling all the in-progress calls.
/// The returned task finishes when shutdown procedure is complete.
/// </summary>
public async Task KillAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(startRequested);
GrpcPreconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
handle.ShutdownAndNotify(HandleServerShutdown, environment);
handle.CancelAllCalls();
await shutdownTcs.Task.ConfigureAwait(false);
DisposeHandle();
await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false);
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
GrpcPreconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
/// <summary>
/// Adds a service definition.
/// </summary>
private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!startRequested);
foreach (var entry in serviceDefinition.CallHandlers)
{
callHandlers.Add(entry.Key, entry.Value);
}
serviceDefinitionsList.Add(serviceDefinition);
}
}
/// <summary>
/// Adds a listening port.
/// </summary>
private int AddPortInternal(ServerPort serverPort)
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort");
GrpcPreconditions.CheckState(!startRequested);
var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port);
int boundPort;
using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials())
{
if (nativeCredentials != null)
{
boundPort = handle.AddSecurePort(address, nativeCredentials);
}
else
{
boundPort = handle.AddInsecurePort(address);
}
}
var newServerPort = new ServerPort(serverPort, boundPort);
this.serverPortList.Add(newServerPort);
return boundPort;
}
}
/// <summary>
/// Allows one new RPC call to be received by server.
/// </summary>
private void AllowOneRpc()
{
lock (myLock)
{
if (!shutdownRequested)
{
handle.RequestCall(HandleNewServerRpc, environment);
}
}
}
private void DisposeHandle()
{
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount);
}
handle.Dispose();
}
/// <summary>
/// Selects corresponding handler for given call and handles the call.
/// </summary>
private async Task HandleCallAsync(ServerRpcNew newRpc)
{
try
{
IServerCallHandler callHandler;
if (!callHandlers.TryGetValue(newRpc.Method, out callHandler))
{
callHandler = NoSuchMethodCallHandler.Instance;
}
await callHandler.HandleCall(newRpc, environment).ConfigureAwait(false);
}
catch (Exception e)
{
Logger.Warning(e, "Exception while handling RPC.");
}
}
/// <summary>
/// Handles the native callback.
/// </summary>
private void HandleNewServerRpc(bool success, BatchContextSafeHandle ctx)
{
if (success)
{
ServerRpcNew newRpc = ctx.GetServerRpcNew(this);
// after server shutdown, the callback returns with null call
if (!newRpc.Call.IsInvalid)
{
Task.Run(async () => await HandleCallAsync(newRpc)).ConfigureAwait(false);
}
}
AllowOneRpc();
}
/// <summary>
/// Handles native callback.
/// </summary>
private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx)
{
shutdownTcs.SetResult(null);
}
/// <summary>
/// Collection of service definitions.
/// </summary>
public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition>
{
readonly Server server;
internal ServiceDefinitionCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a service definition to the server. This is how you register
/// handlers for a service with the server. Only call this before Start().
/// </summary>
public void Add(ServerServiceDefinition serviceDefinition)
{
server.AddServiceDefinitionInternal(serviceDefinition);
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerServiceDefinition> GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serviceDefinitionsList.GetEnumerator();
}
}
/// <summary>
/// Collection of server ports.
/// </summary>
public class ServerPortCollection : IEnumerable<ServerPort>
{
readonly Server server;
internal ServerPortCollection(Server server)
{
this.server = server;
}
/// <summary>
/// Adds a new port on which server should listen.
/// Only call this before Start().
/// <returns>The port on which server will be listening.</returns>
/// </summary>
public int Add(ServerPort serverPort)
{
return server.AddPortInternal(serverPort);
}
/// <summary>
/// Adds a new port on which server should listen.
/// <returns>The port on which server will be listening.</returns>
/// </summary>
/// <param name="host">the host</param>
/// <param name="port">the port. If zero, an unused port is chosen automatically.</param>
/// <param name="credentials">credentials to use to secure this port.</param>
public int Add(string host, int port, ServerCredentials credentials)
{
return Add(new ServerPort(host, port, credentials));
}
/// <summary>
/// Gets enumerator for this collection.
/// </summary>
public IEnumerator<ServerPort> GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return server.serverPortList.GetEnumerator();
}
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class Pkcs12Info
{
private PfxAsn _decoded;
private ReadOnlyMemory<byte> _authSafeContents;
public ReadOnlyCollection<Pkcs12SafeContents> AuthenticatedSafe { get; private set; }
public Pkcs12IntegrityMode IntegrityMode { get; private set; }
private Pkcs12Info()
{
}
public bool VerifyMac(string password)
{
// This extension-method call allows null.
return VerifyMac(password.AsSpan());
}
public bool VerifyMac(ReadOnlySpan<char> password)
{
if (IntegrityMode != Pkcs12IntegrityMode.Password)
{
throw new InvalidOperationException(
SR.Format(
SR.Cryptography_Pkcs12_WrongModeForVerify,
Pkcs12IntegrityMode.Password,
IntegrityMode));
}
Debug.Assert(_decoded.MacData.HasValue);
HashAlgorithmName hashAlgorithm;
int expectedOutputSize;
string algorithmValue = _decoded.MacData.Value.Mac.DigestAlgorithm.Algorithm.Value;
switch (algorithmValue)
{
case Oids.Md5:
expectedOutputSize = 128 >> 3;
hashAlgorithm = HashAlgorithmName.MD5;
break;
case Oids.Sha1:
expectedOutputSize = 160 >> 3;
hashAlgorithm = HashAlgorithmName.SHA1;
break;
case Oids.Sha256:
expectedOutputSize = 256 >> 3;
hashAlgorithm = HashAlgorithmName.SHA256;
break;
case Oids.Sha384:
expectedOutputSize = 384 >> 3;
hashAlgorithm = HashAlgorithmName.SHA384;
break;
case Oids.Sha512:
expectedOutputSize = 512 >> 3;
hashAlgorithm = HashAlgorithmName.SHA512;
break;
default:
throw new CryptographicException(
SR.Format(SR.Cryptography_UnknownHashAlgorithm, algorithmValue));
}
if (_decoded.MacData.Value.Mac.Digest.Length != expectedOutputSize)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
// Cannot use the ArrayPool or stackalloc here because CreateHMAC needs a properly bounded array.
byte[] derived = new byte[expectedOutputSize];
int iterationCount =
PasswordBasedEncryption.NormalizeIterationCount(_decoded.MacData.Value.IterationCount);
Pkcs12Kdf.DeriveMacKey(
password,
hashAlgorithm,
iterationCount,
_decoded.MacData.Value.MacSalt.Span,
derived);
using (IncrementalHash hmac = IncrementalHash.CreateHMAC(hashAlgorithm, derived))
{
hmac.AppendData(_authSafeContents.Span);
if (!hmac.TryGetHashAndReset(derived, out int bytesWritten) || bytesWritten != expectedOutputSize)
{
Debug.Fail($"TryGetHashAndReset wrote {bytesWritten} bytes when {expectedOutputSize} was expected");
throw new CryptographicException();
}
return CryptographicOperations.FixedTimeEquals(
derived,
_decoded.MacData.Value.Mac.Digest.Span);
}
}
public static Pkcs12Info Decode(
ReadOnlyMemory<byte> encodedBytes,
out int bytesConsumed,
bool skipCopy = false)
{
AsnReader reader = new AsnReader(encodedBytes, AsnEncodingRules.BER);
// Trim it to the first value
encodedBytes = reader.PeekEncodedValue();
ReadOnlyMemory<byte> maybeCopy = skipCopy ? encodedBytes : encodedBytes.ToArray();
PfxAsn pfx = PfxAsn.Decode(maybeCopy, AsnEncodingRules.BER);
// https://tools.ietf.org/html/rfc7292#section-4 only defines version 3.
if (pfx.Version != 3)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
ReadOnlyMemory<byte> authSafeBytes = ReadOnlyMemory<byte>.Empty;
Pkcs12IntegrityMode mode = Pkcs12IntegrityMode.Unknown;
if (pfx.AuthSafe.ContentType == Oids.Pkcs7Data)
{
authSafeBytes = PkcsHelpers.DecodeOctetStringAsMemory(pfx.AuthSafe.Content);
if (pfx.MacData.HasValue)
{
mode = Pkcs12IntegrityMode.Password;
}
else
{
mode = Pkcs12IntegrityMode.None;
}
}
else if (pfx.AuthSafe.ContentType == Oids.Pkcs7Signed)
{
SignedDataAsn signedData = SignedDataAsn.Decode(pfx.AuthSafe.Content, AsnEncodingRules.BER);
mode = Pkcs12IntegrityMode.PublicKey;
if (signedData.EncapContentInfo.ContentType == Oids.Pkcs7Data)
{
authSafeBytes = signedData.EncapContentInfo.Content.GetValueOrDefault();
}
if (pfx.MacData.HasValue)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
}
if (mode == Pkcs12IntegrityMode.Unknown)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
List<ContentInfoAsn> authSafeData = new List<ContentInfoAsn>();
AsnReader authSafeReader = new AsnReader(authSafeBytes, AsnEncodingRules.BER);
AsnReader sequenceReader = authSafeReader.ReadSequence();
authSafeReader.ThrowIfNotEmpty();
while (sequenceReader.HasData)
{
ContentInfoAsn.Decode(sequenceReader, out ContentInfoAsn contentInfo);
authSafeData.Add(contentInfo);
}
ReadOnlyCollection<Pkcs12SafeContents> authSafe;
if (authSafeData.Count == 0)
{
authSafe = new ReadOnlyCollection<Pkcs12SafeContents>(Array.Empty<Pkcs12SafeContents>());
}
else
{
Pkcs12SafeContents[] contentsArray = new Pkcs12SafeContents[authSafeData.Count];
for (int i = 0; i < contentsArray.Length; i++)
{
contentsArray[i] = new Pkcs12SafeContents(authSafeData[i]);
}
authSafe = new ReadOnlyCollection<Pkcs12SafeContents>(contentsArray);
}
bytesConsumed = encodedBytes.Length;
return new Pkcs12Info
{
AuthenticatedSafe = authSafe,
IntegrityMode = mode,
_decoded = pfx,
_authSafeContents = authSafeBytes,
};
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
#if FEATURE_CODEPAGES_FILE
namespace System.Text
{
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
// Our input file data structures look like:
//
// Header Structure Looks Like:
// struct NLSPlusHeader
// {
// WORD[16] filename; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // I.e: 3, 2, 0, 0
// WORD count; // 2 bytes = 42 // Number of code page index's that'll follow
// }
//
// Each code page section looks like:
// struct NLSCodePageIndex
// {
// WORD[16] codePageName; // 32 bytes
// WORD codePage; // +2 bytes = 34
// WORD byteCount; // +2 bytes = 36
// DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE.
// }
//
// Each code page then has its own header
// struct NLSCodePage
// {
// WORD[16] codePageName; // 32 bytes
// WORD[4] version; // 8 bytes = 40 // I.e: 3.2.0.0
// WORD codePage; // 2 bytes = 42
// WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS)
// WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character
// WORD byteReplace; // 2 bytes = 48 // default replacement byte(s)
// BYTE[] data; // data section
// }
[Serializable]
internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable
{
// Static & Const stuff
internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";
[NonSerialized]
protected int dataTableCodePage;
// Variables to help us allocate/mark our memory section correctly
[NonSerialized]
protected bool bFlagDataTable = true;
[NonSerialized]
protected int iExtraBytes = 0;
// Our private unicode to bytes best fit array and visa versa.
[NonSerialized]
protected char[] arrayUnicodeBestFit = null;
[NonSerialized]
protected char[] arrayBytesBestFit = null;
// This is used to help ISCII, EUCJP and ISO2022 figure out they're MlangEncodings
[NonSerialized]
protected bool m_bUseMlangTypeForSerialization = false;
[System.Security.SecuritySafeCritical] // static constructors should be safe to call
static BaseCodePageEncoding()
{
}
//
// This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME.
//
// Explicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageDataFileHeader
{
[FieldOffset(0)]
internal char TableName; // WORD[16]
[FieldOffset(0x20)]
internal ushort Version; // WORD[4]
[FieldOffset(0x28)]
internal short CodePageCount; // WORD
[FieldOffset(0x2A)]
internal short unused1; // Add a unused WORD so that CodePages is aligned with DWORD boundary.
// Otherwise, 64-bit version will fail.
[FieldOffset(0x2C)]
internal CodePageIndex CodePages; // Start of code page index
}
[StructLayout(LayoutKind.Explicit, Pack=2)]
internal unsafe struct CodePageIndex
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal short CodePage; // WORD
[FieldOffset(0x22)]
internal short ByteCount; // WORD
[FieldOffset(0x24)]
internal int Offset; // DWORD
}
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct CodePageHeader
{
[FieldOffset(0)]
internal char CodePageName; // WORD[16]
[FieldOffset(0x20)]
internal ushort VersionMajor; // WORD
[FieldOffset(0x22)]
internal ushort VersionMinor; // WORD
[FieldOffset(0x24)]
internal ushort VersionRevision;// WORD
[FieldOffset(0x26)]
internal ushort VersionBuild; // WORD
[FieldOffset(0x28)]
internal short CodePage; // WORD
[FieldOffset(0x2a)]
internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS)
[FieldOffset(0x2c)]
internal char UnicodeReplace; // WORD // default replacement unicode character
[FieldOffset(0x2e)]
internal ushort ByteReplace; // WORD // default replacement bytes
[FieldOffset(0x30)]
internal short FirstDataWord; // WORD[]
}
// Initialize our global stuff
[SecurityCritical]
unsafe static CodePageDataFileHeader* m_pCodePageFileHeader =
(CodePageDataFileHeader*)GlobalizationAssembly.GetGlobalizationResourceBytePtr(
typeof(CharUnicodeInfo).Assembly, CODE_PAGE_DATA_FILE_NAME);
// Real variables
[NonSerialized]
[SecurityCritical]
unsafe protected CodePageHeader* pCodePage = null;
// Safe handle wrapper around section map view
[System.Security.SecurityCritical] // auto-generated
[NonSerialized]
protected SafeViewOfFileHandle safeMemorySectionHandle = null;
// Safe handle wrapper around mapped file handle
[System.Security.SecurityCritical] // auto-generated
[NonSerialized]
protected SafeFileMappingHandle safeFileMappingHandle = null;
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage) : this(codepage, codepage)
{
}
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(int codepage, int dataCodePage) :
base(codepage == 0? Microsoft.Win32.Win32Native.GetACP(): codepage)
{
// Remember number of code page that we'll be using the table for.
dataTableCodePage = dataCodePage;
LoadCodePageTables();
}
// Constructor called by serialization.
[System.Security.SecurityCritical] // auto-generated
internal BaseCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0)
{
// We cannot ever call this, we've proxied ourselved to CodePageEncoding
throw new ArgumentNullException("this");
}
// ISerializable implementation
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Make sure to get teh base stuff too This throws if info is null
SerializeEncoding(info, context);
Contract.Assert(info!=null, "[BaseCodePageEncoding.GetObjectData] Expected null info to throw");
// Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
info.AddValue(m_bUseMlangTypeForSerialization ? "m_maxByteSize" : "maxCharSize",
this.IsSingleByte ? 1 : 2);
// Use this class or MLangBaseCodePageEncoding as our deserializer.
info.SetType(m_bUseMlangTypeForSerialization ? typeof(MLangCodePageEncoding) :
typeof(CodePageEncoding));
}
#endif
// We need to load tables for our code page
[System.Security.SecurityCritical] // auto-generated
private unsafe void LoadCodePageTables()
{
CodePageHeader* pCodePage = FindCodePage(dataTableCodePage);
// Make sure we have one
if (pCodePage == null)
{
// Didn't have one
throw new NotSupportedException(
Environment.GetResourceString("NotSupported_NoCodepageData", CodePage));
}
// Remember our code page
this.pCodePage = pCodePage;
// We had it, so load it
LoadManagedCodePage();
}
// Look up the code page pointer
[System.Security.SecurityCritical] // auto-generated
private static unsafe CodePageHeader* FindCodePage(int codePage)
{
// We'll have to loop through all of the m_pCodePageIndex[] items to find our code page, this isn't
// binary or anything so its not monsterously fast.
for (int i = 0; i < m_pCodePageFileHeader->CodePageCount; i++)
{
CodePageIndex* pCodePageIndex = (&(m_pCodePageFileHeader->CodePages)) + i;
if (pCodePageIndex->CodePage == codePage)
{
// Found it!
CodePageHeader* pCodePage =
(CodePageHeader*)((byte*)m_pCodePageFileHeader + pCodePageIndex->Offset);
return pCodePage;
}
}
// Couldn't find it
return null;
}
// Get our code page byte count
[System.Security.SecurityCritical] // auto-generated
internal static unsafe int GetCodePageByteSize(int codePage)
{
// Get our code page info
CodePageHeader* pCodePage = FindCodePage(codePage);
// If null return 0
if (pCodePage == null)
return 0;
Contract.Assert(pCodePage->ByteCount == 1 || pCodePage->ByteCount == 2,
"[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePage->ByteCount + ") in table");
// Return what it says for byte count
return pCodePage->ByteCount;
}
// We have a managed code page entry, so load our tables
[System.Security.SecurityCritical]
protected abstract unsafe void LoadManagedCodePage();
// Allocate memory to load our code page
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
protected unsafe byte* GetSharedMemory(int iSize)
{
// Build our name
String strName = GetMemorySectionName();
IntPtr mappedFileHandle;
// This gets shared memory for our map. If its can't, it gives us clean memory.
Byte *pMemorySection = EncodingTable.nativeCreateOpenFileMapping(strName, iSize, out mappedFileHandle);
Contract.Assert(pMemorySection != null,
"[BaseCodePageEncoding.GetSharedMemory] Expected non-null memory section to be opened");
// If that failed, we have to die.
if (pMemorySection == null)
throw new OutOfMemoryException(
Environment.GetResourceString("Arg_OutOfMemoryException"));
// if we have null file handle. this means memory was allocated after
// failing to open the mapped file.
if (mappedFileHandle != IntPtr.Zero)
{
safeMemorySectionHandle = new SafeViewOfFileHandle((IntPtr) pMemorySection, true);
safeFileMappingHandle = new SafeFileMappingHandle(mappedFileHandle, true);
}
return pMemorySection;
}
[System.Security.SecurityCritical] // auto-generated
protected unsafe virtual String GetMemorySectionName()
{
int iUseCodePage = this.bFlagDataTable ? dataTableCodePage : CodePage;
String strName = String.Format(CultureInfo.InvariantCulture, "NLS_CodePage_{0}_{1}_{2}_{3}_{4}",
iUseCodePage, this.pCodePage->VersionMajor, this.pCodePage->VersionMinor,
this.pCodePage->VersionRevision, this.pCodePage->VersionBuild);
return strName;
}
[System.Security.SecurityCritical]
protected abstract unsafe void ReadBestFitTable();
[System.Security.SecuritySafeCritical] //
internal override char[] GetBestFitUnicodeToBytesData()
{
// Read in our best fit table if necessary
if (arrayUnicodeBestFit == null) ReadBestFitTable();
Contract.Assert(arrayUnicodeBestFit != null,
"[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit");
// Normally we don't have any best fit data.
return arrayUnicodeBestFit;
}
[System.Security.SecuritySafeCritical] //
internal override char[] GetBestFitBytesToUnicodeData()
{
// Read in our best fit table if necessary
if (arrayBytesBestFit == null) ReadBestFitTable();
Contract.Assert(arrayBytesBestFit != null,
"[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit");
// Normally we don't have any best fit data.
return arrayBytesBestFit;
}
// During the AppDomain shutdown the Encoding class may already finalized and the memory section
// is invalid. so we detect that by validating the memory section handle then re-initialize the memory
// section by calling LoadManagedCodePage() method and eventually the mapped file handle and
// the memory section pointer will get finalized one more time.
[System.Security.SecurityCritical] // auto-generated
internal unsafe void CheckMemorySection()
{
if (safeMemorySectionHandle != null && safeMemorySectionHandle.DangerousGetHandle() == IntPtr.Zero)
{
LoadManagedCodePage();
}
}
}
}
#endif // FEATURE_CODEPAGES_FILE
| |
using DevExpress.XtraReports.UI;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1HeaderDataSetTableAdapters;
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports
{
partial class FormN1Page1
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormN1Page1));
this.DetailReportPage1 = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailPage1 = new DevExpress.XtraReports.UI.DetailBand();
this.DateTimeLabel = new DevExpress.XtraReports.UI.XRLabel();
this.DateTimeCaptionLabel = new DevExpress.XtraReports.UI.XRLabel();
this.xrTable9 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow21 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow22 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow23 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable6 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.cellHeaderParameters = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable7 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.tableCode = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable5 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellOrganization = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellAddress = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.tblSampleHeader = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.pictureLogo = new DevExpress.XtraReports.UI.XRPictureBox();
this.spRepHumFormN1HeaderTableAdapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1HeaderDataSetTableAdapters.spRepHumFormN1HeaderTableAdapter();
this.formN1HeaderDataSet1 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1HeaderDataSet();
this.formattingRule1 = new DevExpress.XtraReports.UI.FormattingRule();
this.xrControlStyle1 = new DevExpress.XtraReports.UI.XRControlStyle();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.detailBand1 = new DevExpress.XtraReports.UI.DetailBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable9)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableCode)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tblSampleHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.formN1HeaderDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// DetailReportPage1
//
this.DetailReportPage1.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailPage1});
this.DetailReportPage1.DataAdapter = this.spRepHumFormN1HeaderTableAdapter;
this.DetailReportPage1.DataMember = "spRepHumFormN1Header";
this.DetailReportPage1.DataSource = this.formN1HeaderDataSet1;
this.DetailReportPage1.Level = 0;
this.DetailReportPage1.Name = "DetailReportPage1";
resources.ApplyResources(this.DetailReportPage1, "DetailReportPage1");
//
// DetailPage1
//
this.DetailPage1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.DateTimeLabel,
this.DateTimeCaptionLabel,
this.xrTable9,
this.xrTable6,
this.xrTable7,
this.tableCode,
this.xrTable5,
this.tblSampleHeader,
this.pictureLogo});
resources.ApplyResources(this.DetailPage1, "DetailPage1");
this.DetailPage1.Name = "DetailPage1";
this.DetailPage1.StylePriority.UseFont = false;
this.DetailPage1.StylePriority.UsePadding = false;
//
// DateTimeLabel
//
resources.ApplyResources(this.DateTimeLabel, "DateTimeLabel");
this.DateTimeLabel.Name = "DateTimeLabel";
this.DateTimeLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.DateTimeLabel.StylePriority.UseTextAlignment = false;
//
// DateTimeCaptionLabel
//
resources.ApplyResources(this.DateTimeCaptionLabel, "DateTimeCaptionLabel");
this.DateTimeCaptionLabel.Name = "DateTimeCaptionLabel";
this.DateTimeCaptionLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.DateTimeCaptionLabel.StylePriority.UseTextAlignment = false;
//
// xrTable9
//
resources.ApplyResources(this.xrTable9, "xrTable9");
this.xrTable9.Name = "xrTable9";
this.xrTable9.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow21,
this.xrTableRow22,
this.xrTableRow23});
this.xrTable9.StylePriority.UseTextAlignment = false;
//
// xrTableRow21
//
this.xrTableRow21.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell44,
this.xrTableCell43,
this.xrTableCell42,
this.xrTableCell45,
this.xrTableCell39,
this.xrTableCell36,
this.xrTableCell35});
this.xrTableRow21.Name = "xrTableRow21";
resources.ApplyResources(this.xrTableRow21, "xrTableRow21");
//
// xrTableCell44
//
this.xrTableCell44.Name = "xrTableCell44";
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
//
// xrTableCell43
//
this.xrTableCell43.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell43.Name = "xrTableCell43";
this.xrTableCell43.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
//
// xrTableCell42
//
this.xrTableCell42.Name = "xrTableCell42";
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
//
// xrTableCell45
//
this.xrTableCell45.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
//
// xrTableCell39
//
this.xrTableCell39.Name = "xrTableCell39";
this.xrTableCell39.StylePriority.UsePadding = false;
this.xrTableCell39.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
//
// xrTableCell36
//
this.xrTableCell36.Name = "xrTableCell36";
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
//
// xrTableCell35
//
this.xrTableCell35.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.StylePriority.UseBorders = false;
this.xrTableCell35.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
//
// xrTableRow22
//
this.xrTableRow22.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell37});
this.xrTableRow22.Name = "xrTableRow22";
resources.ApplyResources(this.xrTableRow22, "xrTableRow22");
//
// xrTableCell37
//
this.xrTableCell37.Name = "xrTableCell37";
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
//
// xrTableRow23
//
this.xrTableRow23.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell41});
this.xrTableRow23.Name = "xrTableRow23";
resources.ApplyResources(this.xrTableRow23, "xrTableRow23");
//
// xrTableCell41
//
this.xrTableCell41.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
//
// xrTable6
//
resources.ApplyResources(this.xrTable6, "xrTable6");
this.xrTable6.Name = "xrTable6";
this.xrTable6.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow20});
this.xrTable6.StylePriority.UseTextAlignment = false;
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.cellHeaderParameters});
this.xrTableRow20.Name = "xrTableRow20";
resources.ApplyResources(this.xrTableRow20, "xrTableRow20");
//
// cellHeaderParameters
//
resources.ApplyResources(this.cellHeaderParameters, "cellHeaderParameters");
this.cellHeaderParameters.Multiline = true;
this.cellHeaderParameters.Name = "cellHeaderParameters";
this.cellHeaderParameters.StylePriority.UseFont = false;
//
// xrTable7
//
resources.ApplyResources(this.xrTable7, "xrTable7");
this.xrTable7.Name = "xrTable7";
this.xrTable7.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow15,
this.xrTableRow18,
this.xrTableRow19});
this.xrTable7.StylePriority.UseFont = false;
this.xrTable7.StylePriority.UseTextAlignment = false;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22});
this.xrTableRow15.Name = "xrTableRow15";
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
//
// xrTableCell22
//
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell30,
this.xrTableCell29});
this.xrTableRow18.Name = "xrTableRow18";
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
//
// xrTableCell30
//
this.xrTableCell30.Name = "xrTableCell30";
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
//
// xrTableCell29
//
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseFont = false;
this.xrTableCell29.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell31,
this.xrTableCell32});
this.xrTableRow19.Name = "xrTableRow19";
resources.ApplyResources(this.xrTableRow19, "xrTableRow19");
//
// xrTableCell31
//
this.xrTableCell31.Name = "xrTableCell31";
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
//
// xrTableCell32
//
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
//
// tableCode
//
this.tableCode.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.tableCode, "tableCode");
this.tableCode.Name = "tableCode";
this.tableCode.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow14,
this.xrTableRow17});
this.tableCode.StylePriority.UseBorders = false;
this.tableCode.StylePriority.UseFont = false;
this.tableCode.StylePriority.UseTextAlignment = false;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell24,
this.xrTableCell25,
this.xrTableCell21});
this.xrTableRow14.Name = "xrTableRow14";
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
//
// xrTableCell24
//
this.xrTableCell24.Multiline = true;
this.xrTableCell24.Name = "xrTableCell24";
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
//
// xrTableCell25
//
this.xrTableCell25.Multiline = true;
this.xrTableCell25.Name = "xrTableCell25";
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseFont = false;
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.xrTableCell27,
this.xrTableCell28});
this.xrTableRow17.Name = "xrTableRow17";
resources.ApplyResources(this.xrTableRow17, "xrTableRow17");
//
// xrTableCell26
//
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseFont = false;
//
// xrTableCell27
//
this.xrTableCell27.Name = "xrTableCell27";
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
//
// xrTableCell28
//
this.xrTableCell28.Name = "xrTableCell28";
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
//
// xrTable5
//
resources.ApplyResources(this.xrTable5, "xrTable5");
this.xrTable5.Name = "xrTable5";
this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow7,
this.xrTableRow8,
this.xrTableRow9,
this.xrTableRow11,
this.xrTableRow12,
this.xrTableRow13});
this.xrTable5.StylePriority.UseTextAlignment = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell13,
this.cellOrganization});
this.xrTableRow7.Name = "xrTableRow7";
this.xrTableRow7.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseFont = false;
//
// cellOrganization
//
this.cellOrganization.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.cellOrganization, "cellOrganization");
this.cellOrganization.Name = "cellOrganization";
this.cellOrganization.StylePriority.UseBorders = false;
this.cellOrganization.StylePriority.UseFont = false;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14,
this.cellAddress});
this.xrTableRow8.Name = "xrTableRow8";
this.xrTableRow8.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
//
// xrTableCell14
//
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseFont = false;
//
// cellAddress
//
this.cellAddress.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.cellAddress.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1Header.strOrganizationAddress")});
resources.ApplyResources(this.cellAddress, "cellAddress");
this.cellAddress.Name = "cellAddress";
this.cellAddress.StylePriority.UseBorders = false;
this.cellAddress.StylePriority.UseFont = false;
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell16,
this.xrTableCell17});
this.xrTableRow9.Name = "xrTableRow9";
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
//
// xrTableCell16
//
this.xrTableCell16.Name = "xrTableCell16";
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
//
// xrTableCell17
//
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
this.xrTableCell17.StylePriority.UseTextAlignment = false;
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell18});
this.xrTableRow11.Name = "xrTableRow11";
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
//
// xrTableCell18
//
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseFont = false;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell19});
this.xrTableRow12.Name = "xrTableRow12";
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
//
// xrTableCell19
//
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseFont = false;
this.xrTableCell19.StylePriority.UseTextAlignment = false;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell20});
this.xrTableRow13.Name = "xrTableRow13";
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
//
// xrTableCell20
//
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Multiline = true;
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseFont = false;
//
// tblSampleHeader
//
resources.ApplyResources(this.tblSampleHeader, "tblSampleHeader");
this.tblSampleHeader.BorderWidth = 2F;
this.tblSampleHeader.Name = "tblSampleHeader";
this.tblSampleHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.tblSampleHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow5,
this.xrTableRow6});
this.tblSampleHeader.StylePriority.UseBorderColor = false;
this.tblSampleHeader.StylePriority.UseBorderWidth = false;
this.tblSampleHeader.StylePriority.UsePadding = false;
this.tblSampleHeader.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1});
this.xrTableRow1.Name = "xrTableRow1";
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell2
//
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseFont = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell11,
this.xrTableCell33,
this.xrTableCell6,
this.xrTableCell4,
this.xrTableCell7,
this.xrTableCell3,
this.xrTableCell8,
this.xrTableCell5,
this.xrTableCell10,
this.xrTableCell9});
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
this.xrTableRow6.Name = "xrTableRow6";
this.xrTableRow6.StylePriority.UseFont = false;
//
// xrTableCell11
//
this.xrTableCell11.Name = "xrTableCell11";
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
//
// xrTableCell33
//
this.xrTableCell33.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
this.xrTableCell33.Multiline = true;
this.xrTableCell33.Name = "xrTableCell33";
this.xrTableCell33.StylePriority.UseBorders = false;
this.xrTableCell33.StylePriority.UseFont = false;
this.xrTableCell33.StylePriority.UseTextAlignment = false;
//
// xrTableCell6
//
this.xrTableCell6.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
//
// xrTableCell4
//
this.xrTableCell4.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
//
// xrTableCell7
//
this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
//
// xrTableCell3
//
this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
//
// xrTableCell8
//
this.xrTableCell8.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
//
// xrTableCell5
//
this.xrTableCell5.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
//
// xrTableCell10
//
this.xrTableCell10.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
//
// pictureLogo
//
this.pictureLogo.Image = ((System.Drawing.Image)(resources.GetObject("pictureLogo.Image")));
resources.ApplyResources(this.pictureLogo, "pictureLogo");
this.pictureLogo.Name = "pictureLogo";
this.pictureLogo.Sizing = DevExpress.XtraPrinting.ImageSizeMode.ZoomImage;
//
// spRepHumFormN1HeaderTableAdapter
//
this.spRepHumFormN1HeaderTableAdapter.ClearBeforeFill = true;
//
// formN1HeaderDataSet1
//
this.formN1HeaderDataSet1.DataSetName = "FormN1HeaderDataSet";
this.formN1HeaderDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// formattingRule1
//
this.formattingRule1.Name = "formattingRule1";
//
// xrControlStyle1
//
this.xrControlStyle1.Name = "xrControlStyle1";
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// detailBand1
//
resources.ApplyResources(this.detailBand1, "detailBand1");
this.detailBand1.Name = "detailBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// FormN1Page1
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailReportPage1,
this.topMarginBand1,
this.detailBand1,
this.bottomMarginBand1});
this.DataAdapter = this.spRepHumFormN1HeaderTableAdapter;
this.DataMember = "spRepHumFormN1Header";
this.DataSource = this.formN1HeaderDataSet1;
resources.ApplyResources(this, "$this");
this.FormattingRuleSheet.AddRange(new DevExpress.XtraReports.UI.FormattingRule[] {
this.formattingRule1});
this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.StyleSheet.AddRange(new DevExpress.XtraReports.UI.XRControlStyle[] {
this.xrControlStyle1});
this.Version = "14.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable9)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableCode)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tblSampleHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.formN1HeaderDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReportPage1;
private DevExpress.XtraReports.UI.DetailBand DetailPage1;
private DevExpress.XtraReports.UI.XRTable tblSampleHeader;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRPictureBox pictureLogo;
private XRTableCell xrTableCell1;
private XRTableRow xrTableRow5;
private XRTableCell xrTableCell2;
private XRTableRow xrTableRow6;
private XRTableCell xrTableCell11;
private XRTableCell xrTableCell10;
private XRTableCell xrTableCell9;
private XRTable xrTable5;
private XRTableRow xrTableRow7;
private XRTableCell cellOrganization;
private XRTableCell xrTableCell13;
private XRTableRow xrTableRow8;
private XRTableCell xrTableCell14;
private XRTableCell cellAddress;
private XRTableRow xrTableRow9;
private XRTableCell xrTableCell16;
private XRTableCell xrTableCell17;
private XRTableRow xrTableRow11;
private XRTableCell xrTableCell18;
private XRTableRow xrTableRow12;
private XRTableCell xrTableCell19;
private XRTableRow xrTableRow13;
private XRTableCell xrTableCell20;
private XRTable tableCode;
private XRTableRow xrTableRow14;
private XRTableCell xrTableCell21;
private XRTable xrTable7;
private XRTableRow xrTableRow15;
private XRTableCell xrTableCell22;
private XRTableCell xrTableCell24;
private XRTableCell xrTableCell25;
private XRTableRow xrTableRow17;
private XRTableCell xrTableCell26;
private XRTableCell xrTableCell27;
private XRTableCell xrTableCell28;
private XRTableRow xrTableRow18;
private XRTableCell xrTableCell30;
private XRTableCell xrTableCell29;
private XRTableRow xrTableRow19;
private XRTableCell xrTableCell31;
private XRTableCell xrTableCell32;
private XRTableCell xrTableCell33;
private XRTable xrTable9;
private XRTableRow xrTableRow21;
private XRTableCell xrTableCell35;
private XRTable xrTable6;
private XRTableRow xrTableRow20;
private XRTableCell cellHeaderParameters;
private FormattingRule formattingRule1;
private XRControlStyle xrControlStyle1;
private XRTableCell xrTableCell39;
private XRTableCell xrTableCell36;
private XRTableRow xrTableRow22;
private XRTableCell xrTableCell37;
private XRTableRow xrTableRow23;
private XRTableCell xrTableCell41;
private XRTableCell xrTableCell44;
private XRTableCell xrTableCell43;
private XRTableCell xrTableCell42;
private XRTableCell xrTableCell45;
private TopMarginBand topMarginBand1;
private DetailBand detailBand1;
private BottomMarginBand bottomMarginBand1;
private XRTableCell xrTableCell6;
private XRTableCell xrTableCell4;
private XRTableCell xrTableCell7;
private XRTableCell xrTableCell3;
private XRTableCell xrTableCell8;
private XRTableCell xrTableCell5;
private spRepHumFormN1HeaderTableAdapter spRepHumFormN1HeaderTableAdapter;
private FormN1HeaderDataSet formN1HeaderDataSet1;
private XRLabel DateTimeLabel;
private XRLabel DateTimeCaptionLabel;
}
}
| |
//
// CMSampelBuffer.cs: Implements the managed CMSampleBuffer
//
// Authors: Mono Team
//
// Copyright 2010 Novell, Inc
//
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
#if !COREBUILD
using MonoMac.CoreVideo;
#endif
namespace MonoMac.CoreMedia {
[Since (4,0)]
public class CMSampleBuffer : INativeObject, IDisposable {
internal IntPtr handle;
internal CMSampleBuffer (IntPtr handle)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CMSampleBuffer (IntPtr handle, bool owns)
{
if (!owns)
CFObject.CFRetain (handle);
this.handle = handle;
}
~CMSampleBuffer ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
/* [DllImport(Constants.CoreMediaLibrary)]
int CMAudioSampleBufferCreateWithPacketDescriptions (
CFAllocatorRef allocator,
CMBlockBufferRef dataBuffer,
Boolean dataReady,
CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
void *makeDataReadyRefcon,
CMFormatDescriptionRef formatDescription,
int numSamples,
CMTime sbufPTS,
const AudioStreamPacketDescription *packetDescriptions,
CMSampleBufferRef *sBufOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCallForEachSample (
CMSampleBufferRef sbuf,
int (*callback)(CMSampleBufferRef sampleBuffer, int index, void *refcon),
void *refcon
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCopySampleBufferForRange (
CFAllocatorRef allocator,
CMSampleBufferRef sbuf,
CFRange sampleRange,
CMSampleBufferRef *sBufOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCreate (
CFAllocatorRef allocator,
CMBlockBufferRef dataBuffer,
Boolean dataReady,
CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
void *makeDataReadyRefcon,
CMFormatDescriptionRef formatDescription,
int numSamples,
int numSampleTimingEntries,
const CMSampleTimingInfo *sampleTimingArray,
int numSampleSizeEntries,
const uint *sampleSizeArray,
CMSampleBufferRef *sBufOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCreateCopy (
CFAllocatorRef allocator,
CMSampleBufferRef sbuf,
CMSampleBufferRef *sbufCopyOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCreateCopyWithNewTiming (
CFAllocatorRef allocator,
CMSampleBufferRef originalSBuf,
int numSampleTimingEntries,
const CMSampleTimingInfo *sampleTimingArray,
CMSampleBufferRef *sBufCopyOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferCreateForImageBuffer (
CFAllocatorRef allocator,
CVImageBufferRef imageBuffer,
Boolean dataReady,
CMSampleBufferMakeDataReadyCallback makeDataReadyCallback,
void *makeDataReadyRefcon,
CMVideoFormatDescriptionRef formatDescription,
const CMSampleTimingInfo *sampleTiming,
CMSampleBufferRef *sBufOut
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static bool CMSampleBufferDataIsReady (IntPtr handle);
public bool DataIsReady
{
get
{
return CMSampleBufferDataIsReady (handle);
}
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer (
CMSampleBufferRef sbuf,
uint *bufferListSizeNeededOut,
AudioBufferList *bufferListOut,
uint bufferListSize,
CFAllocatorRef bbufStructAllocator,
CFAllocatorRef bbufMemoryAllocator,
uint32_t flags,
CMBlockBufferRef *blockBufferOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetAudioStreamPacketDescriptions (
CMSampleBufferRef sbuf,
uint packetDescriptionsSize,
AudioStreamPacketDescription *packetDescriptionsOut,
uint *packetDescriptionsSizeNeededOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetAudioStreamPacketDescriptionsPtr (
CMSampleBufferRef sbuf,
const AudioStreamPacketDescription **packetDescriptionsPtrOut,
uint *packetDescriptionsSizeOut
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetDataBuffer (IntPtr handle);
public CMBlockBuffer GetDataBuffer ()
{
var blockHandle = CMSampleBufferGetDataBuffer (handle);
if (blockHandle == IntPtr.Zero)
{
return null;
}
else
{
return new CMBlockBuffer (blockHandle, false);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetDecodeTimeStamp (IntPtr handle);
public CMTime DecodeTimeStamp
{
get
{
return CMSampleBufferGetDecodeTimeStamp (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetDuration (IntPtr handle);
public CMTime Duration
{
get
{
return CMSampleBufferGetDuration (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetFormatDescription (IntPtr handle);
public CMFormatDescription GetFormatDescription ()
{
var desc = default(CMFormatDescription);
var descHandle = CMSampleBufferGetFormatDescription (handle);
if (descHandle != IntPtr.Zero)
{
desc = new CMFormatDescription (descHandle, false);
}
return desc;
}
#if !COREBUILD
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetImageBuffer (IntPtr handle);
public CVImageBuffer GetImageBuffer ()
{
IntPtr ib = CMSampleBufferGetImageBuffer (handle);
if (ib == IntPtr.Zero)
return null;
var ibt = CFType.GetTypeID (ib);
if (ibt == CVPixelBuffer.CVImageBufferType)
return new CVPixelBuffer (ib, false);
return new CVImageBuffer (ib, false);
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferGetNumSamples (IntPtr handle);
public int NumSamples
{
get
{
return CMSampleBufferGetNumSamples (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetOutputDecodeTimeStamp (IntPtr handle);
public CMTime OutputDecodeTimeStamp
{
get
{
return CMSampleBufferGetOutputDecodeTimeStamp (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetOutputDuration (IntPtr handle);
public CMTime OutputDuration
{
get
{
return CMSampleBufferGetOutputDuration (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetOutputPresentationTimeStamp (IntPtr handle);
public CMTime OutputPresentationTimeStamp
{
get
{
return CMSampleBufferGetOutputPresentationTimeStamp (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferSetOutputPresentationTimeStamp (IntPtr handle, CMTime outputPresentationTimeStamp);
public int SetOutputPresentationTimeStamp (CMTime outputPresentationTimeStamp)
{
return CMSampleBufferSetOutputPresentationTimeStamp (handle, outputPresentationTimeStamp);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetOutputSampleTimingInfoArray (
CMSampleBufferRef sbuf,
int timingArrayEntries,
CMSampleTimingInfo *timingArrayOut,
int *timingArrayEntriesNeededOut
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static CMTime CMSampleBufferGetPresentationTimeStamp (IntPtr handle);
public CMTime PresentationTimeStamp
{
get
{
return CMSampleBufferGetPresentationTimeStamp (handle);
}
}
#if !COREBUILD
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMSampleBufferGetSampleAttachmentsArray (IntPtr handle, bool createIfNecessary);
public NSMutableDictionary [] GetSampleAttachments (bool createIfNecessary)
{
var cfArrayRef = CMSampleBufferGetSampleAttachmentsArray (handle, createIfNecessary);
if (cfArrayRef == IntPtr.Zero)
{
return new NSMutableDictionary [0];
}
else
{
return NSArray.ArrayFromHandle (cfArrayRef, h => (NSMutableDictionary) Runtime.GetNSObject (h));
}
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static uint CMSampleBufferGetSampleSize (IntPtr handle, int sampleIndex);
public uint GetSampleSize (int sampleIndex)
{
return CMSampleBufferGetSampleSize (handle, sampleIndex);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetSampleSizeArray (
CMSampleBufferRef sbuf,
int sizeArrayEntries,
uint *sizeArrayOut,
int *sizeArrayEntriesNeededOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetSampleTimingInfo (
CMSampleBufferRef sbuf,
int sampleIndex,
CMSampleTimingInfo *timingInfoOut
);
[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferGetSampleTimingInfoArray (
CMSampleBufferRef sbuf,
int timingArrayEntries,
CMSampleTimingInfo *timingArrayOut,
int *timingArrayEntriesNeededOut
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static uint CMSampleBufferGetTotalSampleSize (IntPtr handle);
public uint TotalSampleSize
{
get
{
return CMSampleBufferGetTotalSampleSize (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferGetTypeID ();
public static int GetTypeID ()
{
return CMSampleBufferGetTypeID ();
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferInvalidate (IntPtr handle);
public int Invalidate()
{
return CMSampleBufferInvalidate (handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static bool CMSampleBufferIsValid (IntPtr handle);
public bool IsValid
{
get
{
return CMSampleBufferIsValid (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferMakeDataReady (IntPtr handle);
public int MakeDataReady ()
{
return CMSampleBufferMakeDataReady (handle);
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferSetDataBuffer (IntPtr handle, IntPtr dataBufferHandle);
public int SetDataBuffer (CMBlockBuffer dataBuffer)
{
var dataBufferHandle = IntPtr.Zero;
if (dataBuffer != null)
{
dataBufferHandle = dataBuffer.handle;
}
return CMSampleBufferSetDataBuffer (handle, dataBufferHandle);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferSetDataBufferFromAudioBufferList (
CMSampleBufferRef sbuf,
CFAllocatorRef bbufStructAllocator,
CFAllocatorRef bbufMemoryAllocator,
uint32_t flags,
const AudioBufferList *bufferList
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferSetDataReady (IntPtr handle);
public int SetDataReady ()
{
return CMSampleBufferSetDataReady (handle);
}
/*[DllImport(Constants.CoreMediaLibrary)]
int CMSampleBufferSetInvalidateCallback (
CMSampleBufferRef sbuf,
CMSampleBufferInvalidateCallback invalidateCallback,
uint64_t invalidateRefCon
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMSampleBufferTrackDataReadiness (IntPtr handle, IntPtr handleToTrack);
public int TrackDataReadiness (CMSampleBuffer bufferToTrack)
{
var handleToTrack = IntPtr.Zero;
if (bufferToTrack != null) {
handleToTrack = bufferToTrack.handle;
}
return CMSampleBufferTrackDataReadiness (handle, handleToTrack);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using Lua511;
namespace NLua
{
/*
* Type checking and conversion functions.
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
class CheckType
{
private ObjectTranslator translator;
ExtractValue extractNetObject;
Dictionary<long, ExtractValue> extractValues = new Dictionary<long, ExtractValue>();
public CheckType(ObjectTranslator translator)
{
this.translator = translator;
extractValues.Add(typeof(object).TypeHandle.Value.ToInt64(), new ExtractValue(getAsObject));
extractValues.Add(typeof(sbyte).TypeHandle.Value.ToInt64(), new ExtractValue(getAsSbyte));
extractValues.Add(typeof(byte).TypeHandle.Value.ToInt64(), new ExtractValue(getAsByte));
extractValues.Add(typeof(short).TypeHandle.Value.ToInt64(), new ExtractValue(getAsShort));
extractValues.Add(typeof(ushort).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUshort));
extractValues.Add(typeof(int).TypeHandle.Value.ToInt64(), new ExtractValue(getAsInt));
extractValues.Add(typeof(uint).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUint));
extractValues.Add(typeof(long).TypeHandle.Value.ToInt64(), new ExtractValue(getAsLong));
extractValues.Add(typeof(ulong).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUlong));
extractValues.Add(typeof(double).TypeHandle.Value.ToInt64(), new ExtractValue(getAsDouble));
extractValues.Add(typeof(char).TypeHandle.Value.ToInt64(), new ExtractValue(getAsChar));
extractValues.Add(typeof(float).TypeHandle.Value.ToInt64(), new ExtractValue(getAsFloat));
extractValues.Add(typeof(decimal).TypeHandle.Value.ToInt64(), new ExtractValue(getAsDecimal));
extractValues.Add(typeof(bool).TypeHandle.Value.ToInt64(), new ExtractValue(getAsBoolean));
extractValues.Add(typeof(string).TypeHandle.Value.ToInt64(), new ExtractValue(getAsString));
extractValues.Add(typeof(LuaFunction).TypeHandle.Value.ToInt64(), new ExtractValue(getAsFunction));
extractValues.Add(typeof(LuaTable).TypeHandle.Value.ToInt64(), new ExtractValue(getAsTable));
extractValues.Add(typeof(LuaUserData).TypeHandle.Value.ToInt64(), new ExtractValue(getAsUserdata));
extractValues.Add(typeof(Color).TypeHandle.Value.ToInt64(), new ExtractValue(getAsColor));
extractNetObject = new ExtractValue(getAsNetObject);
}
/*
* Checks if the value at Lua stack index stackPos matches paramType,
* returning a conversion function if it does and null otherwise.
*/
internal ExtractValue getExtractor(IReflect paramType)
{
return getExtractor(paramType.UnderlyingSystemType);
}
internal ExtractValue getExtractor(Type paramType)
{
if(paramType.IsByRef) paramType=paramType.GetElementType();
long runtimeHandleValue = paramType.TypeHandle.Value.ToInt64();
if(extractValues.ContainsKey(runtimeHandleValue))
return extractValues[runtimeHandleValue];
else
return extractNetObject;
}
internal ExtractValue checkType(IntPtr luaState,int stackPos,Type paramType)
{
LuaTypes luatype = LuaDLL.lua_type(luaState, stackPos);
if(paramType.IsByRef) paramType=paramType.GetElementType();
Type underlyingType = Nullable.GetUnderlyingType(paramType);
if (underlyingType != null)
{
paramType = underlyingType; // Silently convert nullable types to their non null requics
}
long runtimeHandleValue = paramType.TypeHandle.Value.ToInt64();
if (paramType.Equals(typeof(object)))
return extractValues[runtimeHandleValue];
//CP: Added support for generic parameters
if (paramType.IsGenericParameter)
{
if (luatype == LuaTypes.LUA_TBOOLEAN)
return extractValues[typeof(bool).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TSTRING)
return extractValues[typeof(string).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TTABLE)
return extractValues[typeof(LuaTable).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TUSERDATA)
return extractValues[typeof(object).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TFUNCTION)
return extractValues[typeof(LuaFunction).TypeHandle.Value.ToInt64()];
else if (luatype == LuaTypes.LUA_TNUMBER)
return extractValues[typeof(double).TypeHandle.Value.ToInt64()];
else
;//an unsupported type was encountered
}
if (LuaDLL.lua_isnumber(luaState, stackPos))
return extractValues[runtimeHandleValue];
if (paramType == typeof(bool))
{
if (LuaDLL.lua_isboolean(luaState, stackPos))
return extractValues[runtimeHandleValue];
}
else if (paramType == typeof(Color))
{
return extractValues[runtimeHandleValue];
}
else if (paramType == typeof(string) || paramType == typeof(char[]))
{
if (LuaDLL.lua_isstring(luaState, stackPos))
return extractValues[runtimeHandleValue];
else if (luatype == LuaTypes.LUA_TNIL)
return extractNetObject; // kevinh - silently convert nil to a null string pointer
}
else if (paramType == typeof(LuaTable))
{
if (luatype == LuaTypes.LUA_TTABLE)
return extractValues[runtimeHandleValue];
}
else if (paramType == typeof(LuaUserData))
{
if (luatype == LuaTypes.LUA_TUSERDATA)
return extractValues[runtimeHandleValue];
}
else if (paramType == typeof(LuaFunction))
{
if (luatype == LuaTypes.LUA_TFUNCTION)
return extractValues[runtimeHandleValue];
}
else if (typeof(Delegate).IsAssignableFrom(paramType) && luatype == LuaTypes.LUA_TFUNCTION)
{
return new ExtractValue(new DelegateGenerator(translator, paramType).extractGenerated);
}
else if (paramType.IsInterface && luatype == LuaTypes.LUA_TTABLE)
{
return new ExtractValue(new ClassGenerator(translator, paramType).extractGenerated);
}
else if ((paramType.IsInterface || paramType.IsClass) && luatype == LuaTypes.LUA_TNIL)
{
// kevinh - allow nil to be silently converted to null - extractNetObject will return null when the item ain't found
return extractNetObject;
}
else if (LuaDLL.lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE)
{
if (LuaDLL.luaL_getmetafield(luaState, stackPos, "__index"))
{
object obj = translator.getNetObject(luaState, -1);
LuaDLL.lua_settop(luaState, -2);
if (obj != null && paramType.IsAssignableFrom(obj.GetType()))
return extractNetObject;
}
else
return null;
}
else
{
object obj = translator.getNetObject(luaState, stackPos);
if (obj != null && paramType.IsAssignableFrom(obj.GetType()))
return extractNetObject;
}
return null;
}
/*
* The following functions return the value in the Lua stack
* index stackPos as the desired type if it can, or null
* otherwise.
*/
private object getAsSbyte(IntPtr luaState,int stackPos)
{
sbyte retVal=(sbyte)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsByte(IntPtr luaState,int stackPos)
{
byte retVal=(byte)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsShort(IntPtr luaState,int stackPos)
{
short retVal=(short)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsUshort(IntPtr luaState,int stackPos)
{
ushort retVal=(ushort)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsInt(IntPtr luaState,int stackPos)
{
int retVal=(int)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsUint(IntPtr luaState,int stackPos)
{
uint retVal=(uint)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsLong(IntPtr luaState,int stackPos)
{
long retVal=(long)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsUlong(IntPtr luaState,int stackPos)
{
ulong retVal=(ulong)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsDouble(IntPtr luaState,int stackPos)
{
double retVal=LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsChar(IntPtr luaState,int stackPos)
{
char retVal=(char)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsFloat(IntPtr luaState,int stackPos)
{
float retVal=(float)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsDecimal(IntPtr luaState,int stackPos)
{
decimal retVal=(decimal)LuaDLL.lua_tonumber(luaState,stackPos);
if(retVal==0 && !LuaDLL.lua_isnumber(luaState,stackPos)) return null;
return retVal;
}
private object getAsBoolean(IntPtr luaState,int stackPos)
{
return LuaDLL.lua_toboolean(luaState,stackPos);
}
private object getAsString(IntPtr luaState,int stackPos)
{
string retVal=LuaDLL.lua_tostring(luaState,stackPos);
if(retVal=="" && !LuaDLL.lua_isstring(luaState,stackPos)) return null;
return retVal;
}
private object getAsColor(IntPtr luaState, int stackPos)
{
try
{
if (LuaDLL.lua_isnumber(luaState, stackPos))
{
Color retVal = Color.FromArgb((int)(long)LuaDLL.lua_tonumber(luaState, stackPos));
return retVal;
}
else if (LuaDLL.lua_isstring(luaState, stackPos))
{
Color retVal = Color.FromName(LuaDLL.lua_tostring(luaState, stackPos));
return retVal;
}
return null;
}
catch (Exception)
{
return null;
}
}
private object getAsTable(IntPtr luaState,int stackPos)
{
return translator.getTable(luaState,stackPos);
}
private object getAsFunction(IntPtr luaState,int stackPos)
{
return translator.getFunction(luaState,stackPos);
}
private object getAsUserdata(IntPtr luaState,int stackPos)
{
return translator.getUserData(luaState,stackPos);
}
public object getAsObject(IntPtr luaState,int stackPos)
{
if(LuaDLL.lua_type(luaState,stackPos)==LuaTypes.LUA_TTABLE)
{
if(LuaDLL.luaL_getmetafield(luaState,stackPos,"__index"))
{
if(LuaDLL.luaL_checkmetatable(luaState,-1))
{
LuaDLL.lua_insert(luaState,stackPos);
LuaDLL.lua_remove(luaState,stackPos+1);
}
else
{
LuaDLL.lua_settop(luaState,-2);
}
}
}
object obj=translator.getObject(luaState,stackPos);
return obj;
}
public object getAsNetObject(IntPtr luaState,int stackPos)
{
object obj=translator.getNetObject(luaState,stackPos);
if(obj==null && LuaDLL.lua_type(luaState,stackPos)==LuaTypes.LUA_TTABLE)
{
if(LuaDLL.luaL_getmetafield(luaState,stackPos,"__index"))
{
if(LuaDLL.luaL_checkmetatable(luaState,-1))
{
LuaDLL.lua_insert(luaState,stackPos);
LuaDLL.lua_remove(luaState,stackPos+1);
obj=translator.getNetObject(luaState,stackPos);
}
else
{
LuaDLL.lua_settop(luaState,-2);
}
}
}
return obj;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Booking.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);
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface IEmployeeDepartmentHistoryOriginalData : ISchemaBaseOriginalData
{
System.DateTime StartDate { get; }
string EndDate { get; }
Department Department { get; }
Shift Shift { get; }
}
public partial class EmployeeDepartmentHistory : OGM<EmployeeDepartmentHistory, EmployeeDepartmentHistory.EmployeeDepartmentHistoryData, System.String>, ISchemaBase, INeo4jBase, IEmployeeDepartmentHistoryOriginalData
{
#region Initialize
static EmployeeDepartmentHistory()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, EmployeeDepartmentHistory> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.EmployeeDepartmentHistoryAlias, IWhereQuery> query)
{
q.EmployeeDepartmentHistoryAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.EmployeeDepartmentHistory.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"EmployeeDepartmentHistory => StartDate : {this.StartDate}, EndDate : {this.EndDate?.ToString() ?? "null"}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new EmployeeDepartmentHistoryData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.StartDate == null)
throw new PersistenceException(string.Format("Cannot save EmployeeDepartmentHistory with key '{0}' because the StartDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save EmployeeDepartmentHistory with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class EmployeeDepartmentHistoryData : Data<System.String>
{
public EmployeeDepartmentHistoryData()
{
}
public EmployeeDepartmentHistoryData(EmployeeDepartmentHistoryData data)
{
StartDate = data.StartDate;
EndDate = data.EndDate;
Department = data.Department;
Shift = data.Shift;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "EmployeeDepartmentHistory";
Department = new EntityCollection<Department>(Wrapper, Members.Department, item => { if (Members.Department.Events.HasRegisteredChangeHandlers) { int loadHack = item.EmployeeDepartmentHistories.Count; } });
Shift = new EntityCollection<Shift>(Wrapper, Members.Shift);
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("StartDate", Conversion<System.DateTime, long>.Convert(StartDate));
dictionary.Add("EndDate", EndDate);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("StartDate", out value))
StartDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("EndDate", out value))
EndDate = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface IEmployeeDepartmentHistory
public System.DateTime StartDate { get; set; }
public string EndDate { get; set; }
public EntityCollection<Department> Department { get; private set; }
public EntityCollection<Shift> Shift { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface IEmployeeDepartmentHistory
public System.DateTime StartDate { get { LazyGet(); return InnerData.StartDate; } set { if (LazySet(Members.StartDate, InnerData.StartDate, value)) InnerData.StartDate = value; } }
public string EndDate { get { LazyGet(); return InnerData.EndDate; } set { if (LazySet(Members.EndDate, InnerData.EndDate, value)) InnerData.EndDate = value; } }
public Department Department
{
get { return ((ILookupHelper<Department>)InnerData.Department).GetItem(null); }
set
{
if (LazySet(Members.Department, ((ILookupHelper<Department>)InnerData.Department).GetItem(null), value))
((ILookupHelper<Department>)InnerData.Department).SetItem(value, null);
}
}
private void ClearDepartment(DateTime? moment)
{
((ILookupHelper<Department>)InnerData.Department).ClearLookup(moment);
}
public Shift Shift
{
get { return ((ILookupHelper<Shift>)InnerData.Shift).GetItem(null); }
set
{
if (LazySet(Members.Shift, ((ILookupHelper<Shift>)InnerData.Shift).GetItem(null), value))
((ILookupHelper<Shift>)InnerData.Shift).SetItem(value, null);
}
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static EmployeeDepartmentHistoryMembers members = null;
public static EmployeeDepartmentHistoryMembers Members
{
get
{
if (members == null)
{
lock (typeof(EmployeeDepartmentHistory))
{
if (members == null)
members = new EmployeeDepartmentHistoryMembers();
}
}
return members;
}
}
public class EmployeeDepartmentHistoryMembers
{
internal EmployeeDepartmentHistoryMembers() { }
#region Members for interface IEmployeeDepartmentHistory
public Property StartDate { get; } = Datastore.AdventureWorks.Model.Entities["EmployeeDepartmentHistory"].Properties["StartDate"];
public Property EndDate { get; } = Datastore.AdventureWorks.Model.Entities["EmployeeDepartmentHistory"].Properties["EndDate"];
public Property Department { get; } = Datastore.AdventureWorks.Model.Entities["EmployeeDepartmentHistory"].Properties["Department"];
public Property Shift { get; } = Datastore.AdventureWorks.Model.Entities["EmployeeDepartmentHistory"].Properties["Shift"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static EmployeeDepartmentHistoryFullTextMembers fullTextMembers = null;
public static EmployeeDepartmentHistoryFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(EmployeeDepartmentHistory))
{
if (fullTextMembers == null)
fullTextMembers = new EmployeeDepartmentHistoryFullTextMembers();
}
}
return fullTextMembers;
}
}
public class EmployeeDepartmentHistoryFullTextMembers
{
internal EmployeeDepartmentHistoryFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(EmployeeDepartmentHistory))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["EmployeeDepartmentHistory"];
}
}
return entity;
}
private static EmployeeDepartmentHistoryEvents events = null;
public static EmployeeDepartmentHistoryEvents Events
{
get
{
if (events == null)
{
lock (typeof(EmployeeDepartmentHistory))
{
if (events == null)
events = new EmployeeDepartmentHistoryEvents();
}
}
return events;
}
}
public class EmployeeDepartmentHistoryEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<EmployeeDepartmentHistory, EntityEventArgs> onNew;
public event EventHandler<EmployeeDepartmentHistory, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<EmployeeDepartmentHistory, EntityEventArgs> onDelete;
public event EventHandler<EmployeeDepartmentHistory, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<EmployeeDepartmentHistory, EntityEventArgs> onSave;
public event EventHandler<EmployeeDepartmentHistory, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnStartDate
private static bool onStartDateIsRegistered = false;
private static EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> onStartDate;
public static event EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> OnStartDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
Members.StartDate.Events.OnChange += onStartDateProxy;
onStartDateIsRegistered = true;
}
onStartDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStartDate -= value;
if (onStartDate == null && onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
onStartDateIsRegistered = false;
}
}
}
}
private static void onStartDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> handler = onStartDate;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnEndDate
private static bool onEndDateIsRegistered = false;
private static EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> onEndDate;
public static event EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> OnEndDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
Members.EndDate.Events.OnChange += onEndDateProxy;
onEndDateIsRegistered = true;
}
onEndDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onEndDate -= value;
if (onEndDate == null && onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
onEndDateIsRegistered = false;
}
}
}
}
private static void onEndDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> handler = onEndDate;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnDepartment
private static bool onDepartmentIsRegistered = false;
private static EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> onDepartment;
public static event EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> OnDepartment
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onDepartmentIsRegistered)
{
Members.Department.Events.OnChange -= onDepartmentProxy;
Members.Department.Events.OnChange += onDepartmentProxy;
onDepartmentIsRegistered = true;
}
onDepartment += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onDepartment -= value;
if (onDepartment == null && onDepartmentIsRegistered)
{
Members.Department.Events.OnChange -= onDepartmentProxy;
onDepartmentIsRegistered = false;
}
}
}
}
private static void onDepartmentProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> handler = onDepartment;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnShift
private static bool onShiftIsRegistered = false;
private static EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> onShift;
public static event EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> OnShift
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onShiftIsRegistered)
{
Members.Shift.Events.OnChange -= onShiftProxy;
Members.Shift.Events.OnChange += onShiftProxy;
onShiftIsRegistered = true;
}
onShift += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onShift -= value;
if (onShift == null && onShiftIsRegistered)
{
Members.Shift.Events.OnChange -= onShiftProxy;
onShiftIsRegistered = false;
}
}
}
}
private static void onShiftProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> handler = onShift;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> onModifiedDate;
public static event EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> onUid;
public static event EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<EmployeeDepartmentHistory, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((EmployeeDepartmentHistory)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IEmployeeDepartmentHistoryOriginalData
public IEmployeeDepartmentHistoryOriginalData OriginalVersion { get { return this; } }
#region Members for interface IEmployeeDepartmentHistory
System.DateTime IEmployeeDepartmentHistoryOriginalData.StartDate { get { return OriginalData.StartDate; } }
string IEmployeeDepartmentHistoryOriginalData.EndDate { get { return OriginalData.EndDate; } }
Department IEmployeeDepartmentHistoryOriginalData.Department { get { return ((ILookupHelper<Department>)OriginalData.Department).GetOriginalItem(null); } }
Shift IEmployeeDepartmentHistoryOriginalData.Shift { get { return ((ILookupHelper<Shift>)OriginalData.Shift).GetOriginalItem(null); } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
//__________________________________________________________________________________________________
//
// Copyright (C) 2021, Mariusz Postol LODZ POLAND.
//
// To be in touch join the community at GitHub: https://github.com/mpostol/OPC-UA-OOI/discussions
//__________________________________________________________________________________________________
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using UAOOI.SemanticData.BuildingErrorsHandling;
namespace UAOOI.SemanticData.UANodeSetValidation.DataSerialization
{
/// <summary>
/// Extends a node id by adding a complete namespace URI.
/// </summary>
/// <remarks>
/// Extends a node id by adding a complete namespace URI.
/// </remarks>
public partial class ExpandedNodeId : IComparable, IFormattable, ICloneable
{
#region Constructors
/// <summary>
/// Initializes the object with default values.
/// </summary>
/// <remarks>
/// Creates a new instance of the object, accepting the default values.
/// </remarks>
internal ExpandedNodeId()
{
Initialize();
}
/// <summary>
/// Creates a deep copy of the value.
/// </summary>
/// <remarks>
/// Creates a new instance of the object, while copying the properties of the specified object.
/// </remarks>
/// <param name="value">The ExpandedNodeId to copy</param>
/// <exception cref="ArgumentNullException">Thrown when the parameter is null</exception>
public ExpandedNodeId(ExpandedNodeId value)
{
if (value == null) throw new ArgumentNullException("value");
m_namespaceUri = value.m_namespaceUri;
if (value.m_nodeId != null)
m_nodeId = value.m_nodeId;
}
/// <summary>
/// Initializes an expanded node identifier with a node id.
/// </summary>
/// <remarks>
/// Creates a new instance of the object, while wrapping the specified <see cref="NodeId"/>.
/// </remarks>
/// <param name="nodeId">The <see cref="NodeId"/> to wrap</param>
public ExpandedNodeId(NodeId nodeId)
{
Initialize();
if (nodeId != null)
m_nodeId = nodeId;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpandedNodeId"/> class.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <param name="namespaceIndex">The namespace index.</param>
/// <param name="namespaceUri">The namespace URI.</param>
/// <param name="serverIndex">The server index.</param>
public ExpandedNodeId(object identifier, ushort namespaceIndex, string namespaceUri, uint serverIndex)
{
m_nodeId = new NodeId(identifier, namespaceIndex);
m_namespaceUri = namespaceUri;
m_serverIndex = serverIndex;
}
/// <summary>
/// Initializes an expanded node identifier with a node id and a namespace URI.
/// </summary>
/// <remarks>
/// Creates a new instance of the object while allowing you to specify both the
/// <see cref="NodeId"/> and the Namespace URI that applies to the NodeID.
/// </remarks>
/// <param name="namespaceUri">The namespace that this node belongs to</param>
/// <param name="nodeId">The <see cref="NodeId"/> to wrap.</param>
public ExpandedNodeId(NodeId nodeId, string namespaceUri)
{
Initialize();
if (nodeId != null)
m_nodeId = nodeId;
if (!String.IsNullOrEmpty(namespaceUri))
SetNamespaceUri(namespaceUri);
}
/// <summary>
/// Initializes an expanded node identifier with a node id and a namespace URI.
/// </summary>
/// <remarks>
/// Creates a new instance of the object while allowing you to specify both the
/// <see cref="NodeId"/> and the Namespace URI that applies to the NodeID.
/// </remarks>
/// <param name="nodeId">The <see cref="NodeId"/> to wrap.</param>
/// <param name="namespaceUri">The namespace that this node belongs to</param>
/// <param name="serverIndex">The server that the node belongs to</param>
public ExpandedNodeId(NodeId nodeId, string namespaceUri, uint serverIndex)
{
Initialize();
if (nodeId != null)
m_nodeId = nodeId;
if (!String.IsNullOrEmpty(namespaceUri))
SetNamespaceUri(namespaceUri);
m_serverIndex = serverIndex;
}
/// <summary>
/// Initializes a numeric node identifier.
/// </summary>
/// <remarks>
/// Creates a new instance of the object while accepting the numeric id/value of
/// the NodeID we are wrapping.
/// </remarks>
/// <param name="value">The numeric id of a node to wrap</param>
public ExpandedNodeId(uint value)
{
Initialize();
m_nodeId = new NodeId(value);
}
/// <summary>
/// Initializes a guid node identifier with a namespace index.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while accepting both the id and namespace
/// of the node we are wrapping.
/// </remarks>
/// <param name="namespaceIndex">The namspace index that this node belongs to</param>
/// <param name="value">The numeric id of the node we are wrapping</param>
public ExpandedNodeId(uint value, ushort namespaceIndex)
{
Initialize();
m_nodeId = new NodeId(value, namespaceIndex);
}
/// <summary>
/// Initializes a guid node identifier with a namespace URI.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while accepting both the numeric id of the
/// node, along with the actual namespace that this node belongs to.
/// </remarks>
/// <param name="namespaceUri">The namespace that this node belongs to</param>
/// <param name="value">The numeric id of the node we are wrapping</param>
public ExpandedNodeId(uint value, string namespaceUri)
{
Initialize();
m_nodeId = new NodeId(value);
SetNamespaceUri(namespaceUri);
}
/// <summary>
/// Initializes a string node identifier with a namespace index.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while allowing you to specify both the
/// node and the namespace.
/// </remarks>
/// <param name="namespaceIndex">The numeric index of the namespace within the table, that this node belongs to</param>
/// <param name="value">The string id/value of the node we are wrapping</param>
public ExpandedNodeId(string value, ushort namespaceIndex)
{
Initialize();
m_nodeId = new NodeId(value, namespaceIndex);
}
/// <summary>
/// Initializes a string node identifier with a namespace URI.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while allowing you to specify both the node and namespace
/// </remarks>
/// <param name="namespaceUri">The actual namespace URI that this node belongs to</param>
/// <param name="value">The string value/id of the node we are wrapping</param>
public ExpandedNodeId(string value, string namespaceUri)
{
Initialize();
m_nodeId = new NodeId(value, 0);
SetNamespaceUri(namespaceUri);
}
/// <summary>
/// Initializes a guid node identifier.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while specifying the <see cref="Guid"/> value
/// of the node we are wrapping.
/// </remarks>
/// <param name="value">The Guid value of the node we are wrapping</param>
public ExpandedNodeId(System.Guid value)
{
Initialize();
m_nodeId = new NodeId(value);
}
/// <summary>
/// Initializes a guid node identifier.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while allowing you to specify the byte[] id
/// of the node.
/// </remarks>
/// <param name="value">The id of the node we are wrapping</param>
public ExpandedNodeId(byte[] value)
{
Initialize();
m_nodeId = new NodeId(value);
}
/// <summary>
/// Initializes an opaque node identifier with a namespace index.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while allowing you to specify the node
/// and namespace index.
/// </remarks>
/// <param name="namespaceIndex">The index of the namespace that this node should belong to</param>
/// <param name="value">The id of the node we are wrapping</param>
public ExpandedNodeId(byte[] value, ushort namespaceIndex)
{
Initialize();
m_nodeId = new NodeId(value, namespaceIndex);
}
/// <summary>
/// Initializes an opaque node identifier with a namespace index.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while allowing you to specify the node and namespace.
/// </remarks>
/// <param name="namespaceUri">The namespace that this node belongs to</param>
/// <param name="value">The node we are wrapping</param>
public ExpandedNodeId(byte[] value, string namespaceUri)
{
Initialize();
m_nodeId = new NodeId(value);
SetNamespaceUri(namespaceUri);
}
/// <summary>
/// Initializes a node id by parsing a node id string.
/// </summary>
/// <remarks>
/// Creates a new instance of the class while allowing you to specify the id of the node.
/// </remarks>
/// <param name="text">The textual id of the node being wrapped</param>
public ExpandedNodeId(string text)
{
Initialize();
m_nodeId = new NodeId(text);
}
/// <summary>
/// Sets the private members to default values.
/// </summary>
/// <remarks>
/// Sets the private members to default values.
/// </remarks>
private void Initialize()
{
m_nodeId = null;
m_namespaceUri = null;
m_serverIndex = 0;
}
#endregion Constructors
#region Public Properties
/// <summary>
/// The index of the namespace URI in the server's namespace array.
/// </summary>
/// <remarks>
/// The index of the namespace URI in the server's namespace array.
/// </remarks>
public virtual ushort NamespaceIndex
{
get
{
if (m_nodeId != null)
return m_nodeId.NamespaceIndex;
return 0;
}
}
/// <summary>
/// The type of node identifier used.
/// </summary>
/// <remarks>
/// The type of node identifier used.
/// </remarks>
public IdType IdType
{
get
{
if (m_nodeId != null)
return m_nodeId.IdType;
return IdType.Numeric_0;
}
}
/// <summary>
/// The node identifier.
/// </summary>
/// <remarks>
/// Returns the node id in whatever form, i.e.
/// string, Guid, byte[] or uint.
/// </remarks>
public object IdentifierPart
{
get
{
if (m_nodeId != null)
return m_nodeId.IdentifierPart;
return null;
}
}
/// <summary>
/// The namespace that qualifies the node identifier.
/// </summary>
/// <remarks>
/// Returns the namespace that the node belongs to
/// </remarks>
public string NamespaceUri => m_namespaceUri;
/// <summary>
/// The index of the server where the node exists.
/// </summary>
/// <remarks>
/// Returns the index of the server where the node resides
/// </remarks>
public uint ServerIndex => m_serverIndex;
/// <summary>
/// Whether the object represents a Null NodeId.
/// </summary>
/// <remarks>
/// Returns whether or not the <see cref="NodeId"/> is null
/// </remarks>
public bool IsNull
{
get
{
if (!String.IsNullOrEmpty(m_namespaceUri))
return false;
if (m_serverIndex > 0)
return false;
return NodeId.IsNull(m_nodeId);
}
}
/// <summary>
/// Returns true if the expanded node id is an absolute identifier that contains a namespace URI instead of a server dependent index.
/// </summary>
/// <remarks>
/// Returns true if the expanded node id is an absolute identifier that contains a namespace URI instead of a server dependent index.
/// </remarks>
public bool IsAbsolute
{
get
{
if (!String.IsNullOrEmpty(m_namespaceUri) || m_serverIndex > 0)
return true;
return false;
}
}
/// <summary>
/// Returns the inner node id.
/// </summary>
/// <remarks>
/// Returns the inner node id.
/// </remarks>
internal NodeId InnerNodeId
{
get => m_nodeId;
set => m_nodeId = value;
}
/// <summary>
/// The node identifier formatted as a URI.
/// </summary>
/// <remarks>
/// The node identifier formatted as a URI.
/// </remarks>
internal string IdentifierText
{
get => Format();
set
{
ExpandedNodeId nodeId = ExpandedNodeId.Parse(value);
m_nodeId = nodeId.m_nodeId;
m_namespaceUri = nodeId.m_namespaceUri;
m_serverIndex = nodeId.m_serverIndex;
}
}
#endregion Public Properties
#region public string Format()
/// <summary>
/// Formats a expanded node id as a string.
/// </summary>
/// <remarks>
/// <para>
/// Formats a ExpandedNodeId as a string.
/// <br/></para>
/// <para>
/// An example of this would be:
/// <br/></para>
/// <para>
/// NodeId = "hello123"<br/>
/// NamespaceUri = "http://mycompany/"<br/>
/// <br/> This would translate into: <br/>
/// nsu=http://mycompany/;str=hello123 <br/>
/// </para>
/// </remarks>
public string Format()
{
StringBuilder buffer = new StringBuilder();
Format(buffer);
return buffer.ToString();
}
/// <summary>
/// Formats the node ids as string and adds it to the buffer.
/// </summary>
public void Format(StringBuilder buffer)
{
if (m_nodeId != null)
Format(buffer, m_nodeId.IdentifierPart, m_nodeId.IdType, m_nodeId.NamespaceIndex, m_namespaceUri, m_serverIndex);
else
Format(buffer, null, IdType.Numeric_0, 0, m_namespaceUri, m_serverIndex);
}
/// <summary>
/// Formats the node ids as string and adds it to the buffer.
/// </summary>
public static void Format(StringBuilder buffer, object identifier, IdType identifierType, ushort namespaceIndex, string namespaceUri, uint serverIndex)
{
if (serverIndex != 0)
buffer.AppendFormat(CultureInfo.InvariantCulture, "svr={0};", serverIndex);
if (!String.IsNullOrEmpty(namespaceUri))
{
buffer.Append("nsu=");
for (int ii = 0; ii < namespaceUri.Length; ii++)
{
char ch = namespaceUri[ii];
switch (ch)
{
case ';':
case '%':
{
buffer.AppendFormat(CultureInfo.InvariantCulture, "%{0:X2}", Convert.ToInt16(ch));
break;
}
default:
{
buffer.Append(ch);
break;
}
}
}
buffer.Append(";");
}
NodeId.Format(buffer, identifier, identifierType, namespaceIndex);
}
#endregion public string Format()
#region static Parse
/// <summary>
/// Parses the <paramref name="text" /> to recover an instance of the <see cref="ExpandedNodeId" />.
/// </summary>
/// <remarks>Namespace is translated to get current index.</remarks>
/// <param name="text">The text.</param>
/// <param name="currentNamespaces">The current namespaces table.</param>
/// <param name="targetNamespaces">The target namespaces table.</param>
/// <returns>An instance of the <see cref="ExpandedNodeId"/> recovered from the string representation.</returns>
internal static ExpandedNodeId Parse(string text, INamespaceTable currentNamespaces, INamespaceTable targetNamespaces)
{
// parse the string.
ExpandedNodeId nodeId = Parse(text);
// lookup the namespace uri.
string uri = nodeId.m_namespaceUri;
if (nodeId.m_nodeId.NamespaceIndex != 0)
uri = currentNamespaces.GetModelTableEntry(nodeId.m_nodeId.NamespaceIndex).ToString();
// translate the namespace Uri.
ushort namespaceIndex = 0;
if (!String.IsNullOrEmpty(uri))
{
int index = targetNamespaces.GetURIIndex(new Uri(uri));
if (index == -1)
throw GetResultException(String.Format("Cannot map namespace URI onto an index in the target namespace table: {0}", uri));
namespaceIndex = (ushort)index;
}
// check for absolute node id.
if (nodeId.ServerIndex != 0)
{
nodeId.m_nodeId = new NodeId(nodeId.m_nodeId.IdentifierPart, 0);
nodeId.m_namespaceUri = uri;
return nodeId;
}
// local node id.
nodeId.m_nodeId = new NodeId(nodeId.m_nodeId.IdentifierPart, namespaceIndex);
nodeId.m_namespaceUri = null;
return nodeId;
}
/// <summary>
/// Parses a expanded node id string and returns a node id object.
/// </summary>
/// <remarks>
/// Parses a ExpandedNodeId String and returns a NodeId object
/// </remarks>
/// <param name="text">The ExpandedNodeId value as a string.</param>
/// <exception cref="ServiceResultException">Thrown under a variety of circumstances, each time with a specific message.</exception>
public static ExpandedNodeId Parse(string text)
{
try
{
// check for null.
if (String.IsNullOrEmpty(text))
return ExpandedNodeId.Null;
uint serverIndex = 0;
// parse the server index if present.
if (text.StartsWith("svr=", StringComparison.Ordinal))
{
int index = text.IndexOf(';');
if (index == -1)
throw new ServiceResultException(TraceMessage.BuildErrorTraceMessage(BuildError.ExpandedNodeIdInvalidSyntax, "Invalid server index."), "ExpandedNodeId invalid syntax: invalid server index.");
serverIndex = Convert.ToUInt32(text.Substring(4, index - 4), CultureInfo.InvariantCulture);
text = text.Substring(index + 1);
}
string namespaceUri = null;
// parse the namespace uri if present.
if (text.StartsWith("nsu=", StringComparison.Ordinal))
{
int index = text.IndexOf(';');
if (index == -1)
throw GetResultException("Invalid namespace uri.");
StringBuilder buffer = new StringBuilder();
UnescapeUri(text, 4, index, buffer);
namespaceUri = buffer.ToString();
text = text.Substring(index + 1);
}
// parse the node id.
NodeId nodeId = NodeId.Parse(text);
// crete the node id.
return new ExpandedNodeId(nodeId, namespaceUri, serverIndex);
}
catch (Exception _ex)
{
throw GetResultException(String.Format("Cannot parse expanded node id text: '{0}' because of error {1}", text, _ex.Message));
}
}
/// <summary>
/// Unescapes any reserved characters in the uri.
/// </summary>
[Obsolete("Replace by WebUtility.HtmlDecode")]
internal static void UnescapeUri(string text, int start, int index, StringBuilder buffer)
{
for (int ii = start; ii < index; ii++)
{
char ch = text[ii];
switch (ch)
{
case '%':
{
if (ii + 2 >= index)
throw GetResultException("Invalid escaped character in namespace uri.");
ushort value = 0;
int digit = s_HexDigits.IndexOf(Char.ToUpperInvariant(text[++ii]));
if (digit == -1)
throw GetResultException("Invalid escaped character in namespace uri.");
value += (ushort)digit;
value <<= 4;
digit = s_HexDigits.IndexOf(Char.ToUpperInvariant(text[++ii]));
if (digit == -1)
throw GetResultException("Invalid escaped character in namespace uri.");
value += (ushort)digit;
char unencodedChar = Convert.ToChar(value);
buffer.Append(unencodedChar);
break;
}
default:
{
buffer.Append(ch);
break;
}
}
}
}
#endregion static Parse
#region IComparable Members
/// <summary>
/// Compares the current instance to the object.
/// </summary>
/// <remarks>
/// Compares the current instance to the object.
/// </remarks>
public int CompareTo(object obj)
{
// check for null.
if (Object.ReferenceEquals(obj, null))
return -1;
// check for reference comparisons.
if (Object.ReferenceEquals(this, obj))
return 0;
// just compare node ids.
if (String.IsNullOrEmpty(m_namespaceUri) && this.m_nodeId != null)
return this.m_nodeId.CompareTo(obj);
NodeId nodeId = obj as NodeId;
// check for expanded node ids.
ExpandedNodeId expandedId = obj as ExpandedNodeId;
if (expandedId != null)
{
if (this.ServerIndex != expandedId.ServerIndex)
return this.ServerIndex.CompareTo(expandedId.ServerIndex);
if (this.NamespaceUri != expandedId.NamespaceUri)
{
if (this.NamespaceUri != null)
return String.CompareOrdinal(NamespaceUri, expandedId.NamespaceUri);
return -1;
}
nodeId = expandedId.m_nodeId;
}
// check for null.
if (this.m_nodeId != null)
return this.m_nodeId.CompareTo(nodeId);
// compare node ids.
return (nodeId == null) ? 0 : -1;
}
/// <summary>
/// Returns true if a is greater than b.
/// </summary>
/// <remarks>
/// Returns true if a is greater than b.
/// </remarks>
public static bool operator >(ExpandedNodeId value1, object value2)
{
if (!Object.ReferenceEquals(value1, null))
return value1.CompareTo(value2) > 0;
return false;
}
/// <summary>
/// Returns true if a is less than b.
/// </summary>
/// <remarks>
/// Returns true if a is less than b.
/// </remarks>
public static bool operator <(ExpandedNodeId value1, object value2)
{
if (!Object.ReferenceEquals(value1, null))
return value1.CompareTo(value2) < 0;
return true;
}
#endregion IComparable Members
#region Comparison Functions
/// <summary>
/// Determines if the specified object is equal to the ExpandedNodeId.
/// </summary>
/// <remarks>
/// Determines if the specified object is equal to the ExpandedNodeId.
/// </remarks>
public override bool Equals(object obj)
{
return (CompareTo(obj) == 0);
}
/// <summary>
/// Returns a unique hashcode for the ExpandedNodeId
/// </summary>
/// <remarks>
/// Returns a unique hashcode for the ExpandedNodeId
/// </remarks>
public override int GetHashCode()
{
if (m_nodeId == null)
return 0;
return m_nodeId.GetHashCode();
}
/// <summary>
/// Returns true if the objects are equal.
/// </summary>
/// <remarks>
/// Returns true if the objects are equal.
/// </remarks>
public static bool operator ==(ExpandedNodeId value1, object value2)
{
if (Object.ReferenceEquals(value1, null))
return Object.ReferenceEquals(value2, null);
return (value1.CompareTo(value2) == 0);
}
/// <summary>
/// Returns true if the objects are not equal.
/// </summary>
/// <remarks>
/// Returns true if the objects are not equal.
/// </remarks>
public static bool operator !=(ExpandedNodeId value1, object value2)
{
if (Object.ReferenceEquals(value1, null))
return !Object.ReferenceEquals(value2, null);
return (value1.CompareTo(value2) != 0);
}
#endregion Comparison Functions
#region IFormattable Members
/// <summary>
/// Returns the string representation of an ExpandedNodeId.
/// </summary>
/// <remarks>
/// Returns the string representation of an ExpandedNodeId.
/// </remarks>
/// <returns>The <see cref="ExpandedNodeId"/> as a formatted string</returns>
/// <param name="format">(Unused) The format string.</param>
/// <param name="formatProvider">(Unused) The format-provider.</param>
/// <exception cref="FormatException">Thrown when the 'format' parameter is NOT null. So leave that parameter null.</exception>
public string ToString(string format, IFormatProvider formatProvider)
{
if (format == null)
return Format();
throw new FormatException(String.Format("Invalid format string: '{0}'.", format));
}
#endregion IFormattable Members
#region ICloneable Members
/// <summary>
/// Makes a deep copy of the object.
/// </summary>
/// <remarks>
/// Returns a reference to *this* object. This means that no copy is being made of this object.
/// </remarks>
public object Clone()
{
// this object cannot be altered after it is created so no new allocation is necessary.
return this;
}
#endregion ICloneable Members
#region Public Methods
/// <summary>
/// Returns the string representation of am ExpandedNodeId.
/// </summary>
/// <remarks>
/// Returns the string representation of am ExpandedNodeId.
/// </remarks>
public override string ToString()
{
return ToString(null, null);
}
/// <summary>
/// Converts an expanded node id to a node id using a namespace table.
/// </summary>
/// <remarks>
/// Converts an <see cref="ExpandedNodeId"/> to a <see cref="NodeId"/> using a namespace table.
/// </remarks>
/// <param name="namespaceTable">The namespace table that contains all the namespaces needed to resolve the namespace index as encoded within this object.</param>
/// <param name="nodeId">The ExpandedNodeId to convert to a NodeId</param>
internal static NodeId ToNodeId(ExpandedNodeId nodeId, INamespaceTable namespaceTable)
{
// check for null.
if (nodeId == null)
return null;
// return a reference to the internal node id object.
if (String.IsNullOrEmpty(nodeId.m_namespaceUri) && nodeId.m_serverIndex == 0)
return nodeId.m_nodeId;
// create copy.
NodeId localId = new NodeId(nodeId.m_nodeId);
int index = -1;
if (namespaceTable != null)
index = namespaceTable.GetURIIndex(new Uri(nodeId.NamespaceUri));
if (index < 0)
return null;
localId.SetNamespaceIndex((ushort)index);
return localId;
}
/// <summary>
/// Updates the namespace index.
/// </summary>
/// <remarks>
/// Updates the namespace index.
/// </remarks>
internal void SetNamespaceIndex(ushort namespaceIndex)
{
m_nodeId.SetNamespaceIndex(namespaceIndex);
m_namespaceUri = null;
}
/// <summary>
/// Updates the namespace uri.
/// </summary>
internal void SetNamespaceUri(string uri)
{
m_nodeId.SetNamespaceIndex(0);
m_namespaceUri = uri;
}
/// <summary>
/// Updates the server index.
/// </summary>
internal void SetServerIndex(uint serverIndex)
{
m_serverIndex = serverIndex;
}
#endregion Public Methods
#region Static Members
/// <summary>
/// Parses an absolute NodeId formatted as a string and converts it a local NodeId.
/// </summary>
/// <param name="namespaceUris">The current namespace table.</param>
/// <param name="text">The text to parse.</param>
/// <returns>The local identifier.</returns>
/// <exception cref="ServiceResultException">Thrown if the namespace URI is not in the namespace table.</exception>
internal static NodeId Parse(string text, INamespaceTable namespaceUris)
{
ExpandedNodeId nodeId = ExpandedNodeId.Parse(text);
if (!nodeId.IsAbsolute)
return nodeId.InnerNodeId;
NodeId localId = ExpandedNodeId.ToNodeId(nodeId, namespaceUris);
if (localId == null)
throw new ServiceResultException(
TraceMessage.BuildErrorTraceMessage(BuildError.ExpandedNodeIdInvalidSyntax, String.Format("NamespaceUri ({0}) is not in the namespace table.", nodeId.NamespaceUri)),
"ExpandedNodeId invalid syntax: namespace URI is not in the namespace table. ");
return localId;
}
/// <summary>
/// Converts an ExpandedNodeId to a NodeId.
/// </summary>
/// <remarks>
/// Converts an ExpandedNodeId to a NodeId.
/// </remarks>
/// <exception cref="InvalidCastException">Thrown if the ExpandedNodeId is an absolute node identifier.</exception>
public static explicit operator NodeId(ExpandedNodeId value)
{
if (value == null)
return null;
if (value.IsAbsolute)
throw new InvalidCastException("Cannot cast an absolute ExpandedNodeId to a NodeId. Use ExpandedNodeId.ToNodeId instead.");
return value.InnerNodeId;
}
/// <summary>
/// Converts an integer to a numeric node identifier.
/// </summary>
/// <remarks>
/// Converts an integer to a numeric node identifier.
/// </remarks>
public static implicit operator ExpandedNodeId(uint value)
{
return new ExpandedNodeId(value);
}
/// <summary>
/// Converts a guid to a guid node identifier.
/// </summary>
/// <remarks>
/// Converts a guid to a guid node identifier.
/// </remarks>
public static implicit operator ExpandedNodeId(Guid value)
{
return new ExpandedNodeId(value);
}
/// <summary>
/// Converts a byte array to an opaque node identifier.
/// </summary>
/// <remarks>
/// Converts a byte array to an opaque node identifier.
/// </remarks>
public static implicit operator ExpandedNodeId(byte[] value)
{
return new ExpandedNodeId(value);
}
/// <summary>
/// Parses a node id string and initializes a node id.
/// </summary>
/// <remarks>
/// Parses a node id string and initializes a node id.
/// </remarks>
public static implicit operator ExpandedNodeId(string text)
{
return new ExpandedNodeId(text);
}
/// <summary>
/// Converts a NodeId to an ExpandedNodeId
/// </summary>
/// <remarks>
/// Converts a NodeId to an ExpandedNodeId
/// </remarks>
public static implicit operator ExpandedNodeId(NodeId nodeId)
{
return new ExpandedNodeId(nodeId);
}
/// <summary>
/// Returns an instance of a null ExpandedNodeId.
/// </summary>
public static ExpandedNodeId Null => s_Null;
#endregion Static Members
#region private
//fields
private static readonly ExpandedNodeId s_Null = new ExpandedNodeId();
private NodeId m_nodeId;
private string m_namespaceUri;
private uint m_serverIndex;
/// <summary>
/// The set of hexadecimal digits used for decoding escaped URIs.
/// </summary>
private const string s_HexDigits = "0123456789ABCDEF";
//methods
private static Exception GetResultException(string _msg)
{
BuildError _be = BuildError.ExpandedNodeIdInvalidSyntax;
Exception _ex = new ServiceResultException(TraceMessage.BuildErrorTraceMessage(_be, _msg), _be.ToString() + _msg);
return _ex;
}
#endregion private
}
/// <summary>
/// A collection of ExpandedNodeId objects.
/// </summary>
public partial class ExpandedNodeIdCollection : List<ExpandedNodeId>, ICloneable
{
/// <summary>
/// Initializes an empty collection.
/// </summary>
/// <remarks>
/// Creates a new [empty] collection.
/// </remarks>
public ExpandedNodeIdCollection() { }
/// <summary>
/// Initializes the collection from another collection.
/// </summary>
/// <remarks>
/// Initializes the collection from another collection.
/// </remarks>
public ExpandedNodeIdCollection(IEnumerable<ExpandedNodeId> collection) : base(collection) { }
/// <summary>
/// Initializes the collection with the specified capacity.
/// </summary>
/// <remarks>
/// Initializes the collection with the specified capacity.
/// </remarks>
public ExpandedNodeIdCollection(int capacity) : base(capacity) { }
/// <summary>
/// Converts an array to a collection.
/// </summary>
/// <remarks>
/// This static method converts an array of <see cref="ExpandedNodeId"/> objects to
/// an <see cref="ExpandedNodeIdCollection"/>.
/// </remarks>
/// <param name="values">An array of <see cref="ExpandedNodeId"/> values to return as a collection</param>
public static ExpandedNodeIdCollection ToExpandedNodeIdCollection(ExpandedNodeId[] values)
{
if (values != null)
return new ExpandedNodeIdCollection(values);
return new ExpandedNodeIdCollection();
}
/// <summary>
/// Converts an array to a collection.
/// </summary>
/// <remarks>
/// Converts an array to a collection.
/// </remarks>
/// <param name="values">An array of <see cref="ExpandedNodeId"/> values to return as a collection</param>
public static implicit operator ExpandedNodeIdCollection(ExpandedNodeId[] values)
{
return ToExpandedNodeIdCollection(values);
}
/// <summary>
/// Creates a deep copy of the collection.
/// </summary>
/// <remarks>
/// Creates a deep copy of the collection.
/// </remarks>
public object Clone()
{
ExpandedNodeIdCollection _cloneCollection = new ExpandedNodeIdCollection(this.Count);
foreach (ExpandedNodeId element in this)
_cloneCollection.Add((ExpandedNodeId)element.Clone());
return _cloneCollection;
}
}//class
}//namespace
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// File: TextDpi.cs
//
// Description: Helpers to handle text dpi conversions and limitations.
//
// History:
// 04/25/2003 : [....] - moving from Avalon branch.
//
//---------------------------------------------------------------------------
using System; // Double, ...
using System.Windows; // DependencyObject
using System.Windows.Documents; // TextElement, ...
using System.Windows.Media; // FontFamily
using MS.Internal.PtsHost.UnsafeNativeMethods; // PTS
namespace MS.Internal.Text
{
// ----------------------------------------------------------------------
// Helpers to handle text dpi conversions and limitations.
// ----------------------------------------------------------------------
internal static class TextDpi
{
// ------------------------------------------------------------------
// Minimum width for text measurement.
// ------------------------------------------------------------------
internal static double MinWidth { get { return _minSize; } }
// ------------------------------------------------------------------
// Maximum width for text measurement.
// ------------------------------------------------------------------
internal static double MaxWidth { get { return _maxSize; } }
// ------------------------------------------------------------------
// Convert from logical measurement unit to text measurement unit.
//
// d - value in logical measurement unit
//
// Returns: value in text measurement unit.
// ------------------------------------------------------------------
internal static int ToTextDpi(double d)
{
if (DoubleUtil.IsZero(d)) { return 0; }
else if (d > 0)
{
if (d > _maxSize) { d = _maxSize; }
else if (d < _minSize) { d = _minSize; }
}
else
{
if (d < -_maxSize) { d = -_maxSize; }
else if (d > -_minSize) { d = -_minSize; }
}
return (int)Math.Round(d * _scale);
}
// ------------------------------------------------------------------
// Convert from text measurement unit to logical measurement unit.
//
// i - value in text measurement unit
//
// Returns: value in logical measurement unit.
// ------------------------------------------------------------------
internal static double FromTextDpi(int i)
{
return ((double)i) / _scale;
}
// ------------------------------------------------------------------
// Convert point from logical measurement unit to text measurement unit.
// ------------------------------------------------------------------
internal static PTS.FSPOINT ToTextPoint(Point point)
{
PTS.FSPOINT fspoint = new PTS.FSPOINT();
fspoint.u = ToTextDpi(point.X);
fspoint.v = ToTextDpi(point.Y);
return fspoint;
}
// ------------------------------------------------------------------
// Convert size from logical measurement unit to text measurement unit.
// ------------------------------------------------------------------
internal static PTS.FSVECTOR ToTextSize(Size size)
{
PTS.FSVECTOR fsvector = new PTS.FSVECTOR();
fsvector.du = ToTextDpi(size.Width);
fsvector.dv = ToTextDpi(size.Height);
return fsvector;
}
// ------------------------------------------------------------------
// Convert rect from text measurement unit to logical measurement unit.
// ------------------------------------------------------------------
internal static Rect FromTextRect(PTS.FSRECT fsrect)
{
return new Rect(
FromTextDpi(fsrect.u),
FromTextDpi(fsrect.v),
FromTextDpi(fsrect.du),
FromTextDpi(fsrect.dv));
}
// ------------------------------------------------------------------
// Make sure that LS/PTS limitations are not exceeded for offset
// within a line.
// ------------------------------------------------------------------
internal static void EnsureValidLineOffset(ref double offset)
{
// Offset has to be > min allowed size && < max allowed size.
if (offset > _maxSize) { offset = _maxSize; }
else if (offset < -_maxSize) { offset = -_maxSize; }
}
// ------------------------------------------------------------------
// Snaps the value to TextDPi, makeing sure that convertion to
// TextDpi and the to double produces the same value.
// ------------------------------------------------------------------
internal static void SnapToTextDpi(ref Size size)
{
size = new Size(FromTextDpi(ToTextDpi(size.Width)), FromTextDpi(ToTextDpi(size.Height)));
}
// ------------------------------------------------------------------
// Make sure that LS/PTS limitations are not exceeded for line width.
// ------------------------------------------------------------------
internal static void EnsureValidLineWidth(ref double width)
{
// Line width has to be > 0 && < max allowed size.
if (width > _maxSize) { width = _maxSize; }
else if (width < _minSize) { width = _minSize; }
}
internal static void EnsureValidLineWidth(ref Size size)
{
// Line width has to be > 0 && < max allowed size.
if (size.Width > _maxSize) { size.Width = _maxSize; }
else if (size.Width < _minSize) { size.Width = _minSize; }
}
internal static void EnsureValidLineWidth(ref int width)
{
// Line width has to be > 0 && < max allowed size.
if (width > _maxSizeInt) { width = _maxSizeInt; }
else if (width < _minSizeInt) { width = _minSizeInt; }
}
// ------------------------------------------------------------------
// Make sure that PTS limitations are not exceeded for page size.
// ------------------------------------------------------------------
internal static void EnsureValidPageSize(ref Size size)
{
// Page size has to be > 0 && < max allowed size.
if (size.Width > _maxSize) { size.Width = _maxSize; }
else if (size.Width < _minSize) { size.Width = _minSize; }
if (size.Height > _maxSize) { size.Height = _maxSize; }
else if (size.Height < _minSize) { size.Height = _minSize; }
}
internal static void EnsureValidPageWidth(ref double width)
{
// Page size has to be > 0 && < max allowed size.
if (width > _maxSize) { width = _maxSize; }
else if (width < _minSize) { width = _minSize; }
}
internal static void EnsureValidPageMargin(ref Thickness pageMargin, Size pageSize)
{
if (pageMargin.Left >= pageSize.Width) { pageMargin.Right = 0.0; }
if (pageMargin.Left + pageMargin.Right >= pageSize.Width)
{
pageMargin.Right = Math.Max(0.0, pageSize.Width - pageMargin.Left - _minSize);
if (pageMargin.Left + pageMargin.Right >= pageSize.Width)
{
pageMargin.Left = pageSize.Width - _minSize;
}
}
if (pageMargin.Top >= pageSize.Height) { pageMargin.Bottom = 0.0; }
if (pageMargin.Top + pageMargin.Bottom >= pageSize.Height)
{
pageMargin.Bottom = Math.Max(0.0, pageSize.Height - pageMargin.Top - _minSize);;
if (pageMargin.Top + pageMargin.Bottom >= pageSize.Height)
{
pageMargin.Top = pageSize.Height - _minSize;
}
}
}
// ------------------------------------------------------------------
// Make sure that LS/PTS limitations are not exceeded for object's size.
// ------------------------------------------------------------------
internal static void EnsureValidObjSize(ref Size size)
{
// Embedded object can have size == 0, but its width and height
// have to be less than max allowed size.
if (size.Width > _maxObjSize) { size.Width = _maxObjSize; }
if (size.Height > _maxObjSize) { size.Height = _maxObjSize; }
}
// ------------------------------------------------------------------
// Measuring unit for PTS presenters is int, but logical measuring
// for the rest of the system is is double.
// Logical measuring dpi = 96
// PTS presenters measuring dpi = 28800
// ------------------------------------------------------------------
private const double _scale = 28800.0 / 96; // 300
// ------------------------------------------------------------------
// PTS/LS limitation for max size.
// ------------------------------------------------------------------
private const int _maxSizeInt = 0x3FFFFFFE;
private const double _maxSize = ((double)_maxSizeInt) / _scale; // = 3,579,139.40 pixels
// ------------------------------------------------------------------
// PTS/LS limitation for min size.
// ------------------------------------------------------------------
private const int _minSizeInt = 1;
private const double _minSize = ((double)_minSizeInt) / _scale; // > 0
// ------------------------------------------------------------------
// Embedded object size is limited to 1/3 of max size accepted by LS/PTS.
// ------------------------------------------------------------------
private const double _maxObjSize = _maxSize / 3; // = 1,193,046.46 pixels
}
#if TEXTLAYOUTDEBUG
// ----------------------------------------------------------------------
// Pefrormance debugging helpers.
// ----------------------------------------------------------------------
internal static class TextDebug
{
// ------------------------------------------------------------------
// Enter the scope and log the message.
// ------------------------------------------------------------------
internal static void BeginScope(string name)
{
Log(name);
++_indent;
}
// ------------------------------------------------------------------
// Exit the current scope.
// ------------------------------------------------------------------
internal static void EndScope()
{
--_indent;
}
// ------------------------------------------------------------------
// Log message.
// ------------------------------------------------------------------
internal static void Log(string msg)
{
Console.WriteLine("> " + CurrentIndent + msg);
}
// ------------------------------------------------------------------
// String representing current indent.
// ------------------------------------------------------------------
private static string CurrentIndent { get { return new string(' ', _indent * 2); } }
// ------------------------------------------------------------------
// Current indent.
// ------------------------------------------------------------------
private static int _indent;
}
#endif // TEXTLAYOUTDEBUG
}
| |
using System.Collections;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using static EasyAssertions.MessageHelper;
namespace EasyAssertions;
class StandardErrors : IStandardErrors
{
static IStandardErrors? current;
public static IStandardErrors Current => current ?? new StandardErrors(StandardTests.Instance, ErrorFactory.Instance);
readonly StandardTests test;
readonly ErrorFactory error;
StandardErrors(StandardTests standardTests, ErrorFactory errorFactory)
{
test = standardTests;
error = errorFactory;
}
public static void Override(IStandardErrors newStandardErrors)
{
current = newStandardErrors;
}
public static void Default()
{
current = null;
}
public Exception NotEqual(object? expected, object? actual, string? message = null)
{
return error.WithActualExpression($@"
should be {Expected(expected, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception NotEqual(string expected, string actual, Case caseSensitivity = Case.Sensitive, string? message = null)
{
var differenceIndex = Enumerable.Range(0, Math.Max(expected.Length, actual.Length))
.FirstOrDefault(i => i == actual.Length || i == expected.Length || !CharactersMatch(expected, actual, i, caseSensitivity));
return error.WithActualExpression($@"
should be {Expected(expected, actual, differenceIndex, @"
")}
but was {Value(actual, expected, differenceIndex)}
{Arrow(actual, expected, differenceIndex)}
Difference at index {differenceIndex}." + message.OnNewLine());
}
static bool CharactersMatch(string expected, string actual, int index, Case caseSensitivity)
{
var stringComparison = caseSensitivity == Case.Sensitive
? StringComparison.Ordinal
: StringComparison.OrdinalIgnoreCase;
return expected.Substring(index, 1)
.Equals(actual.Substring(index, 1), stringComparison);
}
public Exception AreEqual(object? notExpected, object? actual, string? message = null)
{
return error.WithActualExpression($@"
should not be {Expected(notExpected, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception IsNull(string? message = null)
{
return error.WithActualExpression(@"
should not be null, but was." + message.OnNewLine());
}
public Exception NotSame(object? expected, object? actual, string? message = null)
{
return error.WithActualExpression($@"
should be instance {Expected(expected, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception AreSame(object? actual, string? message = null)
{
return error.WithActualExpression($@"
shouldn't be instance {Expected(actual, @"
")}" + message.OnNewLine());
}
public Exception NotEmpty(IEnumerable actual, string? message = null)
{
var actualList = actual.Cast<object?>().ToList();
return error.WithActualExpression($@"
should be empty
but {Count(actualList,
$"had 1 element: {Single(actualList)}",
$"had {actualList.Count} elements: {Sample(actualList)}")}" + message.OnNewLine());
}
public Exception NotEmpty(string actual, string? message = null)
{
return error.WithActualExpression($@"
should be empty
but was {Value(actual)}" + message.OnNewLine());
}
public Exception IsEmpty(string? message = null)
{
return error.WithActualExpression(@"should not be empty, but was." + message.OnNewLine());
}
public Exception LengthMismatch(int expectedLength, IEnumerable actual, string? message = null)
{
var actualItems = actual.Cast<object?>().ToList();
return error.WithActualExpression($@"
should have {expectedLength} {Count(expectedLength, "element", "elements")}
but {Count(actualItems,
"was empty.",
$"had 1 element: {Single(actualItems)}",
$"had {actualItems.Count} elements: {Sample(actualItems)}")}"
+ message.OnNewLine());
}
public Exception DoesNotContain(object? expected, IEnumerable actual, string? itemType = null, string? message = null)
{
var actualList = actual.Cast<object?>().ToList();
return error.WithActualExpression($@"
should contain {itemType.WithSpace()}{Expected(expected, @"
" + SpaceFor(itemType.WithSpace()))}
but was {Count(actualList,
"empty.",
$" [{Single(actualList)}]", Sample(actualList))}"
+ message.OnNewLine());
}
public Exception DoesNotContainItems<TActual, TExpected>(IEnumerable<TExpected> expected, IEnumerable<TActual> actual, Func<TActual, TExpected, bool> predicate, string? message = null)
{
var expectedItems = expected.ToList();
var actualItems = actual.ToList();
FindDifferences(expectedItems, actualItems, predicate, out var missingExpected, out _, out var missingIndices);
return DoesNotContainItems(expectedItems, actualItems, missingExpected, missingIndices, message);
}
Exception DoesNotContainItems<TActual, TExpected>(List<TExpected> expectedItems, List<TActual> actualItems, List<TExpected> missingExpected, List<int> missingIndices, string? message)
{
var expectedSource = ExpectedSourceIfDifferentToValue(expectedItems);
return error.Custom(expectedSource == null
? $@"{ActualExpression}
should contain expected item {missingIndices[0]} {Value(missingExpected[0])}
but was {Sample(actualItems)}" + message.OnNewLine()
: $@"{ActualExpression}
should contain {expectedSource}
but was missing item {missingIndices[0]} {Value(missingExpected[0])}
and was {Sample(actualItems)}" + message.OnNewLine());
}
public Exception Contains(object? expectedToNotContain, IEnumerable actual, string? itemType = null, string? message = null)
{
var actualList = actual.Cast<object>().ToList();
return error.WithActualExpression($@"
shouldn't contain {itemType.WithSpace()}{Expected(expectedToNotContain, @"
" + SpaceFor(itemType.WithSpace()))}
but was {Sample(actualList)}" + message.OnNewLine());
}
public Exception Contains(IEnumerable expectedToNotContain, IEnumerable actual, string? message = null)
{
var actualItems = actual.Cast<object?>().ToList();
var actualSet = new HashSet<object?>(actualItems);
var unexpectedList = expectedToNotContain.Cast<object>().ToList();
var unexpectedItemIndex = unexpectedList.FindIndex(actualSet.Contains);
var unexpectedItem = unexpectedItemIndex == -1 ? null
: unexpectedList[unexpectedItemIndex];
var itemIndexInActual = actualItems.IndexOf(unexpectedItem);
var expectedSource = ExpectedSourceIfDifferentToValue(expectedToNotContain);
return error.Custom(expectedSource != null
? $@"{ActualExpression}
shouldn't contain {expectedSource}
but contained {Value(unexpectedItem)}
and was {Sample(actualItems)}
Match at index {itemIndexInActual}." + message.OnNewLine()
: $@"{ActualExpression}
shouldn't contain {Value(unexpectedItem)}
but was {Sample(actualItems)}
Match at index {itemIndexInActual}." + message.OnNewLine());
}
public Exception OnlyContains(IEnumerable expected, IEnumerable actual, string? message = null)
{
var actualItems = new List<object>(actual.Cast<object>());
var expectedItems = expected.Cast<object>().ToList();
var expectedSource = ExpectedSourceIfDifferentToValue(expected);
return error.Custom(expectedSource != null
? $@"{ActualExpression}
should contain more than just {expectedSource}
but was {Sample(actualItems)}" + message.OnNewLine()
: $@"{ActualExpression}
should contain more than just {Sample(expectedItems)}
but was {Sample(actualItems)}" + message.OnNewLine());
}
public Exception DoesNotOnlyContain<TActual, TExpected>(IEnumerable<TExpected> expected, IEnumerable<TActual> actual, Func<TActual, TExpected, bool> predicate, string? message = null)
{
var expectedItems = expected.ToList();
var actualItems = actual.ToList();
if (expectedItems.None())
return NotEmpty(actualItems, message);
FindDifferences(expectedItems, actualItems, predicate, out var missingExpected, out var extraActual, out var missingIndices);
if (missingExpected.Any())
return DoesNotContainItems(expectedItems, actualItems, missingExpected, missingIndices, message);
return ContainsExtraItem(expectedItems, extraActual, message);
}
public Exception ContainsExtraItem<TActual, TExpected>(IEnumerable<TExpected> expectedSuperset, IEnumerable<TActual> actual, Func<TActual, TExpected, bool> predicate, string? message = null)
{
var expectedItems = expectedSuperset.ToList();
FindDifferences(expectedItems, actual, predicate, out _, out var extraActual, out _);
return ContainsExtraItem(expectedItems, extraActual, message);
}
Exception ContainsExtraItem<TActual, TExpected>(List<TExpected> expectedItems, List<TActual> extraActual, string? message)
{
var expectedSource = ExpectedSourceIfDifferentToValue(expectedItems);
return error.Custom(expectedSource != null
? $@"{ActualExpression}
should only contain {expectedSource}
but also contains {Sample(extraActual)}" + message.OnNewLine()
: $@"{ActualExpression}
should only contain {Sample(expectedItems)}
but also contains {Sample(extraActual)}" + message.OnNewLine());
}
static void FindDifferences<TActual, TExpected>(IEnumerable<TExpected> expected, IEnumerable<TActual> actual, Func<TActual, TExpected, bool> predicate, out List<TExpected> missingExpected, out List<TActual> extraActual, out List<int> missingIndices)
{
missingExpected = new List<TExpected>();
extraActual = actual.ToList();
missingIndices = new List<int>();
var expectedIndex = 0;
foreach (var expectedItem in expected)
{
var matchingIndex = extraActual.FindIndex(a => predicate(a, expectedItem));
if (matchingIndex == -1)
{
missingIndices.Add(expectedIndex);
missingExpected.Add(expectedItem);
}
else
{
extraActual.RemoveAt(matchingIndex);
}
expectedIndex++;
}
}
public Exception ContainsDuplicate(IEnumerable actual, string? message = null)
{
var actualItems = actual.Cast<object>().ToList();
var duplicateItem = actualItems.GroupBy(i => i).First(g => g.Count() > 1).Key;
var duplicateIndices = new List<int>();
for (var i = 0; i < actualItems.Count; i++)
if (test.ObjectsAreEqual(actualItems[i], duplicateItem))
duplicateIndices.Add(i);
return error.WithActualExpression($@"
should not contain duplicates
but {Value(duplicateItem)}
was found at indices {duplicateIndices.Take(duplicateIndices.Count - 1).Join(", ")} and {duplicateIndices.Last()}."
+ message.OnNewLine());
}
public Exception DoNotMatch<TActual, TExpected>(IEnumerable<TExpected> expected, IEnumerable<TActual> actual, Func<TActual, TExpected, bool> predicate, string? message = null)
{
var expectedList = expected.Cast<object?>().ToList();
var actualList = actual.Cast<object?>().ToList();
var expectedSource = ExpectedSourceIfDifferentToValue(expected);
if (expectedList.Count != actualList.Count)
return error.Custom($@"{ActualExpression}{(expectedSource == null ? null : $"doesn't match {expectedSource}.").OnNewLine()}
should have {Count(expectedList, "1 element", $"{expectedList.Count} elements")}
but {Count(actualList,
"was empty.",
$"had 1 element: {Single(actualList)}",
$"had {actualList.Count} elements: {Sample(actualList)}")}"
+ message.OnNewLine());
var differenceIndex = FindDifference(expectedList, actualList, (a, e) => predicate((TActual)a!, (TExpected)e!), out var expectedItem, out var actualItem);
return error.WithActualExpression($@"
{(expectedSource != null ? $"doesn't match {expectedSource}. Differs" : "differs")} at index {differenceIndex}.
should match {Value(expectedItem)}
but was {Value(actualItem)}" + message.OnNewLine());
}
public Exception ItemsNotSame(IEnumerable expected, IEnumerable actual, string? message = null)
{
var differenceIndex = FindDifference(expected, actual, ReferenceEquals, out var expectedItem, out var actualItem);
return error.WithActualExpression($@"
differs at index {differenceIndex}.
should be instance {Value(expectedItem)}
but was {Value(actualItem)}" + message.OnNewLine());
}
public Exception DoesNotStartWith<TActual, TExpected>(IEnumerable<TExpected> expected, IEnumerable<TActual> actual, Func<TActual, TExpected, bool> predicate, string? message = null)
{
var expectedItems = expected.Cast<object?>().ToList();
var actualItems = actual.Cast<object?>().ToList();
if (actualItems.Count < expectedItems.Count)
return NotLongEnough(expectedItems, actualItems, message);
var differenceIndex = FindDifference(expectedItems, actualItems, (a, e) => predicate((TActual)a!, (TExpected)e!), out var expectedValue, out var actualValue);
return DiffersAtIndex(differenceIndex, expectedValue, actualValue, message);
}
public Exception DoesNotEndWith<TActual, TExpected>(IEnumerable<TExpected> expected, IEnumerable<TActual> actual, Func<TActual, TExpected, bool> predicate, string? message = null)
{
var expectedItems = expected.Cast<object?>().ToList();
var actualItems = actual.Cast<object?>().ToList();
if (actualItems.Count < expectedItems.Count)
return NotLongEnough(expectedItems, actualItems, message);
var differenceInLength = actualItems.Count - expectedItems.Count;
var differenceIndex = FindDifference(expectedItems, actualItems.Skip(differenceInLength), (a, e) => predicate((TActual)a!, (TExpected)e!), out var expectedValue, out var actualValue)
+ differenceInLength;
return DiffersAtIndex(differenceIndex, expectedValue, actualValue, message);
}
Exception NotLongEnough(List<object?> expectedItems, List<object?> actualItems, string? message)
{
return error.WithActualExpression($@"
should have at least {expectedItems.Count} {Count(expectedItems, "element", "elements")}
but {Count(actualItems,
"was empty.",
$"had 1 element: {Single(actualItems)}",
$"had {actualItems.Count} elements: {Sample(actualItems)}")}" + message.OnNewLine());
}
Exception DiffersAtIndex(int differenceIndex, object? expectedValue, object? actualValue, string? message)
{
return error.WithActualExpression($@"
differs at index {differenceIndex}.
should be {Value(expectedValue)}
but was {Value(actualValue)}" + message.OnNewLine());
}
public Exception TreesDoNotMatch<TActual, TExpected>(IEnumerable<TestNode<TExpected>> expected, IEnumerable<TActual> actual, Func<TActual, IEnumerable<TActual>> getChildren, Func<object?, object?, bool> predicate, string? message = null)
{
return error.Custom(TreesDoNotMatch(expected, actual, getChildren, predicate, message, Enumerable.Empty<TActual>())!);
}
string? TreesDoNotMatch<TActual, TExpected>(IEnumerable<TestNode<TExpected>> expected, IEnumerable<TActual> actual, Func<TActual, IEnumerable<TActual>> getChildren, Func<object?, object?, bool> predicate, string? message, IEnumerable<TActual> path)
{
if (test.CollectionsMatch(actual, expected.Values(), predicate))
return ChildrenDoNotMatch(expected, actual, getChildren, predicate, message, path);
var actualItems = actual.Cast<object?>().ToList();
var expectedItems = expected.Values().Cast<object?>().ToList();
return actualItems.Count != expectedItems.Count
? TreeNodeChildrenLengthMismatch(expectedItems, actualItems, message, path)
: TreeNodeValueDoesNotMatch(expectedItems, actualItems, predicate, message, path);
}
static string TreeNodeChildrenLengthMismatch<TActual>(ICollection<object?> expectedItems, ICollection<object?> actualItems, string? message, IEnumerable<TActual> path)
{
var pathItems = path.Cast<object>().ToList();
var expectedSource = ExpectedSourceIfDifferentToValue(expectedItems);
return $@"{ActualExpression}{$"doesn't match {expectedSource}.".OnNewLine()}
{Path(pathItems)} node should have {Count(expectedItems, "1 child", $"{expectedItems.Count} children")}
but {Count(actualItems,
"was empty.",
$"had 1 child: {Single(actualItems)}",
$"had {actualItems.Count} children: {Sample(actualItems)}")}" + message.OnNewLine();
}
static string TreeNodeValueDoesNotMatch<TActual>(IList<object?> expectedItems, IList<object?> actualItems, Func<object?, object?, bool> predicate, string? message, IEnumerable<TActual> path)
{
var differenceIndex = FindDifference(expectedItems, actualItems, predicate, out var expectedItem, out var actualItem);
var pathItems = path.Cast<object>().ToList();
var expectedSource = ExpectedSourceIfDifferentToValue(expectedItem);
return $@"{ActualExpression}
doesn't match {expectedSource ?? "expected tree"}.
Differs at {Path(pathItems)}, child index {differenceIndex}.
should be {Value(expectedItem)}
but was {Value(actualItem)}" + message.OnNewLine();
}
string? ChildrenDoNotMatch<TActual, TExpected>(IEnumerable<TestNode<TExpected>> expected, IEnumerable<TActual> actual, Func<TActual, IEnumerable<TActual>> getChildren, Func<object?, object?, bool> predicate, string? message, IEnumerable<TActual> path)
{
return expected.Zip(actual, (e, a) => TreesDoNotMatch(e, getChildren(a), getChildren, predicate, message, path.Concat(new[] { a })))
.FirstOrDefault(m => m != null);
}
static int FindDifference(IEnumerable expected, IEnumerable actual, Func<object?, object?, bool> areEqual, out object? expectedValue, out object? actualValue)
{
var expectedList = expected.Cast<object?>().ToList();
var actualList = actual.Cast<object?>().ToList();
return FindDifference(expectedList, actualList, areEqual, out expectedValue, out actualValue);
}
static int FindDifference(IList<object?> expectedList, IList<object?> actualList, Func<object?, object?, bool> areEqual, out object? expectedValue, out object? actualValue)
{
var differenceIndex = Enumerable.Range(0, expectedList.Count)
.First(i => !areEqual(actualList[i], expectedList[i]));
expectedValue = expectedList[differenceIndex];
actualValue = actualList[differenceIndex];
return differenceIndex;
}
public Exception NoException(Type expectedExceptionType, LambdaExpression? function = null, string? message = null)
{
return error.Custom($@"{(function != null ? Value(function) : ActualExpression)}
should throw {Value(expectedExceptionType)}
but didn't throw at all." + message.OnNewLine());
}
public Exception WrongException(Type expectedExceptionType, Exception actualException, LambdaExpression? function = null, string? message = null)
{
return error.Custom($@"{(function != null ? Value(function) : ActualExpression)}
should throw {Value(expectedExceptionType)}
but threw {Value(actualException.GetType())}" + message.OnNewLine(), actualException);
}
public Exception DoesNotContain(string expectedSubstring, string actual, string? message = null)
{
return error.WithActualExpression($@"
should contain {Expected(expectedSubstring, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception Contains(string expectedToNotContain, string actual, string? message = null)
{
var matchIndex = actual.IndexOf(expectedToNotContain, StringComparison.Ordinal);
return error.WithActualExpression($@"
shouldn't contain {Expected(expectedToNotContain, @"
")}
but was {Value(actual, expectedToNotContain, matchIndex)}
{Arrow(actual, expectedToNotContain, matchIndex)}
Match at index {matchIndex}." + message.OnNewLine());
}
public Exception DoesNotStartWith(string expectedStart, string actual, string? message = null)
{
return error.WithActualExpression($@"
should start with {Expected(expectedStart, @"
")}
but starts with {Value(actual)}" + message.OnNewLine());
}
public Exception DoesNotEndWith(string expectedEnd, string actual, string? message = null)
{
return error.WithActualExpression($@"
should end with {Expected(expectedEnd, actual, expectedEnd.Length - 1, @"
")}
but ends with {Value(actual, expectedEnd, actual.Length - 1)}" + message.OnNewLine());
}
public Exception NotGreaterThan(object? expected, object? actual, string? message = null)
{
return error.WithActualExpression($@"
should be greater than {Expected(expected, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception NotLessThan(object? expected, object? actual, string? message = null)
{
return error.WithActualExpression($@"
should be less than {Expected(expected, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception DoesNotMatch(Regex regex, string actual, string? message = null)
{
return error.WithActualExpression($@"
should match {Expected(regex, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception Matches(Regex regex, string actual, string? message = null)
{
return error.WithActualExpression($@"
shouldn't match {Expected(regex, @"
")}
but was {Value(actual)}" + message.OnNewLine());
}
public Exception TaskTimedOut(TimeSpan timeout, string? message = null)
{
return error.WithActualExpression($@"timed out after {Value(timeout)}." + message.OnNewLine());
}
public Exception Matches(IEnumerable notExpected, IEnumerable actual, string? message = null)
{
var actualItems = actual.Cast<object>().ToList();
var expectedSource = ExpectedSourceIfDifferentToValue(notExpected);
return error.WithActualExpression(expectedSource == null
? $@"
should not match {Sample(actualItems)}
but did." + message.OnNewLine()
: $@"
should not match {expectedSource}
but was {Sample(actualItems)}" + message.OnNewLine());
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Formula.Functions
{
using System;
using System.Text;
using NPOI.SS.Formula;
using NPOI.SS.Formula.Eval;
using System.Globalization;
using System.Text.RegularExpressions;
/**
* Common functionality used by VLOOKUP, HLOOKUP, LOOKUP and MATCH
*
* @author Josh Micich
*/
internal class LookupUtils
{
internal class RowVector : ValueVector
{
private AreaEval _tableArray;
private int _size;
private int _rowIndex;
public RowVector(AreaEval tableArray, int rowIndex)
{
_rowIndex = rowIndex;
int _rowAbsoluteIndex = tableArray.FirstRow + rowIndex;
if (!tableArray.ContainsRow(_rowAbsoluteIndex))
{
int lastRowIx = tableArray.LastRow - tableArray.FirstRow;
throw new ArgumentException("Specified row index (" + rowIndex
+ ") is outside the allowed range (0.." + lastRowIx + ")");
}
_tableArray = tableArray;
_size = tableArray.Width;
}
public ValueEval GetItem(int index)
{
if (index > _size)
{
throw new IndexOutOfRangeException("Specified index (" + index
+ ") is outside the allowed range (0.." + (_size - 1) + ")");
}
return _tableArray.GetRelativeValue(_rowIndex, index);
}
public int Size
{
get
{
return _size;
}
}
}
internal class ColumnVector : ValueVector
{
private AreaEval _tableArray;
private int _size;
private int _columnIndex;
public ColumnVector(AreaEval tableArray, int columnIndex)
{
_columnIndex = columnIndex;
int _columnAbsoluteIndex = tableArray.FirstColumn + columnIndex;
if (!tableArray.ContainsColumn((short)_columnAbsoluteIndex))
{
int lastColIx = tableArray.LastColumn - tableArray.FirstColumn;
throw new ArgumentException("Specified column index (" + columnIndex
+ ") is outside the allowed range (0.." + lastColIx + ")");
}
_tableArray = tableArray;
_size = _tableArray.Height;
}
public ValueEval GetItem(int index)
{
if (index > _size)
{
throw new IndexOutOfRangeException("Specified index (" + index
+ ") is outside the allowed range (0.." + (_size - 1) + ")");
}
return _tableArray.GetRelativeValue(index, _columnIndex);
}
public int Size
{
get
{
return _size;
}
}
}
private class SheetVector : ValueVector
{
private RefEval _re;
private int _size;
public SheetVector(RefEval re)
{
_size = re.NumberOfSheets;
_re = re;
}
public ValueEval GetItem(int index)
{
if (index >= _size)
{
throw new IndexOutOfRangeException("Specified index (" + index
+ ") is outside the allowed range (0.." + (_size - 1) + ")");
}
int sheetIndex = _re.FirstSheetIndex + index;
return _re.GetInnerValueEval(sheetIndex);
}
public int Size
{
get
{
return _size;
}
}
}
public static ValueVector CreateRowVector(TwoDEval tableArray, int relativeRowIndex)
{
return new RowVector((AreaEval)tableArray, relativeRowIndex);
}
public static ValueVector CreateColumnVector(TwoDEval tableArray, int relativeColumnIndex)
{
return new ColumnVector((AreaEval)tableArray, relativeColumnIndex);
}
/**
* @return <c>null</c> if the supplied area is neither a single row nor a single colum
*/
public static ValueVector CreateVector(TwoDEval ae)
{
if (ae.IsColumn)
{
return CreateColumnVector(ae, 0);
}
if (ae.IsRow)
{
return CreateRowVector(ae, 0);
}
return null;
}
public static ValueVector CreateVector(RefEval re)
{
return new SheetVector(re);
}
private class StringLookupComparer : LookupValueComparerBase
{
private String _value;
private Regex _wildCardPattern;
private bool _matchExact;
private bool _isMatchFunction;
public StringLookupComparer(StringEval se, bool matchExact, bool isMatchFunction)
: base(se)
{
_value = se.StringValue;
_wildCardPattern = Countif.StringMatcher.GetWildCardPattern(_value);
_matchExact = matchExact;
_isMatchFunction = isMatchFunction;
}
protected override CompareResult CompareSameType(ValueEval other)
{
StringEval se = (StringEval)other;
String stringValue = se.StringValue;
if (_wildCardPattern != null)
{
MatchCollection matcher = _wildCardPattern.Matches(stringValue);
bool matches = matcher.Count > 0;
if (_isMatchFunction ||
!_matchExact)
{
return CompareResult.ValueOf(matches);
}
}
return CompareResult.ValueOf(String.Compare(_value, stringValue, true));
}
protected override String GetValueAsString()
{
return _value;
}
}
private class NumberLookupComparer : LookupValueComparerBase
{
private double _value;
public NumberLookupComparer(NumberEval ne)
: base(ne)
{
_value = ne.NumberValue;
}
protected override CompareResult CompareSameType(ValueEval other)
{
NumberEval ne = (NumberEval)other;
return CompareResult.ValueOf(_value.CompareTo(ne.NumberValue));
}
protected override String GetValueAsString()
{
return _value.ToString(CultureInfo.InvariantCulture);
}
}
/**
* Processes the third argument to VLOOKUP, or HLOOKUP (<b>col_index_num</b>
* or <b>row_index_num</b> respectively).<br/>
* Sample behaviour:
* <table border="0" cellpAdding="1" cellspacing="2" summary="Sample behaviour">
* <tr><th>Input Return</th><th>Value </th><th>Thrown Error</th></tr>
* <tr><td>5</td><td>4</td><td> </td></tr>
* <tr><td>2.9</td><td>2</td><td> </td></tr>
* <tr><td>"5"</td><td>4</td><td> </td></tr>
* <tr><td>"2.18e1"</td><td>21</td><td> </td></tr>
* <tr><td>"-$2"</td><td>-3</td><td>*</td></tr>
* <tr><td>FALSE</td><td>-1</td><td>*</td></tr>
* <tr><td>TRUE</td><td>0</td><td> </td></tr>
* <tr><td>"TRUE"</td><td> </td><td>#REF!</td></tr>
* <tr><td>"abc"</td><td> </td><td>#REF!</td></tr>
* <tr><td>""</td><td> </td><td>#REF!</td></tr>
* <tr><td><blank></td><td> </td><td>#VALUE!</td></tr>
* </table><br/>
*
* * Note - out of range errors (both too high and too low) are handled by the caller.
* @return column or row index as a zero-based value
*
*/
public static int ResolveRowOrColIndexArg(ValueEval rowColIndexArg, int srcCellRow, int srcCellCol)
{
if(rowColIndexArg == null) {
throw new ArgumentException("argument must not be null");
}
ValueEval veRowColIndexArg;
try {
veRowColIndexArg = OperandResolver.GetSingleValue(rowColIndexArg, srcCellRow, (short)srcCellCol);
} catch (EvaluationException) {
// All errors get translated to #REF!
throw EvaluationException.InvalidRef();
}
int oneBasedIndex;
if(veRowColIndexArg is StringEval) {
StringEval se = (StringEval) veRowColIndexArg;
String strVal = se.StringValue;
Double dVal = OperandResolver.ParseDouble(strVal);
if(Double.IsNaN(dVal)) {
// String does not resolve to a number. Raise #REF! error.
throw EvaluationException.InvalidRef();
// This includes text booleans "TRUE" and "FALSE". They are not valid.
}
// else - numeric value parses OK
}
// actual BoolEval values get interpreted as FALSE->0 and TRUE->1
oneBasedIndex = OperandResolver.CoerceValueToInt(veRowColIndexArg);
if (oneBasedIndex < 1) {
// note this is asymmetric with the errors when the index is too large (#REF!)
throw EvaluationException.InvalidValue();
}
return oneBasedIndex - 1; // convert to zero based
}
/**
* The second argument (table_array) should be an area ref, but can actually be a cell ref, in
* which case it Is interpreted as a 1x1 area ref. Other scalar values cause #VALUE! error.
*/
public static AreaEval ResolveTableArrayArg(ValueEval eval)
{
if (eval is AreaEval)
{
return (AreaEval)eval;
}
if(eval is RefEval) {
RefEval refEval = (RefEval) eval;
// Make this cell ref look like a 1x1 area ref.
// It doesn't matter if eval is a 2D or 3D ref, because that detail is never asked of AreaEval.
return refEval.Offset(0, 0, 0, 0);
}
throw EvaluationException.InvalidValue();
}
/**
* Resolves the last (optional) parameter (<b>range_lookup</b>) to the VLOOKUP and HLOOKUP functions.
* @param rangeLookupArg
* @param srcCellRow
* @param srcCellCol
* @return
* @throws EvaluationException
*/
public static bool ResolveRangeLookupArg(ValueEval rangeLookupArg, int srcCellRow, int srcCellCol)
{
if (rangeLookupArg == null)
{
// range_lookup arg not provided
return true; // default Is TRUE
}
ValueEval valEval = OperandResolver.GetSingleValue(rangeLookupArg, srcCellRow, srcCellCol);
if (valEval is BlankEval)
{
// Tricky:
// fourth arg supplied but Evaluates to blank
// this does not Get the default value
return false;
}
if (valEval is BoolEval)
{
// Happy day flow
BoolEval boolEval = (BoolEval)valEval;
return boolEval.BooleanValue;
}
if (valEval is StringEval)
{
String stringValue = ((StringEval)valEval).StringValue;
if (stringValue.Length < 1)
{
// More trickiness:
// Empty string Is not the same as BlankEval. It causes #VALUE! error
throw EvaluationException.InvalidValue();
}
// TODO move parseBoolean to OperandResolver
bool? b = Countif.ParseBoolean(stringValue);
if (b!=null)
{
// string Converted to bool OK
return b==true?true:false;
}
//// Even more trickiness:
//// Note - even if the StringEval represents a number value (for example "1"),
//// Excel does not resolve it to a bool.
throw EvaluationException.InvalidValue();
//// This Is in contrast to the code below,, where NumberEvals values (for
//// example 0.01) *do* resolve to equivalent bool values.
}
if (valEval is NumericValueEval)
{
NumericValueEval nve = (NumericValueEval)valEval;
// zero Is FALSE, everything else Is TRUE
return 0.0 != nve.NumberValue;
}
throw new Exception("Unexpected eval type (" + valEval.GetType().Name + ")");
}
public static int LookupIndexOfValue(ValueEval lookupValue, ValueVector vector, bool isRangeLookup)
{
LookupValueComparer lookupComparer = CreateLookupComparer(lookupValue, isRangeLookup, false);
int result;
if (isRangeLookup)
{
result = PerformBinarySearch(vector, lookupComparer);
}
else
{
result = LookupIndexOfExactValue(lookupComparer, vector);
}
if (result < 0)
{
throw new EvaluationException(ErrorEval.NA);
}
return result;
}
/**
* Finds first (lowest index) exact occurrence of specified value.
* @param lookupComparer the value to be found in column or row vector
* @param vector the values to be searched. For VLOOKUP this Is the first column of the
* tableArray. For HLOOKUP this Is the first row of the tableArray.
* @return zero based index into the vector, -1 if value cannot be found
*/
private static int LookupIndexOfExactValue(LookupValueComparer lookupComparer, ValueVector vector)
{
// Find first occurrence of lookup value
int size = vector.Size;
for (int i = 0; i < size; i++)
{
if (lookupComparer.CompareTo(vector.GetItem(i)).IsEqual)
{
return i;
}
}
return -1;
}
/**
* Excel has funny behaviour when the some elements in the search vector are the wrong type.
*
*/
private static int PerformBinarySearch(ValueVector vector, LookupValueComparer lookupComparer)
{
// both low and high indexes point to values assumed too low and too high.
BinarySearchIndexes bsi = new BinarySearchIndexes(vector.Size);
while (true)
{
int midIx = bsi.GetMidIx();
if (midIx < 0)
{
return bsi.GetLowIx();
}
CompareResult cr = lookupComparer.CompareTo(vector.GetItem(midIx));
if (cr.IsTypeMismatch)
{
int newMidIx = HandleMidValueTypeMismatch(lookupComparer, vector, bsi, midIx);
if (newMidIx < 0)
{
continue;
}
midIx = newMidIx;
cr = lookupComparer.CompareTo(vector.GetItem(midIx));
}
if (cr.IsEqual)
{
return FindLastIndexInRunOfEqualValues(lookupComparer, vector, midIx, bsi.GetHighIx());
}
bsi.NarrowSearch(midIx, cr.IsLessThan);
}
}
/**
* Excel seems to handle mismatched types initially by just stepping 'mid' ix forward to the
* first compatible value.
* @param midIx 'mid' index (value which has the wrong type)
* @return usually -1, signifying that the BinarySearchIndex has been narrowed to the new mid
* index. Zero or greater signifies that an exact match for the lookup value was found
*/
private static int HandleMidValueTypeMismatch(LookupValueComparer lookupComparer, ValueVector vector,
BinarySearchIndexes bsi, int midIx)
{
int newMid = midIx;
int highIx = bsi.GetHighIx();
while (true)
{
newMid++;
if (newMid == highIx)
{
// every element from midIx to highIx was the wrong type
// move highIx down to the low end of the mid values
bsi.NarrowSearch(midIx, true);
return -1;
}
CompareResult cr = lookupComparer.CompareTo(vector.GetItem(newMid));
if (cr.IsLessThan && newMid == highIx - 1)
{
// move highIx down to the low end of the mid values
bsi.NarrowSearch(midIx, true);
return -1;
// but only when "newMid == highIx-1"? slightly weird.
// It would seem more efficient to always do this.
}
if (cr.IsTypeMismatch)
{
// keep stepping over values Until the right type Is found
continue;
}
if (cr.IsEqual)
{
return newMid;
}
// Note - if moving highIx down (due to lookup<vector[newMid]),
// this execution path only moves highIx it down as far as newMid, not midIx,
// which would be more efficient.
bsi.NarrowSearch(newMid, cr.IsLessThan);
return -1;
}
}
/**
* Once the binary search has found a single match, (V/H)LOOKUP steps one by one over subsequent
* values to choose the last matching item.
*/
private static int FindLastIndexInRunOfEqualValues(LookupValueComparer lookupComparer, ValueVector vector,
int firstFoundIndex, int maxIx)
{
for (int i = firstFoundIndex + 1; i < maxIx; i++)
{
if (!lookupComparer.CompareTo(vector.GetItem(i)).IsEqual)
{
return i - 1;
}
}
return maxIx - 1;
}
public static LookupValueComparer CreateLookupComparer(ValueEval lookupValue, bool matchExact, bool isMatchFunction)
{
if (lookupValue == BlankEval.instance)
{
// blank eval translates to zero
// Note - a blank eval in the lookup column/row never matches anything
// empty string in the lookup column/row can only be matched by explicit emtpty string
return new NumberLookupComparer(NumberEval.ZERO);
}
if (lookupValue is StringEval)
{
return new StringLookupComparer((StringEval)lookupValue, matchExact, isMatchFunction);
}
if (lookupValue is NumberEval)
{
return new NumberLookupComparer((NumberEval)lookupValue);
}
if (lookupValue is BoolEval)
{
return new BooleanLookupComparer((BoolEval)lookupValue);
}
throw new ArgumentException("Bad lookup value type (" + lookupValue.GetType().Name + ")");
}
}
/**
* Enumeration to support <b>4</b> valued comparison results.<p/>
* Excel lookup functions have complex behaviour in the case where the lookup array has mixed
* types, and/or Is Unordered. Contrary to suggestions in some Excel documentation, there
* does not appear to be a Universal ordering across types. The binary search algorithm used
* Changes behaviour when the Evaluated 'mid' value has a different type to the lookup value.<p/>
*
* A simple int might have done the same job, but there Is risk in confusion with the well
* known <c>Comparable.CompareTo()</c> and <c>Comparator.Compare()</c> which both use
* a ubiquitous 3 value result encoding.
*/
public class CompareResult
{
private bool _isTypeMismatch;
private bool _isLessThan;
private bool _isEqual;
private bool _isGreaterThan;
private CompareResult(bool IsTypeMismatch, int simpleCompareResult)
{
if (IsTypeMismatch)
{
_isTypeMismatch = true;
_isLessThan = false;
_isEqual = false;
_isGreaterThan = false;
}
else
{
_isTypeMismatch = false;
_isLessThan = simpleCompareResult < 0;
_isEqual = simpleCompareResult == 0;
_isGreaterThan = simpleCompareResult > 0;
}
}
public static readonly CompareResult TypeMismatch = new CompareResult(true, 0);
public static readonly CompareResult LessThan = new CompareResult(false, -1);
public static readonly CompareResult Equal = new CompareResult(false, 0);
public static readonly CompareResult GreaterThan = new CompareResult(false, +1);
public static CompareResult ValueOf(int simpleCompareResult)
{
if (simpleCompareResult < 0)
{
return LessThan;
}
if (simpleCompareResult > 0)
{
return GreaterThan;
}
return Equal;
}
public static CompareResult ValueOf(bool matches)
{
if (matches)
{
return Equal;
}
return LessThan;
}
public bool IsTypeMismatch
{
get { return _isTypeMismatch; }
}
public bool IsLessThan
{
get { return _isLessThan; }
}
public bool IsEqual
{
get { return _isEqual; }
}
public bool IsGreaterThan
{
get { return _isGreaterThan; }
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(FormatAsString);
sb.Append("]");
return sb.ToString();
}
private String FormatAsString
{
get
{
if (_isTypeMismatch)
{
return "TYPE_MISMATCH";
}
if (_isLessThan)
{
return "LESS_THAN";
}
if (_isEqual)
{
return "EQUAL";
}
if (_isGreaterThan)
{
return "GREATER_THAN";
}
// toString must be reliable
return "error";
}
}
}
/**
* Encapsulates some standard binary search functionality so the Unusual Excel behaviour can
* be clearly distinguished.
*/
internal class BinarySearchIndexes
{
private int _lowIx;
private int _highIx;
public BinarySearchIndexes(int highIx)
{
_lowIx = -1;
_highIx = highIx;
}
/**
* @return -1 if the search range Is empty
*/
public int GetMidIx()
{
int ixDiff = _highIx - _lowIx;
if (ixDiff < 2)
{
return -1;
}
return _lowIx + (ixDiff / 2);
}
public int GetLowIx()
{
return _lowIx;
}
public int GetHighIx()
{
return _highIx;
}
public void NarrowSearch(int midIx, bool isLessThan)
{
if (isLessThan)
{
_highIx = midIx;
}
else
{
_lowIx = midIx;
}
}
}
internal class BooleanLookupComparer : LookupValueComparerBase
{
private bool _value;
public BooleanLookupComparer(BoolEval be)
: base(be)
{
_value = be.BooleanValue;
}
protected override CompareResult CompareSameType(ValueEval other)
{
BoolEval be = (BoolEval)other;
bool otherVal = be.BooleanValue;
if (_value == otherVal)
{
return CompareResult.Equal;
}
// TRUE > FALSE
if (_value)
{
return CompareResult.GreaterThan;
}
return CompareResult.LessThan;
}
protected override String GetValueAsString()
{
return _value.ToString();
}
}
/**
* Represents a single row or column within an <c>AreaEval</c>.
*/
public interface ValueVector
{
ValueEval GetItem(int index);
int Size { get; }
}
public interface LookupValueComparer
{
/**
* @return one of 4 instances or <c>CompareResult</c>: <c>LESS_THAN</c>, <c>EQUAL</c>,
* <c>GREATER_THAN</c> or <c>TYPE_MISMATCH</c>
*/
CompareResult CompareTo(ValueEval other);
}
internal abstract class LookupValueComparerBase : LookupValueComparer
{
private Type _targetType;
protected LookupValueComparerBase(ValueEval targetValue)
{
if (targetValue == null)
{
throw new Exception("targetValue cannot be null");
}
_targetType = targetValue.GetType();
}
public CompareResult CompareTo(ValueEval other)
{
if (other == null)
{
throw new Exception("Compare to value cannot be null");
}
if (_targetType != other.GetType())
{
return CompareResult.TypeMismatch;
}
return CompareSameType(other);
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(GetValueAsString());
sb.Append("]");
return sb.ToString();
}
protected abstract CompareResult CompareSameType(ValueEval other);
/** used only for debug purposes */
protected abstract String GetValueAsString();
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.Net.Http.Headers
{
// This type is used to store a collection of headers in 'headerStore':
// - A header can have multiple values.
// - A header can have an associated parser which is able to parse the raw string value into a strongly typed object.
// - If a header has an associated parser and the provided raw value can't be parsed, the value is considered
// invalid. Invalid values are stored if added using TryAddWithoutValidation(). If the value was added using Add(),
// Add() will throw FormatException.
// - Since parsing header values is expensive and users usually only care about a few headers, header values are
// lazily initialized.
//
// Given the properties above, a header value can have three states:
// - 'raw': The header value was added using TryAddWithoutValidation() and it wasn't parsed yet.
// - 'parsed': The header value was successfully parsed. It was either added using Add() where the value was parsed
// immediately, or if added using TryAddWithoutValidation() a user already accessed a property/method triggering the
// value to be parsed.
// - 'invalid': The header value was parsed, but parsing failed because the value is invalid. Storing invalid values
// allows users to still retrieve the value (by calling GetValues()), but it will not be exposed as strongly typed
// object. E.g. the client receives a response with the following header: 'Via: 1.1 proxy, invalid'
// - HttpHeaders.GetValues() will return "1.1 proxy", "invalid"
// - HttpResponseHeaders.Via collection will only contain one ViaHeaderValue object with value "1.1 proxy"
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "This is not a collection")]
public abstract class HttpHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>>
{
private Dictionary<string, HeaderStoreItemInfo> _headerStore;
private Dictionary<string, HttpHeaderParser> _parserStore;
private HashSet<string> _invalidHeaders;
private enum StoreLocation
{
Raw,
Invalid,
Parsed
}
protected HttpHeaders()
{
}
public void Add(string name, string value)
{
CheckHeaderName(name);
// We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing
// the value then throws, we would have to remove the header from the store again. So just get a
// HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header.
HeaderStoreItemInfo info;
bool addToStore;
PrepareHeaderInfoForAdd(name, out info, out addToStore);
ParseAndAddValue(name, info, value);
// If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add
// it to the store if we added at least one value.
if (addToStore && (info.ParsedValue != null))
{
AddHeaderToStore(name, info);
}
}
public void Add(string name, IEnumerable<string> values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
CheckHeaderName(name);
HeaderStoreItemInfo info;
bool addToStore;
PrepareHeaderInfoForAdd(name, out info, out addToStore);
try
{
// Note that if the first couple of values are valid followed by an invalid value, the valid values
// will be added to the store before the exception for the invalid value is thrown.
foreach (string value in values)
{
ParseAndAddValue(name, info, value);
}
}
finally
{
// Even if one of the values was invalid, make sure we add the header for the valid ones. We need to be
// consistent here: If values get added to an _existing_ header, then all values until the invalid one
// get added. Same here: If multiple values get added to a _new_ header, make sure the header gets added
// with the valid values.
// However, if all values for a _new_ header were invalid, then don't add the header.
if (addToStore && (info.ParsedValue != null))
{
AddHeaderToStore(name, info);
}
}
}
public bool TryAddWithoutValidation(string name, string value)
{
if (!TryCheckHeaderName(name))
{
return false;
}
if (value == null)
{
// We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty
// values, we'll just add them to the collection. This will result in delimiter-only values:
// E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,".
value = string.Empty;
}
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, false);
AddValue(info, value, StoreLocation.Raw);
return true;
}
public bool TryAddWithoutValidation(string name, IEnumerable<string> values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
if (!TryCheckHeaderName(name))
{
return false;
}
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, false);
foreach (string value in values)
{
// We allow empty header values. (e.g. "My-Header: "). If the user adds multiple null/empty
// values, we'll just add them to the collection. This will result in delimiter-only values:
// E.g. adding two null-strings (or empty, or whitespace-only) results in "My-Header: ,".
AddValue(info, value ?? string.Empty, StoreLocation.Raw);
}
return true;
}
public void Clear()
{
if (_headerStore != null)
{
_headerStore.Clear();
}
}
public bool Remove(string name)
{
CheckHeaderName(name);
if (_headerStore == null)
{
return false;
}
return _headerStore.Remove(name);
}
public IEnumerable<string> GetValues(string name)
{
CheckHeaderName(name);
IEnumerable<string> values;
if (!TryGetValues(name, out values))
{
throw new InvalidOperationException(SR.net_http_headers_not_found);
}
return values;
}
public bool TryGetValues(string name, out IEnumerable<string> values)
{
if (!TryCheckHeaderName(name))
{
values = null;
return false;
}
if (_headerStore == null)
{
values = null;
return false;
}
HeaderStoreItemInfo info = null;
if (TryGetAndParseHeaderInfo(name, out info))
{
values = GetValuesAsStrings(info);
return true;
}
values = null;
return false;
}
public bool Contains(string name)
{
CheckHeaderName(name);
if (_headerStore == null)
{
return false;
}
// We can't just call headerStore.ContainsKey() since after parsing the value the header may not exist
// anymore (if the value contains invalid newline chars, we remove the header). So try to parse the
// header value.
HeaderStoreItemInfo info = null;
return TryGetAndParseHeaderInfo(name, out info);
}
public override string ToString()
{
// Return all headers as string similar to:
// HeaderName1: Value1, Value2
// HeaderName2: Value1
// ...
StringBuilder sb = new StringBuilder();
foreach (var header in this)
{
sb.Append(header.Key);
sb.Append(": ");
sb.Append(this.GetHeaderString(header.Key));
sb.Append("\r\n");
}
return sb.ToString();
}
internal IEnumerable<KeyValuePair<string, string>> GetHeaderStrings()
{
if (_headerStore == null)
{
yield break;
}
foreach (var header in _headerStore)
{
HeaderStoreItemInfo info = header.Value;
string stringValue = GetHeaderString(info);
yield return new KeyValuePair<string, string>(header.Key, stringValue);
}
}
internal string GetHeaderString(string headerName)
{
return GetHeaderString(headerName, null);
}
internal string GetHeaderString(string headerName, object exclude)
{
HeaderStoreItemInfo info;
if (!TryGetHeaderInfo(headerName, out info))
{
return string.Empty;
}
return GetHeaderString(info, exclude);
}
private string GetHeaderString(HeaderStoreItemInfo info)
{
return GetHeaderString(info, null);
}
private string GetHeaderString(HeaderStoreItemInfo info, object exclude)
{
string stringValue = string.Empty; // returned if values.Length == 0
string[] values = GetValuesAsStrings(info, exclude);
if (values.Length == 1)
{
stringValue = values[0];
}
else
{
// Note that if we get multiple values for a header that doesn't support multiple values, we'll
// just separate the values using a comma (default separator).
string separator = HttpHeaderParser.DefaultSeparator;
if ((info.Parser != null) && (info.Parser.SupportsMultipleValues))
{
separator = info.Parser.Separator;
}
stringValue = string.Join(separator, values);
}
return stringValue;
}
#region IEnumerable<KeyValuePair<string, IEnumerable<string>>> Members
public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator()
{
if (_headerStore == null)
{
yield break;
}
List<string> invalidHeaders = null;
foreach (var header in _headerStore)
{
HeaderStoreItemInfo info = header.Value;
// Make sure we parse all raw values before returning the result. Note that this has to be
// done before we calculate the array length (next line): A raw value may contain a list of
// values.
if (!ParseRawHeaderValues(header.Key, info, false))
{
// We have an invalid header value (contains invalid newline chars). Mark it as "to-be-deleted"
// and skip this header.
if (invalidHeaders == null)
{
invalidHeaders = new List<string>();
}
invalidHeaders.Add(header.Key);
}
else
{
string[] values = GetValuesAsStrings(info);
yield return new KeyValuePair<string, IEnumerable<string>>(header.Key, values);
}
}
// While we were enumerating headers, we also parsed header values. If during parsing it turned out that
// the header value was invalid (contains invalid newline chars), remove the header from the store after
// completing the enumeration.
if (invalidHeaders != null)
{
Debug.Assert(_headerStore != null);
foreach (string invalidHeader in invalidHeaders)
{
_headerStore.Remove(invalidHeader);
}
}
}
#endregion
#region IEnumerable Members
Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
internal void SetConfiguration(Dictionary<string, HttpHeaderParser> parserStore,
HashSet<string> invalidHeaders)
{
Debug.Assert(_parserStore == null, "Parser store was already set.");
_parserStore = parserStore;
_invalidHeaders = invalidHeaders;
}
internal void AddParsedValue(string name, object value)
{
Contract.Requires((name != null) && (name.Length > 0));
Contract.Requires(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Contract.Requires(value != null);
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, true);
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
// If the current header has only one value, we can't add another value. The strongly typed property
// must not call AddParsedValue(), but SetParsedValue(). E.g. for headers like 'Date', 'Host'.
Debug.Assert(info.CanAddValue, "Header '" + name + "' doesn't support multiple values");
AddValue(info, value, StoreLocation.Parsed);
}
internal void SetParsedValue(string name, object value)
{
Contract.Requires((name != null) && (name.Length > 0));
Contract.Requires(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Contract.Requires(value != null);
// This method will first clear all values. This is used e.g. when setting the 'Date' or 'Host' header.
// I.e. headers not supporting collections.
HeaderStoreItemInfo info = GetOrCreateHeaderInfo(name, true);
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
info.InvalidValue = null;
info.ParsedValue = null;
info.RawValue = null;
AddValue(info, value, StoreLocation.Parsed);
}
internal void SetOrRemoveParsedValue(string name, object value)
{
if (value == null)
{
Remove(name);
}
else
{
SetParsedValue(name, value);
}
}
internal bool RemoveParsedValue(string name, object value)
{
Contract.Requires((name != null) && (name.Length > 0));
Contract.Requires(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Contract.Requires(value != null);
if (_headerStore == null)
{
return false;
}
// If we have a value for this header, then verify if we have a single value. If so, compare that
// value with 'item'. If we have a list of values, then remove 'item' from the list.
HeaderStoreItemInfo info = null;
if (TryGetAndParseHeaderInfo(name, out info))
{
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
Debug.Assert(info.Parser.SupportsMultipleValues,
"This method should not be used for single-value headers. Use Remove(string) instead.");
bool result = false;
// If there is no entry, just return.
if (info.ParsedValue == null)
{
return false;
}
IEqualityComparer comparer = info.Parser.Comparer;
List<object> parsedValues = info.ParsedValue as List<object>;
if (parsedValues == null)
{
Debug.Assert(info.ParsedValue.GetType() == value.GetType(),
"Stored value does not have the same type as 'value'.");
if (AreEqual(value, info.ParsedValue, comparer))
{
info.ParsedValue = null;
result = true;
}
}
else
{
foreach (object item in parsedValues)
{
Debug.Assert(item.GetType() == value.GetType(),
"One of the stored values does not have the same type as 'value'.");
if (AreEqual(value, item, comparer))
{
// Remove 'item' rather than 'value', since the 'comparer' may consider two values
// equal even though the default obj.Equals() may not (e.g. if 'comparer' does
// case-insentive comparison for strings, but string.Equals() is case-sensitive).
result = parsedValues.Remove(item);
break;
}
}
// If we removed the last item in a list, remove the list.
if (parsedValues.Count == 0)
{
info.ParsedValue = null;
}
}
// If there is no value for the header left, remove the header.
if (info.IsEmpty)
{
bool headerRemoved = Remove(name);
Debug.Assert(headerRemoved, "Existing header '" + name + "' couldn't be removed.");
}
return result;
}
return false;
}
internal bool ContainsParsedValue(string name, object value)
{
Contract.Requires((name != null) && (name.Length > 0));
Contract.Requires(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Contract.Requires(value != null);
if (_headerStore == null)
{
return false;
}
// If we have a value for this header, then verify if we have a single value. If so, compare that
// value with 'item'. If we have a list of values, then compare each item in the list with 'item'.
HeaderStoreItemInfo info = null;
if (TryGetAndParseHeaderInfo(name, out info))
{
Debug.Assert(info.Parser != null, "Can't add parsed value if there is no parser available.");
Debug.Assert(info.Parser.SupportsMultipleValues,
"This method should not be used for single-value headers. Use equality comparer instead.");
// If there is no entry, just return.
if (info.ParsedValue == null)
{
return false;
}
List<object> parsedValues = info.ParsedValue as List<object>;
IEqualityComparer comparer = info.Parser.Comparer;
if (parsedValues == null)
{
Debug.Assert(info.ParsedValue.GetType() == value.GetType(),
"Stored value does not have the same type as 'value'.");
return AreEqual(value, info.ParsedValue, comparer);
}
else
{
foreach (object item in parsedValues)
{
Debug.Assert(item.GetType() == value.GetType(),
"One of the stored values does not have the same type as 'value'.");
if (AreEqual(value, item, comparer))
{
return true;
}
}
return false;
}
}
return false;
}
internal virtual void AddHeaders(HttpHeaders sourceHeaders)
{
Contract.Requires(sourceHeaders != null);
Debug.Assert(_parserStore == sourceHeaders._parserStore,
"Can only copy headers from an instance with the same header parsers.");
if (sourceHeaders._headerStore == null)
{
return;
}
List<string> invalidHeaders = null;
foreach (var header in sourceHeaders._headerStore)
{
// Only add header values if they're not already set on the message. Note that we don't merge
// collections: If both the default headers and the message have set some values for a certain
// header, then we don't try to merge the values.
if ((_headerStore == null) || (!_headerStore.ContainsKey(header.Key)))
{
HeaderStoreItemInfo sourceInfo = header.Value;
// If DefaultRequestHeaders values are copied to multiple messages, it is useful to parse these
// default header values only once. This is what we're doing here: By parsing raw headers in
// 'sourceHeaders' before copying values to our header store.
if (!sourceHeaders.ParseRawHeaderValues(header.Key, sourceInfo, false))
{
// If after trying to parse source header values no value is left (i.e. all values contain
// invalid newline chars), mark this header as 'to-be-deleted' and skip to the next header.
if (invalidHeaders == null)
{
invalidHeaders = new List<string>();
}
invalidHeaders.Add(header.Key);
}
else
{
AddHeaderInfo(header.Key, sourceInfo);
}
}
}
if (invalidHeaders != null)
{
Debug.Assert(sourceHeaders._headerStore != null);
foreach (string invalidHeader in invalidHeaders)
{
sourceHeaders._headerStore.Remove(invalidHeader);
}
}
}
private void AddHeaderInfo(string headerName, HeaderStoreItemInfo sourceInfo)
{
HeaderStoreItemInfo destinationInfo = CreateAndAddHeaderToStore(headerName);
Debug.Assert(sourceInfo.Parser == destinationInfo.Parser,
"Expected same parser on both source and destination header store for header '" + headerName +
"'.");
// We have custom header values. The parsed values are strings.
if (destinationInfo.Parser == null)
{
Debug.Assert((sourceInfo.RawValue == null) && (sourceInfo.InvalidValue == null),
"No raw or invalid values expected for custom headers.");
// Custom header values are always stored as string or list of strings.
destinationInfo.ParsedValue = CloneStringHeaderInfoValues(sourceInfo.ParsedValue);
}
else
{
// We have a parser, so we have to copy invalid values and clone parsed values.
// Invalid values are always strings. Strings are immutable. So we only have to clone the
// collection (if there is one).
destinationInfo.InvalidValue = CloneStringHeaderInfoValues(sourceInfo.InvalidValue);
// Now clone and add parsed values (if any).
if (sourceInfo.ParsedValue != null)
{
List<object> sourceValues = sourceInfo.ParsedValue as List<object>;
if (sourceValues == null)
{
CloneAndAddValue(destinationInfo, sourceInfo.ParsedValue);
}
else
{
foreach (object item in sourceValues)
{
CloneAndAddValue(destinationInfo, item);
}
}
}
}
}
private static void CloneAndAddValue(HeaderStoreItemInfo destinationInfo, object source)
{
// We only have one value. Clone it and assign it to the store.
ICloneable cloneableValue = source as ICloneable;
if (cloneableValue != null)
{
AddValue(destinationInfo, cloneableValue.Clone(), StoreLocation.Parsed);
}
else
{
// If it doesn't implement ICloneable, it's a value type or an immutable type like String/Uri.
AddValue(destinationInfo, source, StoreLocation.Parsed);
}
}
private static object CloneStringHeaderInfoValues(object source)
{
if (source == null)
{
return null;
}
List<object> sourceValues = source as List<object>;
if (sourceValues == null)
{
// If we just have one value, return the reference to the string (strings are immutable so it's OK
// to use the reference).
return source;
}
else
{
// If we have a list of strings, create a new list and copy all strings to the new list.
return new List<object>(sourceValues);
}
}
private HeaderStoreItemInfo GetOrCreateHeaderInfo(string name, bool parseRawValues)
{
Contract.Requires((name != null) && (name.Length > 0));
Contract.Requires(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
Contract.Ensures(Contract.Result<HeaderStoreItemInfo>() != null);
HeaderStoreItemInfo result = null;
bool found = false;
if (parseRawValues)
{
found = TryGetAndParseHeaderInfo(name, out result);
}
else
{
found = TryGetHeaderInfo(name, out result);
}
if (!found)
{
result = CreateAndAddHeaderToStore(name);
}
return result;
}
private HeaderStoreItemInfo CreateAndAddHeaderToStore(string name)
{
// If we don't have the header in the store yet, add it now.
HeaderStoreItemInfo result = new HeaderStoreItemInfo(GetParser(name));
AddHeaderToStore(name, result);
return result;
}
private void AddHeaderToStore(string name, HeaderStoreItemInfo info)
{
if (_headerStore == null)
{
_headerStore = new Dictionary<string, HeaderStoreItemInfo>(
StringComparer.OrdinalIgnoreCase);
}
_headerStore.Add(name, info);
}
private bool TryGetHeaderInfo(string name, out HeaderStoreItemInfo info)
{
if (_headerStore == null)
{
info = null;
return false;
}
return _headerStore.TryGetValue(name, out info);
}
private bool TryGetAndParseHeaderInfo(string name, out HeaderStoreItemInfo info)
{
if (TryGetHeaderInfo(name, out info))
{
return ParseRawHeaderValues(name, info, true);
}
return false;
}
private bool ParseRawHeaderValues(string name, HeaderStoreItemInfo info, bool removeEmptyHeader)
{
// Prevent multiple threads from parsing the raw value at the same time, or else we would get
// false duplicates or false nulls.
lock (info)
{
// Unlike TryGetHeaderInfo() this method tries to parse all non-validated header values (if any)
// before returning to the caller.
if (info.RawValue != null)
{
List<string> rawValues = info.RawValue as List<string>;
if (rawValues == null)
{
ParseSingleRawHeaderValue(name, info);
}
else
{
ParseMultipleRawHeaderValues(name, info, rawValues);
}
// At this point all values are either in info.ParsedValue, info.InvalidValue, or were removed since they
// contain invalid newline chars. Reset RawValue.
info.RawValue = null;
// During parsing, we removed tha value since it contains invalid newline chars. Return false to indicate that
// this is an empty header. If the caller specified to remove empty headers, we'll remove the header before
// returning.
if ((info.InvalidValue == null) && (info.ParsedValue == null))
{
if (removeEmptyHeader)
{
// After parsing the raw value, no value is left because all values contain invalid newline
// chars.
Debug.Assert(_headerStore != null);
_headerStore.Remove(name);
}
return false;
}
}
}
return true;
}
private static void ParseMultipleRawHeaderValues(string name, HeaderStoreItemInfo info, List<string> rawValues)
{
if (info.Parser == null)
{
foreach (string rawValue in rawValues)
{
if (!ContainsInvalidNewLine(rawValue, name))
{
AddValue(info, rawValue, StoreLocation.Parsed);
}
}
}
else
{
foreach (string rawValue in rawValues)
{
if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true))
{
if (Logging.On) Logging.PrintWarning(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_invalid_value, name, rawValue));
}
}
}
}
private static void ParseSingleRawHeaderValue(string name, HeaderStoreItemInfo info)
{
string rawValue = info.RawValue as string;
Debug.Assert(rawValue != null, "RawValue must either be List<string> or string.");
if (info.Parser == null)
{
if (!ContainsInvalidNewLine(rawValue, name))
{
AddValue(info, rawValue, StoreLocation.Parsed);
}
}
else
{
if (!TryParseAndAddRawHeaderValue(name, info, rawValue, true))
{
if (Logging.On) Logging.PrintWarning(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_invalid_value, name, rawValue));
}
}
}
// See Add(name, string)
internal bool TryParseAndAddValue(string name, string value)
{
// We don't use GetOrCreateHeaderInfo() here, since this would create a new header in the store. If parsing
// the value then throws, we would have to remove the header from the store again. So just get a
// HeaderStoreItemInfo object and try to parse the value. If it works, we'll add the header.
HeaderStoreItemInfo info;
bool addToStore;
PrepareHeaderInfoForAdd(name, out info, out addToStore);
bool result = TryParseAndAddRawHeaderValue(name, info, value, false);
if (result && addToStore && (info.ParsedValue != null))
{
// If we get here, then the value could be parsed correctly. If we created a new HeaderStoreItemInfo, add
// it to the store if we added at least one value.
AddHeaderToStore(name, info);
}
return result;
}
// See ParseAndAddValue
private static bool TryParseAndAddRawHeaderValue(string name, HeaderStoreItemInfo info, string value, bool addWhenInvalid)
{
Contract.Requires(info != null);
Contract.Requires(info.Parser != null);
// Values are added as 'invalid' if we either can't parse the value OR if we already have a value
// and the current header doesn't support multiple values: e.g. trying to add a date/time value
// to the 'Date' header if we already have a date/time value will result in the second value being
// added to the 'invalid' header values.
if (!info.CanAddValue)
{
if (addWhenInvalid)
{
AddValue(info, value ?? string.Empty, StoreLocation.Invalid);
}
return false;
}
int index = 0;
object parsedValue = null;
if (info.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue))
{
// The raw string only represented one value (which was successfully parsed). Add the value and return.
if ((value == null) || (index == value.Length))
{
if (parsedValue != null)
{
AddValue(info, parsedValue, StoreLocation.Parsed);
}
return true;
}
Debug.Assert(index < value.Length, "Parser must return an index value within the string length.");
// If we successfully parsed a value, but there are more left to read, store the results in a temp
// list. Only when all values are parsed successfully write the list to the store.
List<object> parsedValues = new List<object>();
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
while (index < value.Length)
{
if (info.Parser.TryParseValue(value, info.ParsedValue, ref index, out parsedValue))
{
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
}
else
{
if (!ContainsInvalidNewLine(value, name) && addWhenInvalid)
{
AddValue(info, value, StoreLocation.Invalid);
}
return false;
}
}
// All values were parsed correctly. Copy results to the store.
foreach (object item in parsedValues)
{
AddValue(info, item, StoreLocation.Parsed);
}
return true;
}
if (!ContainsInvalidNewLine(value, name) && addWhenInvalid)
{
AddValue(info, value ?? string.Empty, StoreLocation.Invalid);
}
return false;
}
private static void AddValue(HeaderStoreItemInfo info, object value, StoreLocation location)
{
// Since we have the same pattern for all three store locations (raw, invalid, parsed), we use
// this helper method to deal with adding values:
// - if 'null' just set the store property to 'value'
// - if 'List<T>' append 'value' to the end of the list
// - if 'T', i.e. we have already a value stored (but no list), create a list, add the stored value
// to the list and append 'value' at the end of the newly created list.
Debug.Assert((info.Parser != null) || ((info.Parser == null) && (value.GetType() == typeof(string))),
"If no parser is defined, then the value must be string.");
object currentStoreValue = null;
switch (location)
{
case StoreLocation.Raw:
currentStoreValue = info.RawValue;
AddValueToStoreValue<string>(info, value, ref currentStoreValue);
info.RawValue = currentStoreValue;
break;
case StoreLocation.Invalid:
currentStoreValue = info.InvalidValue;
AddValueToStoreValue<string>(info, value, ref currentStoreValue);
info.InvalidValue = currentStoreValue;
break;
case StoreLocation.Parsed:
Debug.Assert((value == null) || (!(value is List<object>)),
"Header value types must not derive from List<object> since this type is used internally to store " +
"lists of values. So we would not be able to distinguish between a single value and a list of values.");
currentStoreValue = info.ParsedValue;
AddValueToStoreValue<object>(info, value, ref currentStoreValue);
info.ParsedValue = currentStoreValue;
break;
default:
Debug.Assert(false, "Unknown StoreLocation value: " + location.ToString());
break;
}
}
private static void AddValueToStoreValue<T>(HeaderStoreItemInfo info, object value,
ref object currentStoreValue) where T : class
{
// If there is no value set yet, then add current item as value (we don't create a list
// if not required). If 'info.Value' is already assigned then make sure 'info.Value' is a
// List<T> and append 'item' to the list.
if (currentStoreValue == null)
{
currentStoreValue = value;
}
else
{
List<T> storeValues = currentStoreValue as List<T>;
if (storeValues == null)
{
storeValues = new List<T>(2);
Debug.Assert(value is T);
storeValues.Add(currentStoreValue as T);
currentStoreValue = storeValues;
}
Debug.Assert(value is T);
storeValues.Add(value as T);
}
}
// Since most of the time we just have 1 value, we don't create a List<object> for one value, but we change
// the return type to 'object'. The caller has to deal with the return type (object vs. List<object>). This
// is to optimize the most common scenario where a header has only one value.
internal object GetParsedValues(string name)
{
Contract.Requires((name != null) && (name.Length > 0));
Contract.Requires(HttpRuleParser.GetTokenLength(name, 0) == name.Length);
HeaderStoreItemInfo info = null;
if (!TryGetAndParseHeaderInfo(name, out info))
{
return null;
}
return info.ParsedValue;
}
private void PrepareHeaderInfoForAdd(string name, out HeaderStoreItemInfo info, out bool addToStore)
{
info = null;
addToStore = false;
if (!TryGetAndParseHeaderInfo(name, out info))
{
info = new HeaderStoreItemInfo(GetParser(name));
addToStore = true;
}
}
private void ParseAndAddValue(string name, HeaderStoreItemInfo info, string value)
{
Contract.Requires(info != null);
if (info.Parser == null)
{
// If we don't have a parser for the header, we consider the value valid if it doesn't contains
// invalid newline characters. We add the values as "parsed value". Note that we allow empty values.
CheckInvalidNewLine(value);
AddValue(info, value ?? string.Empty, StoreLocation.Parsed);
return;
}
// If the header only supports 1 value, we can add the current value only if there is no
// value already set.
if (!info.CanAddValue)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_single_value_header, name));
}
int index = 0;
object parsedValue = info.Parser.ParseValue(value, info.ParsedValue, ref index);
// The raw string only represented one value (which was successfully parsed). Add the value and return.
// If value is null we still have to first call ParseValue() to allow the parser to decide whether null is
// a valid value. If it is (i.e. no exception thrown), we set the parsed value (if any) and return.
if ((value == null) || (index == value.Length))
{
// If the returned value is null, then it means the header accepts empty values. I.e. we don't throw
// but we don't add 'null' to the store either.
if (parsedValue != null)
{
AddValue(info, parsedValue, StoreLocation.Parsed);
}
return;
}
Debug.Assert(index < value.Length, "Parser must return an index value within the string length.");
// If we successfully parsed a value, but there are more left to read, store the results in a temp
// list. Only when all values are parsed successfully write the list to the store.
List<object> parsedValues = new List<object>();
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
while (index < value.Length)
{
parsedValue = info.Parser.ParseValue(value, info.ParsedValue, ref index);
if (parsedValue != null)
{
parsedValues.Add(parsedValue);
}
}
// All values were parsed correctly. Copy results to the store.
foreach (object item in parsedValues)
{
AddValue(info, item, StoreLocation.Parsed);
}
}
private HttpHeaderParser GetParser(string name)
{
if (_parserStore == null)
{
return null;
}
HttpHeaderParser parser = null;
if (_parserStore.TryGetValue(name, out parser))
{
return parser;
}
return null;
}
private void CheckHeaderName(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "name");
}
if (HttpRuleParser.GetTokenLength(name, 0) != name.Length)
{
throw new FormatException(SR.net_http_headers_invalid_header_name);
}
if ((_invalidHeaders != null) && (_invalidHeaders.Contains(name)))
{
throw new InvalidOperationException(SR.net_http_headers_not_allowed_header_name);
}
}
private bool TryCheckHeaderName(string name)
{
if (string.IsNullOrEmpty(name))
{
return false;
}
if (HttpRuleParser.GetTokenLength(name, 0) != name.Length)
{
return false;
}
if ((_invalidHeaders != null) && (_invalidHeaders.Contains(name)))
{
return false;
}
return true;
}
private static void CheckInvalidNewLine(string value)
{
if (value == null)
{
return;
}
if (HttpRuleParser.ContainsInvalidNewLine(value))
{
throw new FormatException(SR.net_http_headers_no_newlines);
}
}
private static bool ContainsInvalidNewLine(string value, string name)
{
if (HttpRuleParser.ContainsInvalidNewLine(value))
{
if (Logging.On) Logging.PrintError(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_no_newlines, name, value));
return true;
}
return false;
}
private static string[] GetValuesAsStrings(HeaderStoreItemInfo info)
{
return GetValuesAsStrings(info, null);
}
// When doing exclusion comparison, assume raw values have been parsed.
private static string[] GetValuesAsStrings(HeaderStoreItemInfo info, object exclude)
{
Contract.Ensures(Contract.Result<string[]>() != null);
int length = GetValueCount(info);
string[] values = new string[length];
if (length > 0)
{
int currentIndex = 0;
ReadStoreValues<string>(values, info.RawValue, null, null, ref currentIndex);
ReadStoreValues<object>(values, info.ParsedValue, info.Parser, exclude, ref currentIndex);
// Set parser parameter to 'null' for invalid values: The invalid values is always a string so we
// don't need the parser to "serialize" the value to a string.
ReadStoreValues<string>(values, info.InvalidValue, null, null, ref currentIndex);
// The values array may not be full because some values were excluded
if (currentIndex < length)
{
string[] trimmedValues = new string[currentIndex];
Array.Copy(values, 0, trimmedValues, 0, currentIndex);
values = trimmedValues;
}
}
return values;
}
private static int GetValueCount(HeaderStoreItemInfo info)
{
Contract.Requires(info != null);
int valueCount = 0;
UpdateValueCount<string>(info.RawValue, ref valueCount);
UpdateValueCount<string>(info.InvalidValue, ref valueCount);
UpdateValueCount<object>(info.ParsedValue, ref valueCount);
return valueCount;
}
private static void UpdateValueCount<T>(object valueStore, ref int valueCount)
{
if (valueStore == null)
{
return;
}
List<T> values = valueStore as List<T>;
if (values != null)
{
valueCount += values.Count;
}
else
{
valueCount++;
}
}
private static void ReadStoreValues<T>(string[] values, object storeValue, HttpHeaderParser parser,
T exclude, ref int currentIndex)
{
Contract.Requires(values != null);
if (storeValue != null)
{
List<T> storeValues = storeValue as List<T>;
if (storeValues == null)
{
if (ShouldAdd<T>(storeValue, parser, exclude))
{
values[currentIndex] = parser == null ? storeValue.ToString() : parser.ToString(storeValue);
currentIndex++;
}
}
else
{
foreach (object item in storeValues)
{
if (ShouldAdd<T>(item, parser, exclude))
{
values[currentIndex] = parser == null ? item.ToString() : parser.ToString(item);
currentIndex++;
}
}
}
}
}
private static bool ShouldAdd<T>(object storeValue, HttpHeaderParser parser, T exclude)
{
bool add = true;
if (parser != null && exclude != null)
{
if (parser.Comparer != null)
{
add = !parser.Comparer.Equals(exclude, storeValue);
}
else
{
add = !exclude.Equals(storeValue);
}
}
return add;
}
private bool AreEqual(object value, object storeValue, IEqualityComparer comparer)
{
Contract.Requires(value != null);
if (comparer != null)
{
return comparer.Equals(value, storeValue);
}
// We don't have a comparer, so use the Equals() method.
return value.Equals(storeValue);
}
#region Private Classes
private class HeaderStoreItemInfo
{
private object _rawValue;
private object _invalidValue;
private object _parsedValue;
private HttpHeaderParser _parser;
internal object RawValue
{
get { return _rawValue; }
set { _rawValue = value; }
}
internal object InvalidValue
{
get { return _invalidValue; }
set { _invalidValue = value; }
}
internal object ParsedValue
{
get { return _parsedValue; }
set { _parsedValue = value; }
}
internal HttpHeaderParser Parser
{
get { return _parser; }
}
internal bool CanAddValue
{
get
{
Debug.Assert(_parser != null,
"There should be no reason to call CanAddValue if there is no parser for the current header.");
// If the header only supports one value, and we have already a value set, then we can't add
// another value. E.g. the 'Date' header only supports one value. We can't add multiple timestamps
// to 'Date'.
// So if this is a known header, ask the parser if it supports multiple values and check wheter
// we already have a (valid or invalid) value.
// Note that we ignore the rawValue by purpose: E.g. we are parsing 2 raw values for a header only
// supporting 1 value. When the first value gets parsed, CanAddValue returns true and we add the
// parsed value to ParsedValue. When the second value is parsed, CanAddValue returns false, because
// we have already a parsed value.
return ((_parser.SupportsMultipleValues) || ((_invalidValue == null) && (_parsedValue == null)));
}
}
internal bool IsEmpty
{
get { return ((_rawValue == null) && (_invalidValue == null) && (_parsedValue == null)); }
}
internal HeaderStoreItemInfo(HttpHeaderParser parser)
{
// Can be null.
_parser = parser;
}
}
#endregion
}
}
| |
using System.ComponentModel;
using System.Drawing.Drawing2D;
namespace NetDimension.NanUI.HostWindow;
using System.Collections.Specialized;
using Vanara.PInvoke;
using static Vanara.PInvoke.User32;
partial class _FackUnusedClass
{
}
internal partial class BorderlessWindow : Form
{
Size? _minimumSize = null;
internal static readonly IntPtr TRUE = new IntPtr(1);
internal static readonly IntPtr FALSE = new IntPtr(0);
internal static readonly IntPtr MESSAGE_HANDLED = new IntPtr(1);
internal static readonly IntPtr MESSAGE_PROCESS = new IntPtr(0);
internal protected bool IsWindowFocused
{
get;
internal set;
}
private Color _shadowColor = ColorTranslator.FromHtml("#CC000000");
private Color? _inactiveShadowColor = null;
private ShadowEffect _windowShadowStyle = ShadowEffect.Normal;
private CornerStyle _windowCornerStyle = CornerStyle.Normal;
#region Window Sizing
private bool _shouldPerformMaximiazedState = false;
private bool _isLoaded = false;
private FieldInfo _clientWidthField;
private FieldInfo _clientHeightField;
private FieldInfo _formStateSetClientSizeField;
private FieldInfo _formStateField;
internal Rectangle RealFormRectangle
{
get
{
GetWindowRect(hWnd, out var windowRect);
return new Rectangle(0, 0, windowRect.Width, windowRect.Height);
}
}
internal int CornerSize => (int)CornerStyle;
internal FormWindowState MinMaxState
{
get
{
var retval = (WindowStyles)GetWindowLong(hWnd, WindowLongFlags.GWL_STYLE);
var max = (retval & WindowStyles.WS_MAXIMIZE) > 0;
if (max)
return FormWindowState.Maximized;
var min = (retval & WindowStyles.WS_MINIMIZE) > 0;
if (min)
return FormWindowState.Minimized;
return FormWindowState.Normal;
}
}
private void PatchClientSize()
{
if (FormBorderStyle != FormBorderStyle.None)
{
var size = ClientSizeFromSize(Size);
_clientWidthField.SetValue(this, size.Width);
_clientHeightField.SetValue(this, size.Height);
}
}
private Size PatchWindowSizeInRestoreWindowBoundsIfNecessary(int width, int height)
{
if (WindowState == FormWindowState.Normal)
{
try
{
var restoredWindowBoundsSpecified = typeof(Form).GetField("restoredWindowBoundsSpecified", BindingFlags.NonPublic | BindingFlags.Instance);
var restoredSpecified = (BoundsSpecified)restoredWindowBoundsSpecified.GetValue(this);
if ((restoredSpecified & BoundsSpecified.Size) != BoundsSpecified.None)
{
var formStateExWindowBoundsFieldInfo = typeof(Form).GetField("FormStateExWindowBoundsWidthIsClientSize", BindingFlags.NonPublic | BindingFlags.Static);
var formStateExFieldInfo = typeof(Form).GetField("formStateEx", BindingFlags.NonPublic | BindingFlags.Instance);
var restoredBoundsFieldInfo = typeof(Form).GetField("restoredWindowBounds", BindingFlags.NonPublic | BindingFlags.Instance);
if (formStateExWindowBoundsFieldInfo != null && formStateExFieldInfo != null && restoredBoundsFieldInfo != null)
{
var restoredWindowBounds = (Rectangle)restoredBoundsFieldInfo.GetValue(this);
var section = (BitVector32.Section)formStateExWindowBoundsFieldInfo.GetValue(this);
var vector = (BitVector32)formStateExFieldInfo.GetValue(this);
if (vector[section] == 1)
{
width = restoredWindowBounds.Width;
height = restoredWindowBounds.Height;
}
}
}
}
catch
{
}
}
return new Size(width, height);
}
private void InitializeReflectedFields()
{
_clientWidthField = typeof(Control).GetField("_clientWidth", BindingFlags.NonPublic | BindingFlags.Instance) ?? typeof(Control).GetField("clientWidth", BindingFlags.NonPublic | BindingFlags.Instance);
_clientHeightField = typeof(Control).GetField("_clientHeight", BindingFlags.NonPublic | BindingFlags.Instance) ?? typeof(Control).GetField("clientHeight", BindingFlags.NonPublic | BindingFlags.Instance);
_formStateSetClientSizeField = typeof(Form).GetField("FormStateSetClientSize", BindingFlags.NonPublic | BindingFlags.Static);
_formStateField = typeof(Form).GetField("formState", BindingFlags.NonPublic | BindingFlags.Instance);
}
internal void SendFrameChangedMessage()
{
SetWindowPos(hWnd, HWND.NULL, 0, 0, 0, 0, SetWindowPosFlags.SWP_FRAMECHANGED | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOCOPYBITS | SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOREPOSITION | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOZORDER);
}
internal void InvalidateNonClientArea()
{
InvalidateNonClientArea(Rectangle.Empty);
}
private void InvalidateNonClientArea(Rectangle invalidRect)
{
if (!IsHandleCreated || IsDisposed)
return;
try
{
RedrawWindow(hWnd, null, HRGN.NULL, RedrawWindowFlags.RDW_FRAME | RedrawWindowFlags.RDW_UPDATENOW | RedrawWindowFlags.RDW_VALIDATE);
UpdateWindow(hWnd);
}
catch { }
}
internal Padding GetNonClientAeraBorders()
{
var rect = RECT.Empty;
var screenRect = ClientRectangle;
screenRect.Offset(-Bounds.Left, -Bounds.Top);
rect.top = screenRect.Top;
rect.left = screenRect.Left;
rect.bottom = screenRect.Bottom;
rect.right = screenRect.Right;
AdjustWindowRect(ref rect, (WindowStyles)CreateParams.Style, (WindowStylesEx)CreateParams.ExStyle);
return new Padding
{
Top = screenRect.Top - rect.top,
Left = screenRect.Left - rect.left,
Bottom = rect.bottom - screenRect.Bottom,
Right = rect.right - screenRect.Right
};
}
internal GraphicsPath GetWindowBorderPath()
{
var rect = RealFormRectangle;
return GetRoundedRectanglePath(rect, CornerSize);
}
private GraphicsPath GetRoundedRectanglePath(Rectangle rect, int radius)
{
var roundedRect = new GraphicsPath();
roundedRect.StartFigure();
if (radius == 0)
{
roundedRect.AddRectangle(rect);
}
else
{
roundedRect.AddArc(rect.X, rect.Y, radius * 2, radius * 2, 180, 90);
roundedRect.AddLine(rect.X + radius, rect.Y, rect.Right - radius * 2, rect.Y);
roundedRect.AddArc(rect.X + rect.Width - radius * 2, rect.Y, radius * 2, radius * 2, 270, 90);
roundedRect.AddLine(rect.Right, rect.Y + radius * 2, rect.Right, rect.Y + rect.Height - radius * 2);
roundedRect.AddArc(rect.X + rect.Width - radius * 2, rect.Y + rect.Height - radius * 2, radius * 2, radius * 2, 0, 90);
roundedRect.AddLine(rect.Right - radius * 2, rect.Bottom, rect.X + radius * 2, rect.Bottom);
roundedRect.AddArc(rect.X, rect.Bottom - radius * 2, radius * 2, radius * 2, 90, 90);
roundedRect.AddLine(rect.X, rect.Bottom - radius * 2, rect.X, rect.Y + radius * 2);
}
roundedRect.CloseFigure();
return roundedRect;
}
internal void RemoveWindowRegion()
{
Region?.Dispose();
Region = null;
}
internal void SetWindowRegion(GraphicsPath pathRegion)
{
Region oldRegion = null;
if (Region != null)
{
oldRegion = Region;
}
Region = new Region(pathRegion);
oldRegion?.Dispose();
}
internal void SetWindowRegion(Rectangle rectangleRegion)
{
Region oldRegion = null;
if (Region != null)
{
oldRegion = Region;
}
Region = new Region(rectangleRegion);
oldRegion?.Dispose();
}
private void AdjustWindowRect(ref RECT rect, WindowStyles style, WindowStylesEx exStyle)
{
if (DpiHelper.IsPerMonitorV2Awareness)
{
AdjustWindowRectExForDpi(ref rect, style, false, exStyle, (uint)DpiHelper.GetDpiForWindow(hWnd));
}
else
{
AdjustWindowRectEx(ref rect, style, false, exStyle);
}
}
#endregion
#region Dpi Features
private bool _isBoundsChangingLocked = false;
private int _deviceDpi;
internal protected float ScaleFactor { get; private set; } = 1.0f;
protected void CheckResetDPIAutoScale(bool force = false)
{
if (force)
{
var fi = typeof(ContainerControl).GetField("currentAutoScaleDimensions", BindingFlags.NonPublic | BindingFlags.Instance);
var dpi = IsHandleCreated ? DpiHelper.GetDpiForWindow(hWnd) : 96;
if (fi != null)
fi.SetValue(this, new SizeF(dpi, dpi));
}
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Always)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
protected int CurrentDpi => DpiHelper.IsPerMonitorV2Awareness ? _deviceDpi : DpiHelper.DeviceDpi;
private bool WmDpiChanged(ref Message m)
{
var oldDeviceDpi = _deviceDpi;
var newDeviceDpi = Macros.SignedHIWORD(m.WParam);
var suggestedRect = Marshal.PtrToStructure<RECT>(m.LParam);
ScaleFactor = DpiHelper.GetScaleFactorForWindow(hWnd);
_deviceDpi = newDeviceDpi;
var maxSizeState = MaximumSize;
var minSizeState = MinimumSize;
MinimumSize = Size.Empty;
MaximumSize = Size.Empty;
SetWindowPos(hWnd, HWND.NULL, suggestedRect.left, suggestedRect.top, suggestedRect.Width, suggestedRect.Height, SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE);
var scaleFactor = (float)newDeviceDpi / oldDeviceDpi;
MinimumSize = DpiHelper.CalcScaledSize(minSizeState, new SizeF(scaleFactor, scaleFactor));
MaximumSize = DpiHelper.CalcScaledSize(maxSizeState, new SizeF(scaleFactor, scaleFactor));
_isBoundsChangingLocked = true;
PerformLayout();
Update();
_isBoundsChangingLocked = false;
DrawShadowBitmap();
SystemDpiChanged?.Invoke(this, new WindowDpiChangedEventArgs(oldDeviceDpi, newDeviceDpi));
return true;
}
#endregion
#region Hit Test
public HitTestValues HitTest(int x, int y)
{
return HitTest(new Point(x, y));
}
public HitTestValues HitTest(Point pt)
{
var htSize = Convert.ToInt32(Math.Ceiling(4 * ScaleFactor));
var rect = new Rectangle(Point.Empty, RealFormRectangle.Size);
var corner = CornerSize;
var x = pt.X;
var y = pt.Y;
HitTestValues htValue = HitTestValues.HTCLIENT;
if (corner == 0)
{
if (x < rect.Left + htSize * 2 && y < rect.Top + htSize * 2)
{
htValue = HitTestValues.HTTOPLEFT;
}
else if (x >= rect.Left + htSize * 2 && x <= rect.Right - htSize * 2 && y <= rect.Top + htSize)
{
htValue = HitTestValues.HTTOP;
}
else if (x > rect.Right - htSize * 2 && y <= rect.Top + htSize * 2)
{
htValue = HitTestValues.HTTOPRIGHT;
}
else if (x <= rect.Left + htSize && y >= rect.Top + htSize * 2 && y <= rect.Bottom - htSize * 2)
{
htValue = HitTestValues.HTLEFT;
}
else if (x >= rect.Right - htSize && y >= rect.Top * 2 + htSize && y <= rect.Bottom - htSize * 2)
{
htValue = HitTestValues.HTRIGHT;
}
else if (x <= rect.Left + htSize * 2 && y >= rect.Bottom - htSize * 2)
{
htValue = HitTestValues.HTBOTTOMLEFT;
}
else if (x > rect.Left + htSize * 2 && x < rect.Right - htSize * 2 && y >= rect.Bottom - htSize)
{
htValue = HitTestValues.HTBOTTOM;
}
else if (x >= rect.Right - htSize * 2 && y >= rect.Bottom - htSize * 2)
{
htValue = HitTestValues.HTBOTTOMRIGHT;
}
}
else
{
if (x < rect.Left + htSize * 2 && y < rect.Top + htSize * 2)
{
htValue = HitTestValues.HTTOPLEFT;
}
else if (x < rect.Left + corner && y < rect.Top + corner && Math.Sqrt(Math.Pow(x - (rect.Left + corner), 2) + Math.Pow(y - (rect.Top + corner), 2)) > corner / 2)
{
htValue = HitTestValues.HTTOPLEFT;
}
else if (x > rect.Right - htSize * 2 && y <= rect.Top + htSize * 2)
{
htValue = HitTestValues.HTTOPRIGHT;
}
else if ((x > rect.Right - corner && y <= rect.Top + corner) && Math.Sqrt(Math.Pow(x - (rect.Right - corner), 2) + Math.Pow(y - (rect.Top + corner), 2)) > corner / 2)
{
htValue = HitTestValues.HTTOPRIGHT;
}
else if (x <= rect.Left + htSize * 2 && y >= rect.Bottom - htSize * 2)
{
htValue = HitTestValues.HTBOTTOMLEFT;
}
else if (x <= rect.Left + corner && y >= rect.Bottom - corner && Math.Sqrt(Math.Pow(x - (rect.Left + corner), 2) + Math.Pow(y - (rect.Bottom - corner), 2)) > corner / 2)
{
htValue = HitTestValues.HTBOTTOMLEFT;
}
else if (x >= rect.Right - htSize * 2 && y >= rect.Bottom - htSize * 2)
{
htValue = HitTestValues.HTBOTTOMRIGHT;
}
else if (x >= rect.Right - corner && y >= rect.Bottom - corner && Math.Sqrt(Math.Pow(x - (rect.Right - corner), 2) + Math.Pow(y - (rect.Bottom - corner), 2)) > corner / 2)
{
htValue = HitTestValues.HTBOTTOMRIGHT;
}
else if (x >= rect.Left + corner && x <= rect.Right - corner && y <= rect.Top + htSize)
{
htValue = HitTestValues.HTTOP;
}
else if (x > rect.Left + corner && x < rect.Right - corner && y >= rect.Bottom - htSize)
{
htValue = HitTestValues.HTBOTTOM;
}
else if (x <= rect.Left + htSize && y >= rect.Top + corner && y <= rect.Bottom - corner)
{
htValue = HitTestValues.HTLEFT;
}
else if (x >= rect.Right - htSize && y >= rect.Top + corner && y <= rect.Bottom - corner)
{
htValue = HitTestValues.HTRIGHT;
}
}
return htValue;
}
#endregion
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace QuantConnect
{
/// <summary>
/// Lean exchange definition
/// </summary>
public class Exchange
{
/// <summary>
/// Unknown exchange value
/// </summary>
public static Exchange UNKNOWN { get; } = new (string.Empty, string.Empty, "UNKNOWN", string.Empty);
/// <summary>
/// National Association of Securities Dealers Automated Quotation.
/// </summary>
public static Exchange NASDAQ { get; }
= new("NASDAQ", "Q", "National Association of Securities Dealers Automated Quotation", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// Bats Global Markets, Better Alternative Trading System
/// </summary>
public static Exchange BATS { get; }
= new("BATS", "Z", "Bats Global Markets, Better Alternative Trading System", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// New York Stock Archipelago Exchange
/// </summary>
public static Exchange ARCA { get; }
= new("ARCA", "P", "New York Stock Archipelago Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// New York Stock Exchange
/// </summary>
public static Exchange NYSE { get; }
= new("NYSE", "N", "New York Stock Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// National Stock Exchange
/// </summary>
/// <remarks>Is now known as the NYSE National</remarks>
public static Exchange NSX { get; }
= new("NSE", "C", "National Stock Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// The Financial Industry Regulatory Authority
/// </summary>
public static Exchange FINRA { get; }
= new("FINRA", "D", "The Financial Industry Regulatory Authority", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// Nasdaq International Securities Exchange
/// </summary>
public static Exchange ISE { get; }
= new("ISE", "I", "Nasdaq International Securities Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// Chicago Stock Exchange
/// </summary>
public static Exchange CSE { get; }
= new("CSE", "M", "Chicago Stock Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// The Chicago Board Options Exchange
/// </summary>
public static Exchange CBOE { get; }
= new("CBOE", "W", "The Chicago Board Options Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// The American Options Exchange
/// </summary>
public static Exchange NASDAQ_BX { get; }
= new("NASDAQ_BX", "B", "National Association of Securities Dealers Automated Quotation BX", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// The Securities Industry Automation Corporation
/// </summary>
public static Exchange SIAC { get; }
= new("SIAC", "SIAC", "The Securities Industry Automation Corporation", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// CBOE EDGA U.S. equities Exchange
/// </summary>
public static Exchange EDGA { get; }
= new("EDGA", "J", "CBOE EDGA U.S. equities Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// CBOE EDGX U.S. equities Exchange
/// </summary>
public static Exchange EDGX { get; }
= new("EDGX", "K", "CBOE EDGX U.S. equities Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// National Association of Securities Dealers Automated Quotation PSX
/// </summary>
public static Exchange NASDAQ_PSX { get; }
= new("NASDAQ_PSX", "X", "National Association of Securities Dealers Automated Quotation PSX", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// National Association of Securities Dealers Automated Quotation PSX
/// </summary>
public static Exchange BATS_Y { get; }
= new("BATS_Y", "Y", "Bats Global Markets, Better Alternative Trading System", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// The Boston Stock Exchange
/// </summary>
/// <remarks>Now NASDAQ OMX BX</remarks>
public static Exchange BOSTON { get; }
= new("BOSTON", "B", "The Boston Stock Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// The American Stock Exchange
/// </summary>
/// <remarks>Now NYSE MKT</remarks>
public static Exchange AMEX { get; }
= new("AMEX", "A", "The American Stock Exchange", QuantConnect.Market.USA, SecurityType.Equity);
/// <summary>
/// Bombay Stock Exchange
/// </summary>
public static Exchange BSE { get; }
= new("BSE", string.Empty, "Bombay Stock Exchange", QuantConnect.Market.India, SecurityType.Equity);
/// <summary>
/// National Stock Exchange of India
/// </summary>
public static Exchange NSE { get; }
= new("NSE", string.Empty, "National Stock Exchange of India", QuantConnect.Market.India, SecurityType.Equity);
/// <summary>
/// The American Options Exchange
/// </summary>
/// <remarks>Now NYSE Amex Options</remarks>
public static Exchange AMEX_Options { get; }
= new("AMEX", "A", "The American Options Exchange", QuantConnect.Market.USA, SecurityType.Option);
/// <summary>
/// The Options Price Reporting Authority
/// </summary>
public static Exchange OPRA { get; }
= new("OPRA", "O", "The Options Price Reporting Authority", QuantConnect.Market.USA, SecurityType.Option);
/// <summary>
/// CBOE Options Exchange
/// </summary>
public static Exchange C2 { get; }
= new("C2", "W", "CBOE Options Exchange", QuantConnect.Market.USA, SecurityType.Option);
/// <summary>
/// Miami International Securities Options Exchange
/// </summary>
public static Exchange MIAX { get; }
= new("MIAX", "M", "Miami International Securities Options Exchange", QuantConnect.Market.USA, SecurityType.Option);
/// <summary>
/// International Securities Options Exchange GEMINI
/// </summary>
public static Exchange ISE_GEMINI { get; }
= new("ISE_GEMINI", "H", "International Securities Options Exchange GEMINI", QuantConnect.Market.USA, SecurityType.Option);
/// <summary>
/// International Securities Options Exchange MERCURY
/// </summary>
public static Exchange ISE_MERCURY { get; }
= new("ISE_MERCURY", "J", "International Securities Options Exchange MERCURY", QuantConnect.Market.USA, SecurityType.Option);
/// <summary>
/// The Chicago Mercantile Exchange (CME), is an organized exchange for the trading of futures and options.
/// </summary>
public static Exchange CME { get; }
= new("CME", "CME", "Futures and Options Chicago Mercantile Exchange", QuantConnect.Market.CME, SecurityType.Future, SecurityType.FutureOption);
/// <summary>
/// The Chicago Board of Trade (CBOT) is a commodity exchange
/// </summary>
public static Exchange CBOT { get; }
= new("CBOT", "CBOT", " Chicago Board of Trade Commodity Exchange", QuantConnect.Market.CBOT, SecurityType.Future, SecurityType.FutureOption);
/// <summary>
/// Cboe Futures Exchange
/// </summary>
public static Exchange CFE { get; }
= new("CFE", "CFE", "CFE Futures Exchange", QuantConnect.Market.CFE, SecurityType.Future);
/// <summary>
/// COMEX Commodity Exchange
/// </summary>
public static Exchange COMEX { get; }
= new("COMEX", "COMEX", "COMEX Futures Exchange", QuantConnect.Market.COMEX, SecurityType.Future);
/// <summary>
/// The Intercontinental Exchange
/// </summary>
public static Exchange ICE { get; }
= new("ICE", "ICE", "The Intercontinental Exchange", QuantConnect.Market.ICE, SecurityType.Future);
/// <summary>
/// New York Mercantile Exchange
/// </summary>
public static Exchange NYMEX { get; }
= new("NYMEX", "NYMEX", "New York Mercantile Exchange", QuantConnect.Market.NYMEX, SecurityType.Future, SecurityType.FutureOption);
/// <summary>
/// London International Financial Futures and Options Exchange
/// </summary>
public static Exchange NYSELIFFE { get; }
= new("NYSELIFFE", "NYSELIFFE", "London International Financial Futures and Options Exchange", QuantConnect.Market.NYSELIFFE, SecurityType.Future, SecurityType.FutureOption);
/// <summary>
/// Exchange description
/// </summary>
[JsonIgnore]
public string Description { get; }
/// <summary>
/// The exchange short code
/// </summary>
public string Code { get; init; }
/// <summary>
/// The exchange name
/// </summary>
public string Name { get; init; }
/// <summary>
/// The associated lean market <see cref="Market"/>
/// </summary>
public string Market { get; init; }
/// <summary>
/// Security types traded in this exchange
/// </summary>
[JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Ignore)]
public IReadOnlyList<SecurityType> SecurityTypes { get; init; } = new List<SecurityType>();
/// <summary>
/// Creates a new empty exchange instance
/// </summary>
/// <remarks>For json round trip serialization</remarks>
private Exchange()
{
}
/// <summary>
/// Creates a new exchange instance
/// </summary>
private Exchange(string name, string code, string description, string market, params SecurityType[] securityTypes)
{
Name = name;
Market = market;
Description = description;
SecurityTypes = securityTypes?.ToList() ?? new List<SecurityType>();
Code = string.IsNullOrEmpty(code) ? name : code;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
public override string ToString()
{
return Name;
}
/// <summary>
/// Returns the string representation of this exchange
/// </summary>
public static implicit operator string(Exchange exchange)
{
return ReferenceEquals(exchange, null) ? string.Empty : exchange.ToString();
}
/// <summary>
/// Indicates whether the current object is equal to another object
/// </summary>
public override bool Equals(object? obj)
{
if (ReferenceEquals(this, obj))
{
return true;
}
var exchange = obj as Exchange;
if (ReferenceEquals(exchange, null) || ReferenceEquals(exchange, UNKNOWN))
{
// other is null or UNKNOWN (equivalents)
// so we need to know how We compare with UNKNOWN
return ReferenceEquals(this, UNKNOWN);
}
return Code == exchange.Code
&& Market == exchange.Market
&& SecurityTypes.All(exchange.SecurityTypes.Contains)
&& SecurityTypes.Count == exchange.SecurityTypes.Count;
}
/// <summary>
/// Equals operator
/// </summary>
/// <param name="left">The left operand</param>
/// <param name="right">The right operand</param>
/// <returns>True if both symbols are equal, otherwise false</returns>
public static bool operator ==(Exchange left, Exchange right)
{
if (ReferenceEquals(left, right))
{
return true;
}
if (ReferenceEquals(left, null) || left.Equals(UNKNOWN))
{
return ReferenceEquals(right, null) || right.Equals(UNKNOWN);
}
return left.Equals(right);
}
/// <summary>
/// Not equals operator
/// </summary>
/// <param name="left">The left operand</param>
/// <param name="right">The right operand</param>
/// <returns>True if both symbols are not equal, otherwise false</returns>
public static bool operator !=(Exchange left, Exchange right)
{
return !(left == right);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
public override int GetHashCode()
{
unchecked
{
var hashCode = Code.GetHashCode();
hashCode = (hashCode * 397) ^ Market.GetHashCode();
for (var i = 0; i < SecurityTypes.Count; i++)
{
hashCode = (hashCode * 397) ^ SecurityTypes[i].GetHashCode();
}
return hashCode;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// AssertionHelper is an optional base class for user tests,
/// allowing the use of shorter names in making asserts.
/// </summary>
[Obsolete("The AssertionHelper class will be removed in a coming release. " +
"Consider using the NUnit.StaticExpect NuGet package as a replacement.")]
public class AssertionHelper
{
#region Expect
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to
/// <see cref="Assert.That(bool, string, object[])"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect(bool condition, string message, params object[] args)
{
Assert.That(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="AssertionException"/>. Works Identically to <see cref="Assert.That(bool)"/>.
/// </summary>
/// <param name="condition">The evaluated condition</param>
public void Expect(bool condition)
{
Assert.That(condition, Is.True, null, null);
}
#endregion
#region ActualValueDelegate
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
public void Expect<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
{
Assert.That(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public void Expect<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
{
Assert.That(del, expr, message, args);
}
#endregion
#region TestDelegate
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A Constraint expression to be applied</param>
public void Expect(TestDelegate code, IResolveConstraint constraint)
{
Assert.That((object)code, constraint);
}
#endregion
#endregion
#region Expect<TActual>
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="actual">The actual value to test</param>
static public void Expect<TActual>(TActual actual, IResolveConstraint expression)
{
Assert.That(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and throwing an assertion exception on failure.
/// </summary>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="actual">The actual value to test</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Expect<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
{
Assert.That(actual, expression, message, args);
}
#endregion
#region Map
/// <summary>
/// Returns a ListMapper based on a collection.
/// </summary>
/// <param name="original">The original collection</param>
/// <returns></returns>
public ListMapper Map( ICollection original )
{
return new ListMapper( original );
}
#endregion
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return Is.Not; }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return Has.No; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public ConstraintExpression All
{
get { return Is.All; }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return Has.Some; }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return Has.None; }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public static ItemsConstraintExpression Exactly(int expectedCount)
{
return Has.Exactly(expectedCount);
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return Has.Property(name);
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Has.Length; }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Has.Count; }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Has.Message; }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Has.InnerException; }
}
#endregion
#region Attribute
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute(Type expectedType)
{
return Has.Attribute(expectedType);
}
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute<TExpected>()
{
return Attribute(typeof(TExpected));
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region Zero
/// <summary>
/// Returns a constraint that tests for equality with zero
/// </summary>
public EqualConstraint Zero
{
get { return new EqualConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#if SERIALIZATION
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in XML format.
/// </summary>
public XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endif
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the supplied argument
/// </summary>
public GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the supplied argument
/// </summary>
public LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf<TExpected>()
{
return new ExactTypeConstraint(typeof(TExpected));
}
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<TExpected>()
{
return new InstanceOfTypeConstraint(typeof(TExpected));
}
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom<TExpected>()
{
return new AssignableFromConstraint(typeof(TExpected));
}
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo<TExpected>()
{
return new AssignableToConstraint(typeof(TExpected));
}
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region SupersetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a superset of the collection supplied as an argument.
/// </summary>
public CollectionSupersetConstraint SupersetOf(IEnumerable expected)
{
return new CollectionSupersetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region Member
/// <summary>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </summary>
public SomeItemsConstraint Member(object expected)
{
return new SomeItemsConstraint(new EqualConstraint(expected));
}
/// <summary>
/// Returns a new <see cref="SomeItemsConstraint"/> checking for the
/// presence of a particular object in the collection.
/// </summary>
public SomeItemsConstraint Contains(object expected)
{
return new SomeItemsConstraint(new EqualConstraint(expected));
}
#endregion
#region Contains
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contains(string expected)
{
return new ContainsConstraint(expected);
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint ContainsSubstring(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region DoesNotContain
/// <summary>
/// Returns a constraint that fails if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.Contain")]
public SubstringConstraint DoesNotContain(string expected)
{
return new ConstraintExpression().Not.ContainsSubstring(expected);
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.StartWith or StartsWith")]
public StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region DoesNotStartWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.StartWith")]
public StartsWithConstraint DoesNotStartWith(string expected)
{
return new ConstraintExpression().Not.StartsWith(expected);
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.EndWith or EndsWith")]
public EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region DoesNotEndWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.EndWith")]
public EndsWithConstraint DoesNotEndWith(string expected)
{
return new ConstraintExpression().Not.EndsWith(expected);
}
#endregion
#region Matches
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Match(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Matches(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Match or Matches")]
public RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endregion
#region DoesNotMatch
/// <summary>
/// Returns a constraint that fails if the actual
/// value matches the pattern supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.Match")]
public RegexConstraint DoesNotMatch(string pattern)
{
return new ConstraintExpression().Not.Matches(pattern);
}
#endregion
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is a subpath of the expected path after canonicalization.
/// </summary>
public SubPathConstraint SubPathOf(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#region InRange
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public RangeConstraint InRange(object from, object to)
{
return new RangeConstraint(from, to);
}
#endregion
}
}
| |
/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
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.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.IO;
using Windows.Web;
using System.Xml;
using System.Xml.Linq;
using Windows.Web.Http;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Shield.Communication
{
public class BlobHelper : RESTHelper
{
// Constructor.
public BlobHelper(string storageAccount, string storageKey) : base("http://" + storageAccount + ".blob.core.windows.net/", storageAccount, storageKey)
{
}
public async Task<List<string>> ListContainers()
{
List<string> containers = new List<string>();
try
{
HttpRequestMessage request = CreateRESTRequest("GET", "?comp=list");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if ((int)response.StatusCode == 200)
{
var inputStream = await response.Content.ReadAsInputStreamAsync();
var memStream = new MemoryStream();
Stream testStream = inputStream.AsStreamForRead();
await testStream.CopyToAsync(memStream);
memStream.Position = 0;
using (StreamReader reader = new StreamReader(memStream))
{
string result = reader.ReadToEnd();
XElement x = XElement.Parse(result);
foreach (XElement container in x.Element("Containers").Elements("Container"))
{
containers.Add(container.Element("Name").Value);
//Debug.WriteLine(container.Element("Name").Value);
}
}
}
else
{
Debug.WriteLine("Request: " + response.RequestMessage.ToString());
Debug.WriteLine("Response: " + response);
}
return containers;
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
return null;
}
}
// Create a blob container.
// Return true on success, false if already exists, throw exception on error.
public async Task<bool> CreateContainer(string container)
{
try
{
HttpRequestMessage request = CreateRESTRequest("PUT", container + "?restype=container");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if (response.StatusCode == HttpStatusCode.Created)
{
return true;
}
else
{
Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase);
return false;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return false;
throw;
}
}
//// List blobs in a container.
public async Task<List<string>> ListBlobs(string container)
{
List<string> blobs = new List<string>();
try
{
HttpRequestMessage request = CreateRESTRequest("GET", container + "?restype=container&comp=list&include=snapshots&include=metadata");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if ((int)response.StatusCode == 200)
{
var inputStream = await response.Content.ReadAsInputStreamAsync();
var memStream = new MemoryStream();
Stream testStream = inputStream.AsStreamForRead();
await testStream.CopyToAsync(memStream);
memStream.Position = 0;
using (StreamReader reader = new StreamReader(memStream))
{
string result = reader.ReadToEnd();
XElement x = XElement.Parse(result);
foreach (XElement blob in x.Element("Blobs").Elements("Blob"))
{
blobs.Add(blob.Element("Name").Value);
//Debug.WriteLine(blob.Element("Name").Value);
}
}
}
else
{
Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase);
return null;
}
return blobs;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
throw;
}
}
// Retrieve the content of a blob.
// Return true on success, false if not found, throw exception on error.
public async Task<string> GetBlob(string container, string blob)
{
string content = null;
try
{
HttpRequestMessage request = CreateRESTRequest("GET", container + "/" + blob);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if ((int)response.StatusCode == 200)
{
var inputStream = await response.Content.ReadAsInputStreamAsync();
var memStream = new MemoryStream();
Stream testStream = inputStream.AsStreamForRead();
await testStream.CopyToAsync(memStream);
memStream.Position = 0;
using (StreamReader reader = new StreamReader(memStream))
{
content = reader.ReadToEnd();
}
return content;
}
else
{
Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase);
return null;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
throw;
}
}
public async Task<MemoryStream> GetBlobStream(string container, string blob)
{
try
{
HttpRequestMessage request = CreateRESTRequest("GET", container + "/" + blob);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if ((int)response.StatusCode == 200)
{
var inputStream = await response.Content.ReadAsInputStreamAsync();
var memStream = new MemoryStream();
Stream testStream = inputStream.AsStreamForRead();
await testStream.CopyToAsync(memStream);
memStream.Position = 0;
return memStream;
}
else
{
Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase);
return null;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
throw;
}
}
// Create or update a blob.
// Return true on success, false if not found, throw exception on error.
public async Task<bool> PutBlob(string container, string blob, string content)
{
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("x-ms-blob-type", "BlockBlob");
HttpRequestMessage request = CreateRESTRequest("PUT", container + "/" + blob, content, headers);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if (response.StatusCode == HttpStatusCode.Created)
{
return true;
}
else
{
Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase);
return false;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return false;
throw;
}
}
// Create or update a blob (Image).
// Return true on success, false if not found, throw exception on error.
public async Task<bool> PutBlob(string container, string blob, MemoryStream content)
{
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("x-ms-blob-type", "BlockBlob");
HttpRequestMessage request = CreateStreamRESTRequest("PUT", container + "/" + blob, content, headers);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if (response.StatusCode == HttpStatusCode.Created)
{
return true;
}
else
{
Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase);
return false;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return false;
throw;
}
}
// Retrieve a blob's properties.
// Return true on success, false if not found, throw exception on error.
public async Task<Dictionary<string, string>> GetBlobProperties(string container, string blob)
{
Dictionary<string, string> propertiesList = new Dictionary<string, string>();
try
{
HttpRequestMessage request = CreateStreamRESTRequest("HEAD", container + "/" + blob);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if ((int)response.StatusCode == 200)
{
if (response.Headers != null)
{
foreach (var kvp in response.Headers)
{
propertiesList.Add(kvp.Key, kvp.Value);
}
}
}
else
{
Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase);
return null;
}
return propertiesList;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
throw;
}
}
// Retrieve a blob's metadata.
// Return true on success, false if not found, throw exception on error.
public async Task<Dictionary<string, string>> GetBlobMetadata(string container, string blob)
{
Dictionary<string, string> metadata = new Dictionary<string, string>();
try
{
HttpRequestMessage request = CreateStreamRESTRequest("HEAD", container + "/" + blob + "?comp=metadata");
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if ((int)response.StatusCode == 200)
{
if (response.Headers != null)
{
foreach (var kvp in response.Headers)
{
if (kvp.Key.StartsWith("x-ms-meta-"))
{
metadata.Add(kvp.Key, kvp.Value);
}
}
}
}
return metadata;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
throw;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Http.Headers
{
/// <summary>
/// Strongly typed HTTP request headers.
/// </summary>
public class RequestHeaders
{
/// <summary>
/// Initializes a new instance of <see cref="RequestHeaders"/>.
/// </summary>
/// <param name="headers">The request headers.</param>
public RequestHeaders(IHeaderDictionary headers)
{
if (headers == null)
{
throw new ArgumentNullException(nameof(headers));
}
Headers = headers;
}
/// <summary>
/// Gets the backing request header dictionary.
/// </summary>
public IHeaderDictionary Headers { get; }
/// <summary>
/// Gets or sets the <c>Accept</c> header for an HTTP request.
/// </summary>
public IList<MediaTypeHeaderValue> Accept
{
get
{
return Headers.Accept.GetList<MediaTypeHeaderValue>();
}
set
{
Headers.SetList(HeaderNames.Accept, value);
}
}
/// <summary>
/// Gets or sets the <c>Accept-Charset</c> header for an HTTP request.
/// </summary>
public IList<StringWithQualityHeaderValue> AcceptCharset
{
get
{
return Headers.AcceptCharset.GetList<StringWithQualityHeaderValue>();
}
set
{
Headers.SetList(HeaderNames.AcceptCharset, value);
}
}
/// <summary>
/// Gets or sets the <c>Accept-Encoding</c> header for an HTTP request.
/// </summary>
public IList<StringWithQualityHeaderValue> AcceptEncoding
{
get
{
return Headers.AcceptEncoding.GetList<StringWithQualityHeaderValue>();
}
set
{
Headers.SetList(HeaderNames.AcceptEncoding, value);
}
}
/// <summary>
/// Gets or sets the <c>Accept-Language</c> header for an HTTP request.
/// </summary>
public IList<StringWithQualityHeaderValue> AcceptLanguage
{
get
{
return Headers.AcceptLanguage.GetList<StringWithQualityHeaderValue>();
}
set
{
Headers.SetList(HeaderNames.AcceptLanguage, value);
}
}
/// <summary>
/// Gets or sets the <c>Cache-Control</c> header for an HTTP request.
/// </summary>
public CacheControlHeaderValue? CacheControl
{
get
{
return Headers.Get<CacheControlHeaderValue>(HeaderNames.CacheControl);
}
set
{
Headers.Set(HeaderNames.CacheControl, value);
}
}
/// <summary>
/// Gets or sets the <c>Content-Disposition</c> header for an HTTP request.
/// </summary>
public ContentDispositionHeaderValue? ContentDisposition
{
get
{
return Headers.Get<ContentDispositionHeaderValue>(HeaderNames.ContentDisposition);
}
set
{
Headers.Set(HeaderNames.ContentDisposition, value);
}
}
/// <summary>
/// Gets or sets the <c>Content-Length</c> header for an HTTP request.
/// </summary>
public long? ContentLength
{
get
{
return Headers.ContentLength;
}
set
{
Headers.ContentLength = value;
}
}
/// <summary>
/// Gets or sets the <c>Content-Range</c> header for an HTTP request.
/// </summary>
public ContentRangeHeaderValue? ContentRange
{
get
{
return Headers.Get<ContentRangeHeaderValue>(HeaderNames.ContentRange);
}
set
{
Headers.Set(HeaderNames.ContentRange, value);
}
}
/// <summary>
/// Gets or sets the <c>Content-Type</c> header for an HTTP request.
/// </summary>
public MediaTypeHeaderValue? ContentType
{
get
{
return Headers.Get<MediaTypeHeaderValue>(HeaderNames.ContentType);
}
set
{
Headers.Set(HeaderNames.ContentType, value);
}
}
/// <summary>
/// Gets or sets the <c>Cookie</c> header for an HTTP request.
/// </summary>
public IList<CookieHeaderValue> Cookie
{
get
{
return Headers.Cookie.GetList<CookieHeaderValue>();
}
set
{
Headers.SetList(HeaderNames.Cookie, value);
}
}
/// <summary>
/// Gets or sets the <c>Date</c> header for an HTTP request.
/// </summary>
public DateTimeOffset? Date
{
get
{
return Headers.GetDate(HeaderNames.Date);
}
set
{
Headers.SetDate(HeaderNames.Date, value);
}
}
/// <summary>
/// Gets or sets the <c>Expires</c> header for an HTTP request.
/// </summary>
public DateTimeOffset? Expires
{
get
{
return Headers.GetDate(HeaderNames.Expires);
}
set
{
Headers.SetDate(HeaderNames.Expires, value);
}
}
/// <summary>
/// Gets or sets the <c>Host</c> header for an HTTP request.
/// </summary>
public HostString Host
{
get
{
return HostString.FromUriComponent(Headers.Host.ToString());
}
set
{
Headers.Host = value.ToUriComponent();
}
}
/// <summary>
/// Gets or sets the <c>If-Match</c> header for an HTTP request.
/// </summary>
public IList<EntityTagHeaderValue> IfMatch
{
get
{
return Headers.IfMatch.GetList<EntityTagHeaderValue>();
}
set
{
Headers.SetList(HeaderNames.IfMatch, value);
}
}
/// <summary>
/// Gets or sets the <c>If-Modified-Since</c> header for an HTTP request.
/// </summary>
public DateTimeOffset? IfModifiedSince
{
get
{
return Headers.GetDate(HeaderNames.IfModifiedSince);
}
set
{
Headers.SetDate(HeaderNames.IfModifiedSince, value);
}
}
/// <summary>
/// Gets or sets the <c>If-None-Match</c> header for an HTTP request.
/// </summary>
public IList<EntityTagHeaderValue> IfNoneMatch
{
get
{
return Headers.IfNoneMatch.GetList<EntityTagHeaderValue>();
}
set
{
Headers.SetList(HeaderNames.IfNoneMatch, value);
}
}
/// <summary>
/// Gets or sets the <c>If-Range</c> header for an HTTP request.
/// </summary>
public RangeConditionHeaderValue? IfRange
{
get
{
return Headers.Get<RangeConditionHeaderValue>(HeaderNames.IfRange);
}
set
{
Headers.Set(HeaderNames.IfRange, value);
}
}
/// <summary>
/// Gets or sets the <c>If-Unmodified-Since</c> header for an HTTP request.
/// </summary>
public DateTimeOffset? IfUnmodifiedSince
{
get
{
return Headers.GetDate(HeaderNames.IfUnmodifiedSince);
}
set
{
Headers.SetDate(HeaderNames.IfUnmodifiedSince, value);
}
}
/// <summary>
/// Gets or sets the <c>Last-Modified</c> header for an HTTP request.
/// </summary>
public DateTimeOffset? LastModified
{
get
{
return Headers.GetDate(HeaderNames.LastModified);
}
set
{
Headers.SetDate(HeaderNames.LastModified, value);
}
}
/// <summary>
/// Gets or sets the <c>Range</c> header for an HTTP request.
/// </summary>
public RangeHeaderValue? Range
{
get
{
return Headers.Get<RangeHeaderValue>(HeaderNames.Range);
}
set
{
Headers.Set(HeaderNames.Range, value);
}
}
/// <summary>
/// Gets or sets the <c>Referer</c> header for an HTTP request.
/// </summary>
public Uri? Referer
{
get
{
if (Uri.TryCreate(Headers.Referer, UriKind.RelativeOrAbsolute, out var uri))
{
return uri;
}
return null;
}
set
{
Headers.Set(HeaderNames.Referer, value == null ? null : UriHelper.Encode(value));
}
}
/// <summary>
/// Gets the value of header with <paramref name="name"/>.
/// </summary>
/// <remarks><typeparamref name="T"/> must contain a TryParse method with the signature <c>public static bool TryParse(string, out T)</c>.</remarks>
/// <typeparam name="T">The type of the header.
/// The given type must have a static TryParse method.</typeparam>
/// <param name="name">The name of the header to retrieve.</param>
/// <returns>The value of the header.</returns>
public T? Get<T>(string name)
{
return Headers.Get<T>(name);
}
/// <summary>
/// Gets the values of header with <paramref name="name"/>.
/// </summary>
/// <remarks><typeparamref name="T"/> must contain a TryParseList method with the signature <c>public static bool TryParseList(IList<string>, out IList<T>)</c>.</remarks>
/// <typeparam name="T">The type of the header.
/// The given type must have a static TryParseList method.</typeparam>
/// <param name="name">The name of the header to retrieve.</param>
/// <returns>List of values of the header.</returns>
public IList<T> GetList<T>(string name)
{
return Headers.GetList<T>(name);
}
/// <summary>
/// Sets the header value.
/// </summary>
/// <param name="name">The header name.</param>
/// <param name="value">The header value.</param>
public void Set(string name, object? value)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Headers.Set(name, value);
}
/// <summary>
/// Sets the specified header and it's values.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="name">The header name.</param>
/// <param name="values">The sequence of header values.</param>
public void SetList<T>(string name, IList<T>? values)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Headers.SetList<T>(name, values);
}
/// <summary>
/// Appends the header name and value.
/// </summary>
/// <param name="name">The header name.</param>
/// <param name="value">The header value.</param>
public void Append(string name, object value)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Headers.Append(name, value.ToString());
}
/// <summary>
/// Appends the header name and it's values.
/// </summary>
/// <param name="name">The header name.</param>
/// <param name="values">The header values.</param>
public void AppendList<T>(string name, IList<T> values)
{
Headers.AppendList<T>(name, values);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class SignHere : IEquatable<SignHere>
{
/// <summary>
/// Specifies the tool tip text for the tab.
/// </summary>
/// <value>Specifies the tool tip text for the tab.</value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// The label string associated with the tab.
/// </summary>
/// <value>The label string associated with the tab.</value>
[DataMember(Name="tabLabel", EmitDefaultValue=false)]
public string TabLabel { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="scaleValue", EmitDefaultValue=false)]
public Object ScaleValue { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="optional", EmitDefaultValue=false)]
public string Optional { get; set; }
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
/// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.
/// </summary>
/// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value>
[DataMember(Name="recipientId", EmitDefaultValue=false)]
public string RecipientId { get; set; }
/// <summary>
/// Specifies the page number on which the tab is located.
/// </summary>
/// <value>Specifies the page number on which the tab is located.</value>
[DataMember(Name="pageNumber", EmitDefaultValue=false)]
public string PageNumber { get; set; }
/// <summary>
/// This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="xPosition", EmitDefaultValue=false)]
public string XPosition { get; set; }
/// <summary>
/// This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="yPosition", EmitDefaultValue=false)]
public string YPosition { get; set; }
/// <summary>
/// Anchor text information for a radio button.
/// </summary>
/// <value>Anchor text information for a radio button.</value>
[DataMember(Name="anchorString", EmitDefaultValue=false)]
public string AnchorString { get; set; }
/// <summary>
/// Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the X axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorXOffset", EmitDefaultValue=false)]
public string AnchorXOffset { get; set; }
/// <summary>
/// Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the Y axis location of the tab, in achorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorYOffset", EmitDefaultValue=false)]
public string AnchorYOffset { get; set; }
/// <summary>
/// Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.
/// </summary>
/// <value>Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.</value>
[DataMember(Name="anchorUnits", EmitDefaultValue=false)]
public string AnchorUnits { get; set; }
/// <summary>
/// When set to **true**, this tab is ignored if anchorString is not found in the document.
/// </summary>
/// <value>When set to **true**, this tab is ignored if anchorString is not found in the document.</value>
[DataMember(Name="anchorIgnoreIfNotPresent", EmitDefaultValue=false)]
public string AnchorIgnoreIfNotPresent { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorCaseSensitive", EmitDefaultValue=false)]
public string AnchorCaseSensitive { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorMatchWholeWord", EmitDefaultValue=false)]
public string AnchorMatchWholeWord { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="anchorHorizontalAlignment", EmitDefaultValue=false)]
public string AnchorHorizontalAlignment { get; set; }
/// <summary>
/// The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].
/// </summary>
/// <value>The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].</value>
[DataMember(Name="tabId", EmitDefaultValue=false)]
public string TabId { get; set; }
/// <summary>
/// When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateLocked", EmitDefaultValue=false)]
public string TemplateLocked { get; set; }
/// <summary>
/// When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateRequired", EmitDefaultValue=false)]
public string TemplateRequired { get; set; }
/// <summary>
/// For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.
/// </summary>
/// <value>For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.</value>
[DataMember(Name="conditionalParentLabel", EmitDefaultValue=false)]
public string ConditionalParentLabel { get; set; }
/// <summary>
/// For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.
/// </summary>
/// <value>For conditional fields, this is the value of the parent tab that controls the tab's visibility.\n\nIf the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.</value>
[DataMember(Name="conditionalParentValue", EmitDefaultValue=false)]
public string ConditionalParentValue { get; set; }
/// <summary>
/// The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.
/// </summary>
/// <value>The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.</value>
[DataMember(Name="customTabId", EmitDefaultValue=false)]
public string CustomTabId { get; set; }
/// <summary>
/// Gets or Sets MergeField
/// </summary>
[DataMember(Name="mergeField", EmitDefaultValue=false)]
public MergeField MergeField { get; set; }
/// <summary>
/// Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later.
/// </summary>
/// <value>Indicates the envelope status. Valid values are:\n\n* sent - The envelope is sent to the recipients. \n* created - The envelope is saved as a draft and can be modified and sent later.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { 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 SignHere {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" TabLabel: ").Append(TabLabel).Append("\n");
sb.Append(" ScaleValue: ").Append(ScaleValue).Append("\n");
sb.Append(" Optional: ").Append(Optional).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" RecipientId: ").Append(RecipientId).Append("\n");
sb.Append(" PageNumber: ").Append(PageNumber).Append("\n");
sb.Append(" XPosition: ").Append(XPosition).Append("\n");
sb.Append(" YPosition: ").Append(YPosition).Append("\n");
sb.Append(" AnchorString: ").Append(AnchorString).Append("\n");
sb.Append(" AnchorXOffset: ").Append(AnchorXOffset).Append("\n");
sb.Append(" AnchorYOffset: ").Append(AnchorYOffset).Append("\n");
sb.Append(" AnchorUnits: ").Append(AnchorUnits).Append("\n");
sb.Append(" AnchorIgnoreIfNotPresent: ").Append(AnchorIgnoreIfNotPresent).Append("\n");
sb.Append(" AnchorCaseSensitive: ").Append(AnchorCaseSensitive).Append("\n");
sb.Append(" AnchorMatchWholeWord: ").Append(AnchorMatchWholeWord).Append("\n");
sb.Append(" AnchorHorizontalAlignment: ").Append(AnchorHorizontalAlignment).Append("\n");
sb.Append(" TabId: ").Append(TabId).Append("\n");
sb.Append(" TemplateLocked: ").Append(TemplateLocked).Append("\n");
sb.Append(" TemplateRequired: ").Append(TemplateRequired).Append("\n");
sb.Append(" ConditionalParentLabel: ").Append(ConditionalParentLabel).Append("\n");
sb.Append(" ConditionalParentValue: ").Append(ConditionalParentValue).Append("\n");
sb.Append(" CustomTabId: ").Append(CustomTabId).Append("\n");
sb.Append(" MergeField: ").Append(MergeField).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).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 SignHere);
}
/// <summary>
/// Returns true if SignHere instances are equal
/// </summary>
/// <param name="other">Instance of SignHere to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SignHere other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.TabLabel == other.TabLabel ||
this.TabLabel != null &&
this.TabLabel.Equals(other.TabLabel)
) &&
(
this.ScaleValue == other.ScaleValue ||
this.ScaleValue != null &&
this.ScaleValue.Equals(other.ScaleValue)
) &&
(
this.Optional == other.Optional ||
this.Optional != null &&
this.Optional.Equals(other.Optional)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.RecipientId == other.RecipientId ||
this.RecipientId != null &&
this.RecipientId.Equals(other.RecipientId)
) &&
(
this.PageNumber == other.PageNumber ||
this.PageNumber != null &&
this.PageNumber.Equals(other.PageNumber)
) &&
(
this.XPosition == other.XPosition ||
this.XPosition != null &&
this.XPosition.Equals(other.XPosition)
) &&
(
this.YPosition == other.YPosition ||
this.YPosition != null &&
this.YPosition.Equals(other.YPosition)
) &&
(
this.AnchorString == other.AnchorString ||
this.AnchorString != null &&
this.AnchorString.Equals(other.AnchorString)
) &&
(
this.AnchorXOffset == other.AnchorXOffset ||
this.AnchorXOffset != null &&
this.AnchorXOffset.Equals(other.AnchorXOffset)
) &&
(
this.AnchorYOffset == other.AnchorYOffset ||
this.AnchorYOffset != null &&
this.AnchorYOffset.Equals(other.AnchorYOffset)
) &&
(
this.AnchorUnits == other.AnchorUnits ||
this.AnchorUnits != null &&
this.AnchorUnits.Equals(other.AnchorUnits)
) &&
(
this.AnchorIgnoreIfNotPresent == other.AnchorIgnoreIfNotPresent ||
this.AnchorIgnoreIfNotPresent != null &&
this.AnchorIgnoreIfNotPresent.Equals(other.AnchorIgnoreIfNotPresent)
) &&
(
this.AnchorCaseSensitive == other.AnchorCaseSensitive ||
this.AnchorCaseSensitive != null &&
this.AnchorCaseSensitive.Equals(other.AnchorCaseSensitive)
) &&
(
this.AnchorMatchWholeWord == other.AnchorMatchWholeWord ||
this.AnchorMatchWholeWord != null &&
this.AnchorMatchWholeWord.Equals(other.AnchorMatchWholeWord)
) &&
(
this.AnchorHorizontalAlignment == other.AnchorHorizontalAlignment ||
this.AnchorHorizontalAlignment != null &&
this.AnchorHorizontalAlignment.Equals(other.AnchorHorizontalAlignment)
) &&
(
this.TabId == other.TabId ||
this.TabId != null &&
this.TabId.Equals(other.TabId)
) &&
(
this.TemplateLocked == other.TemplateLocked ||
this.TemplateLocked != null &&
this.TemplateLocked.Equals(other.TemplateLocked)
) &&
(
this.TemplateRequired == other.TemplateRequired ||
this.TemplateRequired != null &&
this.TemplateRequired.Equals(other.TemplateRequired)
) &&
(
this.ConditionalParentLabel == other.ConditionalParentLabel ||
this.ConditionalParentLabel != null &&
this.ConditionalParentLabel.Equals(other.ConditionalParentLabel)
) &&
(
this.ConditionalParentValue == other.ConditionalParentValue ||
this.ConditionalParentValue != null &&
this.ConditionalParentValue.Equals(other.ConditionalParentValue)
) &&
(
this.CustomTabId == other.CustomTabId ||
this.CustomTabId != null &&
this.CustomTabId.Equals(other.CustomTabId)
) &&
(
this.MergeField == other.MergeField ||
this.MergeField != null &&
this.MergeField.Equals(other.MergeField)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
);
}
/// <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.Name != null)
hash = hash * 57 + this.Name.GetHashCode();
if (this.TabLabel != null)
hash = hash * 57 + this.TabLabel.GetHashCode();
if (this.ScaleValue != null)
hash = hash * 57 + this.ScaleValue.GetHashCode();
if (this.Optional != null)
hash = hash * 57 + this.Optional.GetHashCode();
if (this.DocumentId != null)
hash = hash * 57 + this.DocumentId.GetHashCode();
if (this.RecipientId != null)
hash = hash * 57 + this.RecipientId.GetHashCode();
if (this.PageNumber != null)
hash = hash * 57 + this.PageNumber.GetHashCode();
if (this.XPosition != null)
hash = hash * 57 + this.XPosition.GetHashCode();
if (this.YPosition != null)
hash = hash * 57 + this.YPosition.GetHashCode();
if (this.AnchorString != null)
hash = hash * 57 + this.AnchorString.GetHashCode();
if (this.AnchorXOffset != null)
hash = hash * 57 + this.AnchorXOffset.GetHashCode();
if (this.AnchorYOffset != null)
hash = hash * 57 + this.AnchorYOffset.GetHashCode();
if (this.AnchorUnits != null)
hash = hash * 57 + this.AnchorUnits.GetHashCode();
if (this.AnchorIgnoreIfNotPresent != null)
hash = hash * 57 + this.AnchorIgnoreIfNotPresent.GetHashCode();
if (this.AnchorCaseSensitive != null)
hash = hash * 57 + this.AnchorCaseSensitive.GetHashCode();
if (this.AnchorMatchWholeWord != null)
hash = hash * 57 + this.AnchorMatchWholeWord.GetHashCode();
if (this.AnchorHorizontalAlignment != null)
hash = hash * 57 + this.AnchorHorizontalAlignment.GetHashCode();
if (this.TabId != null)
hash = hash * 57 + this.TabId.GetHashCode();
if (this.TemplateLocked != null)
hash = hash * 57 + this.TemplateLocked.GetHashCode();
if (this.TemplateRequired != null)
hash = hash * 57 + this.TemplateRequired.GetHashCode();
if (this.ConditionalParentLabel != null)
hash = hash * 57 + this.ConditionalParentLabel.GetHashCode();
if (this.ConditionalParentValue != null)
hash = hash * 57 + this.ConditionalParentValue.GetHashCode();
if (this.CustomTabId != null)
hash = hash * 57 + this.CustomTabId.GetHashCode();
if (this.MergeField != null)
hash = hash * 57 + this.MergeField.GetHashCode();
if (this.Status != null)
hash = hash * 57 + this.Status.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 57 + this.ErrorDetails.GetHashCode();
return hash;
}
}
}
}
| |
/*
Copyright 2018 Esri
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.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Layouts;
using ArcGIS.Desktop.Mapping;
namespace Layout_HelpExamples
{
public class Export_Examples
{
async public static void ExportLayoutToPDF()
{
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout Name"));
Layout layout = await QueuedTask.Run(() => layoutItem.GetLayout());
String filePath = null;
#region Layout_ExportPDF
//Export a layout to PDF
//Create a PDF export format
PDFFormat pdf = new PDFFormat()
{
OutputFileName = filePath,
Resolution = 300,
DoCompressVectorGraphics = true,
DoEmbedFonts = true,
HasGeoRefInfo = true,
ImageCompression = ImageCompression.Adaptive,
ImageQuality = ImageQuality.Best,
LayersAndAttributes = LayersAndAttributes.LayersAndAttributes
};
//Check to see if the path is valid and export
if (pdf.ValidateOutputFilePath())
{
layout.Export(pdf); //Export the PDF
}
#endregion Layout_ExportPDF
}
}
}
namespace Layout_HelpExamples
{
// cref: ExportBMP_Layout;ArcGIS.Desktop.Mapping.BMPFormat
#region ExportBMP_Layout
//This example demonstrates how to export a layout to BMP.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToBMPExample
{
public static Task ExportLayoutToBMPAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create BMP format with appropriate settings
BMPFormat BMP = new BMPFormat();
BMP.Resolution = 300;
BMP.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (BMP.ValidateOutputFilePath())
{
lyt.Export(BMP);
}
});
}
}
#endregion ExportBMP_Layout
}
namespace Layout_HelpExamples
{
#region ExportBMP_MapFrame
//This example demonstrates how to export an individual map frame on a layout to BMP.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToBMPExample
{
public static Task ExportMapFrameToBMPAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create BMP format with appropriate settings
BMPFormat BMP = new BMPFormat();
BMP.HasWorldFile = true;
BMP.Resolution = 300;
BMP.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
BMP.OutputFileName = Path;
if (BMP.ValidateOutputFilePath())
{
mf.Export(BMP);
}
});
}
}
#endregion ExportBMP_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportBMP_ActiveMap
//This example demonstrates how to export the active mapview to BMP.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToBMPExample
{
public static Task ExportActiveMapToBMPAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create BMP format with appropriate settings
BMPFormat BMP = new BMPFormat();
BMP.Resolution = 300;
BMP.Height = 500;
BMP.Width = 800;
BMP.HasWorldFile = true;
BMP.OutputFileName = Path;
//Export active map view
if (BMP.ValidateOutputFilePath())
{
map.Export(BMP);
}
});
}
}
#endregion ExportBMP_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportEMF_Layout;ArcGIS.Desktop.Mapping.EMFFormat
#region ExportEMF_Layout
//This example demonstrates how to export a layout to EMF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToEMFExample
{
public static Task ExportLayoutToEMFAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create EMF format with appropriate settings
EMFFormat EMF = new EMFFormat();
EMF.Resolution = 300;
EMF.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (EMF.ValidateOutputFilePath())
{
lyt.Export(EMF);
}
});
}
}
#endregion ExportEMF_Layout
}
namespace Layout_HelpExamples
{
#region ExportEMF_MapFrame
//This example demonstrates how to export an individual map frame on a layout to EMF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToEMFExample
{
public static Task ExportMapFrameToEMFAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create EMF format with appropriate settings
EMFFormat EMF = new EMFFormat();
EMF.Resolution = 300;
EMF.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
EMF.OutputFileName = Path;
if (EMF.ValidateOutputFilePath())
{
mf.Export(EMF);
}
});
}
}
#endregion ExportEMF_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportEMF_ActiveMap
//This example demonstrates how to export the active mapview to EMF.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToEMFExample
{
public static Task ExportActiveMapToEMFAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create EMF format with appropriate settings
EMFFormat EMF = new EMFFormat();
EMF.Resolution = 300;
EMF.Height = 500;
EMF.Width = 800;
EMF.OutputFileName = Path;
//Export active map view
if (EMF.ValidateOutputFilePath())
{
map.Export(EMF);
}
});
}
}
#endregion ExportEMF_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportEPS_Layout;ArcGIS.Desktop.Mapping.EPSFormat
#region ExportEPS_Layout
//This example demonstrates how to export a layout to EPS.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToEPSExample
{
public static Task ExportLayoutToEPSAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create EPS format with appropriate settings
EPSFormat EPS = new EPSFormat();
EPS.Resolution = 300;
EPS.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (EPS.ValidateOutputFilePath())
{
lyt.Export(EPS);
}
});
}
}
#endregion ExportEPS_Layout
}
namespace Layout_HelpExamples
{
#region ExportEPS_MapFrame
//This example demonstrates how to export an individual map frame on a layout to EPS.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToEPSExample
{
public static Task ExportMapFrameToEPSAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create EPS format with appropriate settings
EMFFormat EPS = new EMFFormat();
EPS.Resolution = 300;
EPS.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
EPS.OutputFileName = Path;
if (EPS.ValidateOutputFilePath())
{
mf.Export(EPS);
}
});
}
}
#endregion ExportEMF_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportEPS_ActiveMap
//This example demonstrates how to export the active mapview to EPS.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToEPSExample
{
public static Task ExportActiveMapToEPSAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create EMF format with appropriate settings
EPSFormat EPS = new EPSFormat();
EPS.Resolution = 300;
EPS.Height = 500;
EPS.Width = 800;
EPS.OutputFileName = Path;
//Export active map view
if (EPS.ValidateOutputFilePath())
{
map.Export(EPS);
}
});
}
}
#endregion ExportEPS_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportGIF_Layout;ArcGIS.Desktop.Mapping.GIFFormat
#region ExportGIF_Layout
//This example demonstrates how to export a layout to GIF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToGIFExample
{
public static Task ExportLayoutToGIFAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create GIF format with appropriate settings
GIFFormat GIF = new GIFFormat();
GIF.Resolution = 300;
GIF.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (GIF.ValidateOutputFilePath())
{
lyt.Export(GIF);
}
});
}
}
#endregion ExportGIF_Layout
}
namespace Layout_HelpExamples
{
#region ExportGIF_MapFrame
//This example demonstrates how to export an individual map frame on a layout to GIF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToGIFExample
{
public static Task ExportMapFrameToGIFAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create GIF format with appropriate settings
GIFFormat GIF = new GIFFormat();
GIF.HasWorldFile = true;
GIF.Resolution = 300;
GIF.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
GIF.OutputFileName = Path;
if (GIF.ValidateOutputFilePath())
{
mf.Export(GIF);
}
});
}
}
#endregion ExportGIF_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportGIF_ActiveMap
//This example demonstrates how to export the active mapview to GIF.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToGIFExample
{
public static Task ExportActiveMapToGIFAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create GIF format with appropriate settings
GIFFormat GIF = new GIFFormat();
GIF.Resolution = 300;
GIF.Height = 500;
GIF.Width = 800;
GIF.HasWorldFile = true;
GIF.OutputFileName = Path;
//Export active map view
if (GIF.ValidateOutputFilePath())
{
map.Export(GIF);
}
});
}
}
#endregion ExportGIF_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportJPEG_Layout;ArcGIS.Desktop.Mapping.JPEGFormat
#region ExportJPEG_Layout
//This example demonstrates how to export a layout to JPEG.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToJPEGExample
{
public static Task ExportLayoutToJPEGAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create JPEG format with appropriate settings
JPEGFormat JPEG = new JPEGFormat();
JPEG.Resolution = 300;
JPEG.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (JPEG.ValidateOutputFilePath())
{
lyt.Export(JPEG);
}
});
}
}
#endregion ExportJPEG_Layout
}
namespace Layout_HelpExamples
{
#region ExportJPEG_MapFrame
//This example demonstrates how to export an individual map frame on a layout to JPEG.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToJPEGExample
{
public static Task ExportMapFrameToJPEGAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create JPEG format with appropriate settings
JPEGFormat JPEG = new JPEGFormat();
JPEG.HasWorldFile = true;
JPEG.Resolution = 300;
JPEG.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
JPEG.OutputFileName = Path;
if (JPEG.ValidateOutputFilePath())
{
mf.Export(JPEG);
}
});
}
}
#endregion ExportJPEG_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportJPEG_ActiveMap
//This example demonstrates how to export the active mapview to JPEG.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToJPEGExample
{
public static Task ExportActiveMapToJPEGAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create JPEG format with appropriate settings
JPEGFormat JPEG = new JPEGFormat();
JPEG.Resolution = 300;
JPEG.Height = 500;
JPEG.Width = 800;
JPEG.HasWorldFile = true;
JPEG.OutputFileName = Path;
//Export active map view
if (JPEG.ValidateOutputFilePath())
{
map.Export(JPEG);
}
});
}
}
#endregion ExportJPEG_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportPDF_Layout;ArcGIS.Desktop.Mapping.PDFFormat
#region ExportPDF_Layout
//This example demonstrates how to export a layout to PDF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToPDFExample
{
public static Task ExportLayoutToPDFAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create PDF format with appropriate settings
PDFFormat PDF = new PDFFormat();
PDF.Resolution = 300;
PDF.OutputFileName = Path;
//PDF.Password = "xxx";
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (PDF.ValidateOutputFilePath())
{
lyt.Export(PDF);
}
});
}
}
#endregion ExportPDF_Layout
}
namespace Layout_HelpExamples
{
#region ExportPDF_MapFrame
//This example demonstrates how to export an individual map frame on a layout to PDF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToPDFExample
{
public static Task ExportMapFrameToPDFAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create PDF format with appropriate settings
PDFFormat PDF = new PDFFormat();
PDF.Resolution = 300;
PDF.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
PDF.OutputFileName = Path;
if (PDF.ValidateOutputFilePath())
{
mf.Export(PDF);
}
});
}
}
#endregion ExportPDF_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportPDF_ActiveMap
//This example demonstrates how to export the active mapview to PDF.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToPDFExample
{
public static Task ExportActiveMapToPDFAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create PDF format with appropriate settings
PDFFormat PDF = new PDFFormat();
PDF.Resolution = 300;
PDF.Height = 500;
PDF.Width = 800;
PDF.OutputFileName = Path;
//Export active map view
if (PDF.ValidateOutputFilePath())
{
map.Export(PDF);
}
});
}
}
#endregion ExportPDF_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportPNG_Layout;ArcGIS.Desktop.Mapping.PNGFormat
#region ExportPNG_Layout
//This example demonstrates how to export a layout to PNG.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToPNGExample
{
public static Task ExportLayoutToPNGAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create PNG format with appropriate settings
PNGFormat PNG = new PNGFormat();
PNG.Resolution = 300;
PNG.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (PNG.ValidateOutputFilePath())
{
lyt.Export(PNG);
}
});
}
}
#endregion ExportPNG_Layout
}
namespace Layout_HelpExamples
{
#region ExportPNG_MapFrame
//This example demonstrates how to export an individual map frame on a layout to PNG.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToPNGExample
{
public static Task ExportMapFrameToPNGAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create PNG format with appropriate settings
PNGFormat PNG = new PNGFormat();
PNG.Resolution = 300;
PNG.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
PNG.OutputFileName = Path;
if (PNG.ValidateOutputFilePath())
{
mf.Export(PNG);
}
});
}
}
#endregion ExportPNG_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportPNG_ActiveMap
//This example demonstrates how to export the active mapview to PNG.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToPNGExample
{
public static Task ExportActiveMapToPNGAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create PNG format with appropriate settings
PNGFormat PNG = new PNGFormat();
PNG.Resolution = 300;
PNG.Height = 500;
PNG.Width = 800;
PNG.OutputFileName = Path;
//Export active map view
if (PNG.ValidateOutputFilePath())
{
map.Export(PNG);
}
});
}
}
#endregion ExportPNG_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportSVG_Layout;ArcGIS.Desktop.Mapping.SVGFormat
#region ExportSVG_Layout
//This example demonstrates how to export a layout to SVG.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToSVGExample
{
public static Task ExportLayoutToSVGAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create SVG format with appropriate settings
SVGFormat SVG = new SVGFormat();
SVG.Resolution = 300;
SVG.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (SVG.ValidateOutputFilePath())
{
lyt.Export(SVG);
}
});
}
}
#endregion ExportSVG_Layout
}
namespace Layout_HelpExamples
{
#region ExportSVG_MapFrame
//This example demonstrates how to export an individual map frame on a layout to SVG.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToSVGExample
{
public static Task ExportMapFrameToSVGAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create SVG format with appropriate settings
SVGFormat SVG = new SVGFormat();
SVG.Resolution = 300;
SVG.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
SVG.OutputFileName = Path;
if (SVG.ValidateOutputFilePath())
{
mf.Export(SVG);
}
});
}
}
#endregion ExportSVG_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportSVG_ActiveMap
//This example demonstrates how to export the active mapview to SVG.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToSVGExample
{
public static Task ExportActiveMapToSVGAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create SVG format with appropriate settings
SVGFormat SVG = new SVGFormat();
SVG.Resolution = 300;
SVG.Height = 500;
SVG.Width = 800;
SVG.OutputFileName = Path;
//Export active map view
if (SVG.ValidateOutputFilePath())
{
map.Export(SVG);
}
});
}
}
#endregion ExportSVG_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportTGA_Layout;ArcGIS.Desktop.Mapping.TGAFormat
#region ExportTGA_Layout
//This example demonstrates how to export a layout to TGA.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToTGAExample
{
public static Task ExportLayoutToTGAAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create TGA format with appropriate settings
TGAFormat TGA = new TGAFormat();
TGA.Resolution = 300;
TGA.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (TGA.ValidateOutputFilePath())
{
lyt.Export(TGA);
}
});
}
}
#endregion ExportTGA_Layout
}
namespace Layout_HelpExamples
{
#region ExportTGA_MapFrame
//This example demonstrates how to export an individual map frame on a layout to TGA.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToTGAExample
{
public static Task ExportMapFrameToTGAAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create TGA format with appropriate settings
TGAFormat TGA = new TGAFormat();
TGA.Resolution = 300;
TGA.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
TGA.OutputFileName = Path;
if (TGA.ValidateOutputFilePath())
{
mf.Export(TGA);
}
});
}
}
#endregion ExportTGA_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportTGA_ActiveMap
//This example demonstrates how to export the active mapview to TGA.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToTGAExample
{
public static Task ExportActiveMapToTGAAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create TGA format with appropriate settings
TGAFormat TGA = new TGAFormat();
TGA.Resolution = 300;
TGA.Height = 500;
TGA.Width = 800;
TGA.OutputFileName = Path;
//Export active map view
if (TGA.ValidateOutputFilePath())
{
map.Export(TGA);
}
});
}
}
#endregion ExportTGA_ActiveMap
}
namespace Layout_HelpExamples
{
// cref: ExportTIFF_Layout;ArcGIS.Desktop.Mapping.TIFFFormat
#region ExportTIFF_Layout
//This example demonstrates how to export a layout to TIFF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportLayoutToTIFFExample
{
public static Task ExportLayoutToTIFFAsync(string LayoutName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create TIFF format with appropriate settings
TIFFFormat TIFF = new TIFFFormat();
TIFF.Resolution = 300;
TIFF.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export Layout
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
if (TIFF.ValidateOutputFilePath())
{
lyt.Export(TIFF);
}
});
}
}
#endregion ExportTIFF_Layout
}
namespace Layout_HelpExamples
{
#region ExportTIFF_MapFrame
//This example demonstrates how to export an individual map frame on a layout to TIFF.
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout classes
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //Export formats
public class ExportMapFrameToTIFFExample
{
public static Task ExportMapFrameToTIFFAsync(string LayoutName, string MFName, string Path)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult<Layout>(null);
//Create TIFF format with appropriate settings
TIFFFormat TIFF = new TIFFFormat();
TIFF.Resolution = 300;
TIFF.OutputFileName = Path;
return QueuedTask.Run(() =>
{
//Export MapFrame
Layout lyt = layoutItem.GetLayout(); //Loads and returns the layout associated with a LayoutItem
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
TIFF.OutputFileName = Path;
if (TIFF.ValidateOutputFilePath())
{
mf.Export(TIFF);
}
});
}
}
#endregion ExportTIFF_MapFrame
}
namespace Layout_HelpExamples
{
#region ExportTIFF_ActiveMap
//This example demonstrates how to export the active mapview to TIFF.
//Added references
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Desktop.Mapping; //MapView and Export formats
public class ExportActiveMapToTIFFExample
{
public static Task ExportActiveMapToTIFFAsync(string Path)
{
return QueuedTask.Run(() =>
{
//Reference the active map view
MapView map = MapView.Active;
//Create TIFF format with appropriate settings
TIFFFormat TIFF = new TIFFFormat();
TIFF.Resolution = 300;
TIFF.Height = 500;
TIFF.Width = 800;
TIFF.OutputFileName = Path;
//Export active map view
if (TIFF.ValidateOutputFilePath())
{
map.Export(TIFF);
}
});
}
}
#endregion ExportTIFF_ActiveMap
}
namespace Layout_HelpExamples
{
internal class ExportCodeSamples_button1 : Button //Export to BMP
{
async protected override void OnClick()
{
await ExportLayoutToBMPExample.ExportLayoutToBMPAsync("Layout Name", @"C:\Temp\BMP_Layout.bmp");
await ExportMapFrameToBMPExample.ExportMapFrameToBMPAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\BMP_MapFrame.bmp");
await ExportActiveMapToBMPExample.ExportActiveMapToBMPAsync(@"C:\Temp\BMP_ActiveMap.bmp");
}
}
internal class ExportCodeSamples_button2 : Button //Export to EMF
{
async protected override void OnClick()
{
await ExportLayoutToEMFExample.ExportLayoutToEMFAsync("Layout Name", @"C:\Temp\EMF_Layout.emf");
await ExportMapFrameToEMFExample.ExportMapFrameToEMFAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\EMF_MapFrame.emf");
await ExportActiveMapToEMFExample.ExportActiveMapToEMFAsync(@"C:\Temp\EMF_ActiveMap.emf");
}
}
internal class ExportCodeSamples_button3 : Button //Export to EPS
{
async protected override void OnClick()
{
await ExportLayoutToEPSExample.ExportLayoutToEPSAsync("Layout Name", @"C:\Temp\EPS_Layout.eps");
await ExportMapFrameToEPSExample.ExportMapFrameToEPSAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\EPS_MapFrame.eps");
await ExportActiveMapToEPSExample.ExportActiveMapToEPSAsync(@"C:\Temp\EPS_ActiveMap.eps");
}
}
internal class ExportCodeSamples_button4 : Button //Export to GIF
{
async protected override void OnClick()
{
await ExportLayoutToGIFExample.ExportLayoutToGIFAsync("Layout Name", @"C:\Temp\GIF_Layout.gif");
await ExportMapFrameToGIFExample.ExportMapFrameToGIFAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\GIF_MapFrame.gif");
await ExportActiveMapToGIFExample.ExportActiveMapToGIFAsync(@"C:\Temp\GIF_ActiveMap.gif");
}
}
internal class ExportCodeSamples_button5 : Button //Export to JPEG
{
async protected override void OnClick()
{
await ExportLayoutToJPEGExample.ExportLayoutToJPEGAsync("Layout Name", @"C:\Temp\JPEG_Layout.jpg");
await ExportMapFrameToJPEGExample.ExportMapFrameToJPEGAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\JPEG_MapFrame.jpg");
await ExportActiveMapToJPEGExample.ExportActiveMapToJPEGAsync(@"C:\Temp\JPEG_ActiveMap.jpg");
}
}
internal class ExportCodeSamples_button6 : Button //Export to PDF
{
async protected override void OnClick()
{
await ExportLayoutToPDFExample.ExportLayoutToPDFAsync("Layout Name", @"C:\Temp\PDF_Layout.pdf");
await ExportMapFrameToPDFExample.ExportMapFrameToPDFAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\PDF_MapFrame.pdf");
await ExportActiveMapToPDFExample.ExportActiveMapToPDFAsync(@"C:\Temp\PDF_ActiveMap.pdf");
}
}
internal class ExportCodeSamples_button7 : Button //Export to PNG
{
async protected override void OnClick()
{
await ExportLayoutToPNGExample.ExportLayoutToPNGAsync("Layout Name", @"C:\Temp\PNG_Layout.png");
await ExportMapFrameToPNGExample.ExportMapFrameToPNGAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\PNG_MapFrame.png");
await ExportActiveMapToPNGExample.ExportActiveMapToPNGAsync(@"C:\Temp\PNG_ActiveMap.png");
}
}
internal class ExportCodeSamples_button8 : Button //Export to SVG
{
async protected override void OnClick()
{
await ExportLayoutToSVGExample.ExportLayoutToSVGAsync("Layout Name", @"C:\Temp\SVG_Layout.svg");
await ExportMapFrameToSVGExample.ExportMapFrameToSVGAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\SVG_MapFrame.svg");
await ExportActiveMapToSVGExample.ExportActiveMapToSVGAsync(@"C:\Temp\SVG_ActiveMap.svg");
}
}
internal class ExportCodeSamples_button9 : Button //Export to TGA
{
async protected override void OnClick()
{
await ExportLayoutToTGAExample.ExportLayoutToTGAAsync("Layout Name", @"C:\Temp\TGA_Layout.tga");
await ExportMapFrameToTGAExample.ExportMapFrameToTGAAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\TGA_MapFrame.tga");
await ExportActiveMapToTGAExample.ExportActiveMapToTGAAsync(@"C:\Temp\TGA_ActiveMap.tga");
}
}
internal class ExportCodeSamples_button10 : Button //Export to TIFF
{
async protected override void OnClick()
{
await ExportLayoutToTIFFExample.ExportLayoutToTIFFAsync("Layout Name", @"C:\Temp\TIFF_Layout.tif");
await ExportMapFrameToTIFFExample.ExportMapFrameToTIFFAsync("Layout Name", "Map1 Map Frame", @"C:\Temp\TIFF_MapFrame.tif");
await ExportActiveMapToTIFFExample.ExportActiveMapToTIFFAsync(@"C:\Temp\TIFF_ActiveMap.tif");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlQualifiedName.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml {
using System.Collections;
using System.Diagnostics;
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
#if !SILVERLIGHT
[Serializable]
#endif
public class XmlQualifiedName {
string name;
string ns;
#if !SILVERLIGHT
[NonSerialized]
#endif
Int32 hash;
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Empty"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static readonly XmlQualifiedName Empty = new XmlQualifiedName(string.Empty);
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.XmlQualifiedName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlQualifiedName() : this(string.Empty, string.Empty) {}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.XmlQualifiedName1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlQualifiedName(string name) : this(name, string.Empty) {}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.XmlQualifiedName2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlQualifiedName(string name, string ns) {
this.ns = ns == null ? string.Empty : ns;
this.name = name == null ? string.Empty : name;
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Namespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Namespace {
get { return ns; }
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Name"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Name {
get { return name; }
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.GetHashCode"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode() {
if(hash == 0) {
hash = Name.GetHashCode() /*+ Namespace.GetHashCode()*/; // for perf reasons we are not taking ns's hashcode.
}
return hash;
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.IsEmpty"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool IsEmpty {
get { return Name.Length == 0 && Namespace.Length == 0; }
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.ToString"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string ToString() {
return Namespace.Length == 0 ? Name : string.Concat(Namespace, ":" , Name);
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.Equals"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(object other) {
XmlQualifiedName qname;
if ((object) this == other) {
return true;
}
qname = other as XmlQualifiedName;
if (qname != null) {
return (Name == qname.Name && Namespace == qname.Namespace);
}
return false;
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.operator=="]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static bool operator ==(XmlQualifiedName a, XmlQualifiedName b) {
if ((object) a == (object) b)
return true;
if ((object) a == null || (object) b == null)
return false;
return (a.Name == b.Name && a.Namespace == b.Namespace);
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.operator!="]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static bool operator !=(XmlQualifiedName a, XmlQualifiedName b) {
return !(a == b);
}
/// <include file='doc\XmlQualifiedName.uex' path='docs/doc[@for="XmlQualifiedName.ToString1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string ToString(string name, string ns) {
return ns == null || ns.Length == 0 ? name : ns + ":" + name;
}
#if !SILVERLIGHT // These methods are not used in Silverlight
// --------- Some useful internal stuff -----------------
internal void Init(string name, string ns) {
Debug.Assert(name != null && ns != null);
this.name = name;
this.ns = ns;
this.hash = 0;
}
internal void SetNamespace(string ns) {
Debug.Assert(ns != null);
this.ns = ns; //Not changing hash since ns is not used to compute hashcode
}
internal void Verify() {
XmlConvert.VerifyNCName(name);
if (ns.Length != 0) {
XmlConvert.ToUri(ns);
}
}
internal void Atomize(XmlNameTable nameTable) {
Debug.Assert(name != null);
name = nameTable.Add(name);
ns = nameTable.Add(ns);
}
internal static XmlQualifiedName Parse(string s, IXmlNamespaceResolver nsmgr, out string prefix) {
string localName;
ValidateNames.ParseQNameThrow(s, out prefix, out localName);
string uri = nsmgr.LookupNamespace(prefix);
if (uri == null) {
if (prefix.Length != 0) {
throw new XmlException(Res.Xml_UnknownNs, prefix);
}
else { //Re-map namespace of empty prefix to string.Empty when there is no default namespace declared
uri = string.Empty;
}
}
return new XmlQualifiedName(localName, uri);
}
internal XmlQualifiedName Clone() {
return (XmlQualifiedName)MemberwiseClone();
}
internal static int Compare(XmlQualifiedName a, XmlQualifiedName b) {
if (null == a) {
return (null == b) ? 0 : -1;
}
if (null == b) {
return 1;
}
int i = String.CompareOrdinal(a.Namespace, b.Namespace);
if (i == 0) {
i = String.CompareOrdinal(a.Name, b.Name);
}
return i;
}
#endif
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using Cassandra.IntegrationTests.TestClusterManagement;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestDataTypes;
using Cassandra.Tests;
namespace Cassandra.IntegrationTests.Core
{
[Category(TestCategory.Short), Category(TestCategory.RealCluster), Category(TestCategory.ServerApi)]
public class UdtMappingsTests : SharedClusterTest
{
const string CqlTable1 = "CREATE TABLE users (id int PRIMARY KEY, main_phone frozen<phone>)";
const string CqlTable2 = "CREATE TABLE users_contacts (id int PRIMARY KEY, contacts list<frozen<contact>>)";
const string CqlTable3 = "CREATE TABLE table_udt_collections (id int PRIMARY KEY, nullable_id int, udt frozen<udt_collections>, udt_list list<frozen<udt_collections>>)";
public override void OneTimeSetUp()
{
if (TestClusterManager.CheckCassandraVersion(false, Version.Parse("2.1.0"), Comparison.LessThan))
Assert.Ignore("Requires Cassandra version >= 2.1");
base.OneTimeSetUp();
Session.Execute(Phone.CreateUdtCql);
Session.Execute(Contact.CreateUdtCql);
Session.Execute(UdtWithCollections.CreateUdtCql);
Session.Execute(UdtMappingsTests.CqlTable1);
Session.Execute(UdtMappingsTests.CqlTable2);
Session.Execute(UdtMappingsTests.CqlTable3);
}
[Test]
public void MappingSingleExplicitTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
.Map(v => v.VerifiedAt, "verified_at")
.Map(v => v.PhoneType, "phone_type")
);
var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(100000);
localSession.Execute($"INSERT INTO users (id, main_phone) values (1, {{alias: 'home phone', number: '123', country_code: 34, verified_at: '100000', phone_type: 'Home'}})");
var rs = localSession.Execute("SELECT * FROM users WHERE id = 1");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("home phone", value.Alias);
Assert.AreEqual("123", value.Number);
Assert.AreEqual(34, value.CountryCode);
Assert.AreEqual(date, value.VerifiedAt);
Assert.AreEqual(PhoneType.Home, value.PhoneType);
}
[Test]
public async Task MappingSingleExplicitTestAsync()
{
var localSession = GetNewTemporarySession(KeyspaceName);
await localSession.UserDefinedTypes.DefineAsync(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
).ConfigureAwait(false);
localSession.Execute("INSERT INTO users (id, main_phone) values (1, {alias: 'home phone', number: '123', country_code: 34})");
var rs = localSession.Execute("SELECT * FROM users WHERE id = 1");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("home phone", value.Alias);
Assert.AreEqual("123", value.Number);
Assert.AreEqual(34, value.CountryCode);
}
[Test]
public async Task MappingDifferentKeyspaceSingleExplicitAsync_AsParameter()
{
const string cqlType1 = "CREATE TYPE phone2 (alias2 text, number2 text, country_code2 int, verified_at timestamp, phone_type text)";
const string cqlTable1 = "CREATE TABLE users2 (id int PRIMARY KEY, main_phone frozen<phone2>)";
var cluster = GetNewTemporaryCluster();
var newKeyspace = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant();
var session = cluster.Connect();
session.CreateKeyspaceIfNotExists(newKeyspace);
session.ChangeKeyspace(newKeyspace);
session.Execute(cqlType1);
session.Execute(cqlTable1);
await session.UserDefinedTypes.DefineAsync(
UdtMap.For<Phone>("phone", KeyspaceName)
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number"),
UdtMap.For<Phone2>("phone2")
.Map(v => v.Alias, "alias2")
.Map(v => v.CountryCode, "country_code2")
.Map(v => v.Number, "number2")
).ConfigureAwait(false);
var phone = new Phone
{
Alias = "home phone",
Number = "85 988888888",
CountryCode = 55
};
var phone2 = new Phone2
{
Alias = "home phone2",
Number = "85 988888811",
CountryCode = 66
};
session.Execute(new SimpleStatement($"INSERT INTO {KeyspaceName}.users (id, main_phone) values (1, ?)", phone));
var rs = session.Execute($"SELECT * FROM {KeyspaceName}.users WHERE id = 1");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
session.Execute(new SimpleStatement("INSERT INTO users2 (id, main_phone) values (1, ?)", phone2));
rs = session.Execute("SELECT * FROM users2 WHERE id = 1");
row = rs.First();
var value2 = row.GetValue<Phone2>("main_phone");
Assert.AreEqual(phone, value);
Assert.AreEqual(phone2, value2);
}
[Test]
public void MappingDifferentKeyspaceWithoutSpecifyingIt()
{
const string cqlType1 = "CREATE TYPE phone2 (alias2 text, number2 text, country_code2 int, verified_at timestamp, phone_type text)";
const string cqlTable1 = "CREATE TABLE users2 (id int PRIMARY KEY, main_phone frozen<phone2>)";
var cluster = GetNewTemporaryCluster();
var newKeyspace = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant();
var session = cluster.Connect();
session.CreateKeyspaceIfNotExists(newKeyspace);
session.ChangeKeyspace(newKeyspace);
session.Execute(cqlType1);
session.Execute(cqlTable1);
Assert.ThrowsAsync<InvalidTypeException>(() => session.UserDefinedTypes.DefineAsync(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number"),
UdtMap.For<Phone2>("phone2")
.Map(v => v.Alias, "alias2")
.Map(v => v.CountryCode, "country_code2")
.Map(v => v.Number, "number2")
));
}
[Test]
public async Task MappingSingleExplicitAsync_AsParameter()
{
var localSession = GetNewTemporarySession(KeyspaceName);
await localSession.UserDefinedTypes.DefineAsync(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
).ConfigureAwait(false);
var phone = new Phone
{
Alias = "home phone",
Number = "85 988888888",
CountryCode = 55
};
localSession.Execute(new SimpleStatement("INSERT INTO users (id, main_phone) values (1, ?)", phone));
var rs = localSession.Execute("SELECT * FROM users WHERE id = 1");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.AreEqual(phone, value);
}
[Test]
public void MappingSingleExplicitNullsTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
);
//Some fields are null
localSession.Execute("INSERT INTO users (id, main_phone) values (1, {alias: 'empty phone'})");
var row = localSession.Execute("SELECT * FROM users WHERE id = 1").First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("empty phone", value.Alias);
//Default
Assert.IsNull(value.Number);
//Default
Assert.AreEqual(0, value.CountryCode);
//column value is null
localSession.Execute("INSERT INTO users (id, main_phone) values (2, null)");
row = localSession.Execute("SELECT * FROM users WHERE id = 2").First();
Assert.IsNull(row.GetValue<Phone>("main_phone"));
//first values are null
localSession.Execute("INSERT INTO users (id, main_phone) values (3, {country_code: 34})");
row = localSession.Execute("SELECT * FROM users WHERE id = 3").First();
Assert.IsNotNull(row.GetValue<Phone>("main_phone"));
Assert.AreEqual(34, row.GetValue<Phone>("main_phone").CountryCode);
Assert.IsNull(row.GetValue<Phone>("main_phone").Alias);
Assert.IsNull(row.GetValue<Phone>("main_phone").Number);
}
[Test]
public void MappingSingleImplicitTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>()
);
localSession.Execute("INSERT INTO users (id, main_phone) values (1, {alias: 'home phone', number: '123', country_code: 34})");
var rs = localSession.Execute("SELECT * FROM users WHERE id = 1");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("home phone", value.Alias);
Assert.AreEqual("123", value.Number);
//The property and the field names don't match
Assert.AreEqual(0, value.CountryCode);
}
[Test]
public void MappingNestedTypeTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>(),
UdtMap.For<Contact>()
.Map(c => c.FirstName, "first_name")
.Map(c => c.LastName, "last_name")
.Map(c => c.Birth, "birth_date")
.Map(c => c.NullableLong, "nullable_long")
);
var insertedContacts = new List<Contact>
{
new Contact
{
FirstName = "Jules", LastName = "Winnfield",
Birth = new DateTimeOffset(1950, 2, 3, 4, 5, 0, 0, TimeSpan.Zero),
NullableLong = null,
Phones = new HashSet<Phone>{ new Phone { Alias = "home", Number = "123456" }}
},
new Contact
{
FirstName = "Mia", LastName = "Wallace",
Birth = null,
NullableLong = 2,
Phones = new HashSet<Phone>
{
new Phone { Alias = "mobile", Number = "789" },
new Phone { Alias = "office", Number = "123" }
}
}
};
localSession.Execute(new SimpleStatement("INSERT INTO users_contacts (id, contacts) values (?, ?)", 1, insertedContacts));
var rs = localSession.Execute("SELECT * FROM users_contacts WHERE id = 1");
var row = rs.First();
var contacts = row.GetValue<List<Contact>>("contacts");
Assert.NotNull(contacts);
Assert.AreEqual(2, contacts.Count);
Assert.AreEqual(insertedContacts[0], contacts[0]);
Assert.AreEqual(insertedContacts[1], contacts[1]);
}
[Test]
public void MappingCaseSensitiveTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
//Cassandra identifiers are lowercased by default
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.SetIgnoreCase(false)
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
);
localSession.Execute("INSERT INTO users (id, main_phone) values (101, {alias: 'home phone', number: '123', country_code: 34})");
var rs = localSession.Execute("SELECT * FROM users WHERE id = 101");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("home phone", value.Alias);
Assert.AreEqual("123", value.Number);
Assert.AreEqual(34, value.CountryCode);
Assert.Throws<InvalidTypeException>(() => localSession.UserDefinedTypes.Define(
//The name should be forced to be case sensitive
UdtMap.For<Phone>("PhoNe")
.SetIgnoreCase(false)));
Assert.Throws<InvalidTypeException>(() => localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.SetIgnoreCase(false)
//the field is called 'alias' it should fail
.Map(v => v.Alias, "Alias")
));
}
[Test]
public void MappingNotExistingFieldsTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
Assert.Throws<InvalidTypeException>(() => localSession.UserDefinedTypes.Define(
//there is no field named like this
UdtMap.For<Phone>("phone").Map(v => v.Number, "Alias_X_WTF")
));
}
[Test]
public void MappingEncodingSingleTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
);
const string insertQuery = "INSERT INTO users (id, main_phone) values (?, ?)";
//All of the fields null
var id = 201;
var phone = new Phone();
localSession.Execute(new SimpleStatement(insertQuery, id, phone));
var rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id));
Assert.AreEqual(phone, rs.First().GetValue<Phone>("main_phone"));
//Some fields null and others with value
id = 202;
phone = new Phone() {Alias = "Home phone"};
localSession.Execute(new SimpleStatement(insertQuery, id, phone));
rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id));
Assert.AreEqual(phone, rs.First().GetValue<Phone>("main_phone"));
//All fields filled in
id = 203;
phone = new Phone() { Alias = "Mobile phone", CountryCode = 54, Number = "1234567"};
localSession.Execute(new SimpleStatement(insertQuery, id, phone));
rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id));
Assert.AreEqual(phone, rs.First().GetValue<Phone>("main_phone"));
}
[Test]
public void MappingEncodingNestedTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>(),
UdtMap.For<Contact>()
.Map(c => c.FirstName, "first_name")
.Map(c => c.LastName, "last_name")
.Map(c => c.Birth, "birth_date")
);
//All of the fields null
var id = 301;
var contacts = new List<Contact>
{
new Contact
{
FirstName = "Vincent",
LastName = "Vega",
Phones = new HashSet<Phone>
{
new Phone {Alias = "Wat", Number = "0000000000121220000"},
new Phone {Alias = "Office", Number = "123"}
}
}
};
var insert = new SimpleStatement("INSERT INTO users_contacts (id, contacts) values (?, ?)", id, contacts);
localSession.Execute(insert);
var rs = localSession.Execute(new SimpleStatement("SELECT * FROM users_contacts WHERE id = ?", id));
Assert.AreEqual(contacts, rs.First().GetValue<List<Contact>>("contacts"));
}
/// <summary>
/// Checks that if no mapping defined, the driver gets out of the way.
/// </summary>
[Test]
public void NoMappingDefinedTest()
{
const string cqlType = "CREATE TYPE temp_udt (text_sample text, date_sample timestamp)";
const string cqlTable = "CREATE TABLE temp_table (id int PRIMARY KEY, sample_udt frozen<temp_udt>, sample_udt_list list<frozen<temp_udt>>)";
const string cqlInsert = "INSERT INTO temp_table (id, sample_udt, sample_udt_list) VALUES (1, {text_sample: 'one', date_sample: 1}, [{text_sample: 'first'}])";
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.Execute(cqlType);
localSession.Execute(cqlTable);
localSession.Execute(cqlInsert);
var row = localSession.Execute("SELECT * from temp_table").First();
Assert.IsNotNull(row.GetValue<object>("sample_udt"));
Assert.IsInstanceOf<byte[]>(row.GetValue<object>("sample_udt"));
Assert.IsNotNull(row.GetValue<object>("sample_udt_list"));
Assert.IsInstanceOf<IEnumerable<byte[]>>(row.GetValue<object>("sample_udt_list"));
row = localSession.Execute("SELECT id, sample_udt.text_sample from temp_table").First();
Assert.AreEqual("one", row.GetValue<string>("sample_udt.text_sample"));
//Trying to encode an unmapped type should throw
var statement = new SimpleStatement("INSERT INTO temp_table (id, sample_udt) VALUES (?, ?)", 2, new DummyClass());
Assert.Throws<InvalidTypeException>(() => localSession.Execute(statement));
}
[Test]
public void MappingGetChildClassTest()
{
var localSession = GetNewTemporarySession(KeyspaceName);
var tableName = TestUtils.GetUniqueTableName().ToLowerInvariant();
localSession.Execute($"CREATE TABLE {tableName} (id uuid PRIMARY KEY, main_phone frozen<phone>, phones list<frozen<phone>>)");
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone2>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
.Map(v => v.VerifiedAt, "verified_at")
.Map(v => v.PhoneType, "phone_type"));
var id = Guid.NewGuid();
var date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(100000);
var phoneCql = "{alias: 'home phone', number: '123', country_code: 34, verified_at: '100000', phone_type: 'Home'}";
localSession.Execute($"INSERT INTO {tableName} (id, phones, main_phone) values ({id}, [{phoneCql}], {phoneCql})");
var rs = localSession.Execute(new SimpleStatement($"SELECT * FROM {tableName} WHERE id = ?", id));
var row = rs.First();
void AssertAreEqualPhone(Phone v)
{
Assert.AreEqual("home phone", v.Alias);
Assert.AreEqual("123", v.Number);
Assert.AreEqual(34, v.CountryCode);
Assert.AreEqual(date, v.VerifiedAt);
Assert.AreEqual(PhoneType.Home, v.PhoneType);
}
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
AssertAreEqualPhone(value);
var valueChild = row.GetValue<Phone2>("main_phone");
Assert.NotNull(valueChild);
AssertAreEqualPhone(valueChild);
var valueList = row.GetValue<IEnumerable<Phone>>("phones");
var valueInsideList = valueList.Single();
Assert.NotNull(valueInsideList);
AssertAreEqualPhone(valueInsideList);
var valueListChild = row.GetValue<IEnumerable<Phone2>>("phones");
var valueInsideListChild = valueListChild.Single();
Assert.NotNull(valueInsideListChild);
AssertAreEqualPhone(value);
}
[Test]
public void Should_ExecuteSelectsAndInserts_When_UdtWithCollections()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(UdtMap.For<UdtWithCollections>("udt_collections"));
var udtList = new List<UdtWithCollections>
{
// nulls
new UdtWithCollections
{
Id = 1
},
// collections with elements
new UdtWithCollections
{
Id = 2,
NullableId = 4,
IntEnumerable = new [] { 1, 10 },
IntEnumerableSet = new [] { 2, 20 },
IntIList = new List<int> { 3, 30 },
IntList = new List<int> { 4, 40 },
IntReadOnlyList = new List<int> { 5, 50 },
NullableIntEnumerable = new int?[] { 6, 60 },
NullableIntList = new List<int?> { 7, 70 }
},
// empty collections
new UdtWithCollections
{
Id = 3,
NullableId = 5,
IntEnumerable = new int[0],
IntEnumerableSet = new int[0],
IntIList = new List<int>(),
IntList = new List<int>(),
IntReadOnlyList = new List<int>(),
NullableIntEnumerable = new int?[0],
NullableIntList = new List<int?>()
}
};
var insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list, nullable_id) values (?, ?, ?, ?)", 1, udtList[0], udtList, 100);
localSession.Execute(insert);
insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 2, udtList[1], udtList);
localSession.Execute(insert);
insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 3, udtList[2], udtList);
localSession.Execute(insert);
insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 4, null, null);
localSession.Execute(insert);
var rs = localSession.Execute(new SimpleStatement("SELECT * FROM table_udt_collections WHERE id = ?", 1)).ToList();
CollectionAssert.AreEqual(udtList, rs.Single().GetValue<List<UdtWithCollections>>("udt_list"));
Assert.AreEqual(udtList[0], rs.Single().GetValue<UdtWithCollections>("udt"));
Assert.AreEqual(100, rs.Single().GetValue<int?>("nullable_id"));
var ps = localSession.Prepare("SELECT * FROM table_udt_collections WHERE id = ?");
rs = localSession.Execute(ps.Bind(2)).ToList();
CollectionAssert.AreEqual(udtList, rs.Single().GetValue<List<UdtWithCollections>>("udt_list"));
Assert.AreEqual(udtList[1], rs.Single().GetValue<UdtWithCollections>("udt"));
Assert.IsNull(rs.Single().GetValue<int?>("nullable_id"));
rs = localSession.Execute(ps.Bind(3)).ToList();
CollectionAssert.AreEqual(udtList, rs.Single().GetValue<List<UdtWithCollections>>("udt_list"));
Assert.AreEqual(udtList[2], rs.Single().GetValue<UdtWithCollections>("udt"));
rs = localSession.Execute(ps.Bind(4)).ToList();
Assert.IsNull(rs.Single().GetValue<List<UdtWithCollections>>("udt_list"));
Assert.IsNull(rs.Single().GetValue<UdtWithCollections>("udt"));
}
[Test]
public void Should_ThrowException_When_UdtWithCollectionsWithNullValues()
{
var localSession = GetNewTemporarySession(KeyspaceName);
localSession.UserDefinedTypes.Define(UdtMap.For<UdtWithCollections>("udt_collections"));
var udtList = new List<UdtWithCollections>
{
// collections with null elements
new UdtWithCollections
{
Id = 1111,
NullableId = 4444,
NullableIntEnumerable = new int?[] { 6, null },
NullableIntList = new List<int?> { 7, null }
},
};
var insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list, nullable_id) values (?, ?, ?, ?)", 1111, null, udtList, 1000);
Assert.Throws<InvalidCastException>(() => localSession.Execute(insert));
insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 2222, udtList[0], null);
Assert.Throws<InvalidCastException>(() => localSession.Execute(insert));
insert = new SimpleStatement("INSERT INTO table_udt_collections (id, udt, udt_list) values (?, ?, ?)", 3333, null, new List<UdtWithCollections> {null});
Assert.Throws<ArgumentNullException>(() => localSession.Execute(insert));
}
[Test, TestCassandraVersion(3, 0, Comparison.LessThan)]
public void MappingOnLowerProtocolVersionTest()
{
using (var cluster = ClusterBuilder()
.AddContactPoint(TestCluster.InitialContactPoint)
.WithMaxProtocolVersion(ProtocolVersion.V2)
.Build())
{
var localSession = cluster.Connect(KeyspaceName);
Assert.Throws<NotSupportedException>(() => localSession.UserDefinedTypes.Define(UdtMap.For<Phone>()));
}
}
private class DummyClass
{
}
}
}
| |
namespace MichaelJBaird.Themes.JQMobile.Controls
{
#region using
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core.Web.Extensions;
#endregion
/// <summary>
/// The comment view.
/// </summary>
public partial class CommentView : UserControl, ICallbackEventHandler
{
#region Constants and Fields
/// <summary>
/// The callback.
/// </summary>
private string callback;
/// <summary>
/// The nesting supported.
/// </summary>
private bool? nestingSupported;
/// <summary>
/// Initializes a new instance of the <see cref = "CommentView" /> class.
/// </summary>
public CommentView()
{
this.NameInputId = string.Empty;
this.DefaultName = string.Empty;
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether NestingSupported.
/// </summary>
public bool NestingSupported
{
get
{
if (!this.nestingSupported.HasValue)
{
if (!BlogSettings.Instance.IsCommentNestingEnabled)
{
this.nestingSupported = false;
}
else
{
var path = string.Format(
"{0}themes/{1}/CommentView.ascx", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.GetThemeWithAdjustments(null));
// test comment control for nesting placeholder (for backwards compatibility with older themes)
var commentTester = (CommentViewBase)this.LoadControl(path);
var subComments = commentTester.FindControl("phSubComments") as PlaceHolder;
this.nestingSupported = subComments != null;
}
}
return this.nestingSupported.Value;
}
}
/// <summary>
/// Gets or sets the post from which the comments are parsed.
/// </summary>
public Post Post { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [any captcha enabled].
/// </summary>
/// <value><c>true</c> if [any captcha enabled]; otherwise, <c>false</c>.</value>
protected bool AnyCaptchaEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [any captcha necessary].
/// </summary>
/// <value><c>true</c> if [any captcha necessary]; otherwise, <c>false</c>.</value>
protected bool AnyCaptchaNecessary { get; set; }
/// <summary>
/// Gets or sets the comment counter.
/// </summary>
/// <value>The comment counter.</value>
protected int CommentCounter { get; set; }
/// <summary>
/// Gets or sets the default name.
/// </summary>
/// <value>The default name.</value>
protected string DefaultName { get; set; }
/// <summary>
/// Gets or sets the name input id.
/// </summary>
/// <value>The name input id.</value>
protected string NameInputId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [re captcha enabled].
/// </summary>
/// <value><c>true</c> if [re captcha enabled]; otherwise, <c>false</c>.</value>
protected bool ReCaptchaEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [simple captcha enabled].
/// </summary>
/// <value>
/// <c>true</c> if [simple captcha enabled]; otherwise, <c>false</c>.
/// </value>
protected bool SimpleCaptchaEnabled { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Resolves the region based on the browser language.
/// </summary>
/// <returns>
/// The region info.
/// </returns>
public static RegionInfo ResolveRegion()
{
var languages = HttpContext.Current.Request.UserLanguages;
if (languages == null || languages.Length == 0)
{
return new RegionInfo(CultureInfo.CurrentCulture.LCID);
}
try
{
var language = languages[0].ToLowerInvariant().Trim();
var culture = CultureInfo.CreateSpecificCulture(language);
return new RegionInfo(culture.LCID);
}
catch (ArgumentException)
{
try
{
return new RegionInfo(CultureInfo.CurrentCulture.LCID);
}
catch (ArgumentException)
{
// the googlebot sometimes gives a culture LCID of 127 which is invalid
// so assume US english if invalid LCID
return new RegionInfo(1033);
}
}
}
/// <summary>
/// Binds the country dropdown list with countries retrieved
/// from the .NET Framework.
/// </summary>
public void BindCountries()
{
var dic = new StringDictionary();
var col = new List<string>();
foreach (
var ri in CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(ci => new RegionInfo(ci.Name)))
{
if (!dic.ContainsKey(ri.EnglishName))
{
dic.Add(ri.EnglishName, ri.TwoLetterISORegionName.ToLowerInvariant());
}
if (!col.Contains(ri.EnglishName))
{
col.Add(ri.EnglishName);
}
}
// Add custom cultures
if (!dic.ContainsValue("bd"))
{
dic.Add("Bangladesh", "bd");
col.Add("Bangladesh");
}
if (!dic.ContainsValue("bm"))
{
dic.Add("Bermuda", "bm");
col.Add("Bermuda");
}
col.Sort();
this.ddlCountry.Items.Add(new ListItem("[Not specified]", string.Empty));
foreach (var key in col)
{
this.ddlCountry.Items.Add(new ListItem(key, dic[key]));
}
if (this.ddlCountry.SelectedIndex == 0)
{
this.ddlCountry.SelectedValue = ResolveRegion().TwoLetterISORegionName.ToLowerInvariant();
this.SetFlagImageUrl();
}
}
#endregion
#region Implemented Interfaces
#region ICallbackEventHandler
/// <summary>
/// Returns the results of a callback event that targets a control.
/// </summary>
/// <returns>
/// The result of the callback.
/// </returns>
public string GetCallbackResult()
{
return this.callback;
}
/// <summary>
/// Processes a callback event that targets a control.
/// </summary>
/// <param name="eventArgument">
/// A string that represents an event argument to pass to the event handler.
/// </param>
public void RaiseCallbackEvent(string eventArgument)
{
if (!BlogSettings.Instance.IsCommentsEnabled || !Security.IsAuthorizedTo(Rights.CreateComments))
{
return;
}
var args = eventArgument.Split(new[] { "-|-" }, StringSplitOptions.None);
var author = args[0];
var email = args[1];
var website = args[2];
var country = args[3];
var content = args[4];
var notify = bool.Parse(args[5]);
var preview = bool.Parse(args[6]);
var sentCaptcha = args[7];
// If there is no "reply to" comment, args[8] is empty
var replyToCommentId = String.IsNullOrEmpty(args[8]) ? Guid.Empty : new Guid(args[8]);
var avatar = args[9];
var recaptchaResponse = args[10];
var recaptchaChallenge = args[11];
var simpleCaptchaChallenge = args[12];
this.recaptcha.UserUniqueIdentifier = this.hfCaptcha.Value;
if (!preview && this.AnyCaptchaEnabled && this.AnyCaptchaNecessary)
{
if (this.ReCaptchaEnabled)
{
if (!this.recaptcha.ValidateAsync(recaptchaResponse, recaptchaChallenge))
{
this.callback = "RecaptchaIncorrect";
return;
}
}
else
{
this.simplecaptcha.Validate(simpleCaptchaChallenge);
if (!this.simplecaptcha.IsValid)
{
this.callback = "SimpleCaptchaIncorrect";
return;
}
}
}
var storedCaptcha = this.hfCaptcha.Value;
if (sentCaptcha != storedCaptcha)
{
return;
}
var comment = new Comment
{
Id = Guid.NewGuid(),
ParentId = replyToCommentId,
Author = this.Server.HtmlEncode(author),
Email = email,
Content = this.Server.HtmlEncode(content),
IP = Utils.GetClientIP(),
Country = country,
DateCreated = DateTime.Now,
Parent = this.Post,
IsApproved = !BlogSettings.Instance.EnableCommentsModeration,
Avatar = avatar.Trim()
};
if (Security.IsAuthenticated && BlogSettings.Instance.TrustAuthenticatedUsers)
{
comment.IsApproved = true;
}
if (BlogSettings.Instance.EnableWebsiteInComments)
{
if (website.Trim().Length > 0)
{
if (!website.ToLowerInvariant().Contains("://"))
{
website = string.Format("http://{0}", website);
}
Uri url;
if (Uri.TryCreate(website, UriKind.Absolute, out url))
{
comment.Website = url;
}
}
}
if (!preview)
{
if (notify && !this.Post.NotificationEmails.Contains(email))
{
this.Post.NotificationEmails.Add(email);
}
else if (!notify && this.Post.NotificationEmails.Contains(email))
{
this.Post.NotificationEmails.Remove(email);
}
this.Post.AddComment(comment);
this.SetCookie(author, email, website, country);
if (this.ReCaptchaEnabled)
{
this.recaptcha.UpdateLog(comment);
}
}
var path = string.Format(
"{0}themes/{1}/CommentView.ascx", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.GetThemeWithAdjustments(null));
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.RenderComment();
using (var sw = new StringWriter())
{
control.RenderControl(new HtmlTextWriter(sw));
this.callback = sw.ToString();
}
}
#endregion
#endregion
#region Methods
/// <summary>
/// Displays a delete link to visitors that is authenticated
/// using the default membership provider.
/// </summary>
/// <param name="id">
/// The id of the comment.
/// </param>
/// <returns>
/// The admin link.
/// </returns>
protected string AdminLink(string id)
{
if (Security.IsAuthenticated)
{
var sb = new StringBuilder();
foreach (var comment in this.Post.Comments.Where(comment => comment.Id.ToString() == id))
{
sb.AppendFormat(" | <a href=\"mailto:{0}\">{0}</a>", comment.Email);
}
if (Security.IsAuthorizedTo(Rights.ModerateComments))
{
const string ConfirmDelete = "Are you sure you want to delete the comment?";
sb.AppendFormat(
" | <a href=\"?deletecomment={0}\" onclick=\"return confirm('{1}?')\">{2}</a>",
id,
ConfirmDelete,
"Delete");
}
return sb.ToString();
}
return string.Empty;
}
/// <summary>
/// Displays BBCodes dynamically loaded from settings.
/// </summary>
/// <returns>
/// The bb codes.
/// </returns>
protected string BBCodes()
{
try
{
var sb = new StringBuilder();
var settings = ExtensionManager.GetSettings("BBCode");
if (settings != null)
{
var table = settings.GetDataTable();
foreach (DataRow row in table.Rows)
{
var code = (string)row["Code"];
var title = string.Format("[{0}][/{1}]", code, code);
sb.AppendFormat(
"<a title=\"{0}\" href=\"javascript:void(BlogEngine.addBbCode('{1}'))\">{2}</a>",
title,
code,
code);
}
}
return sb.ToString();
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
/// </summary>
/// <param name="e">
/// The <see cref="T:System.EventArgs"/> object that contains the event data.
/// </param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
bool isOdd = true;
if (this.Post == null)
{
this.Response.Redirect(Utils.RelativeWebRoot);
return;
}
this.NameInputId = string.Format("txtName{0}", DateTime.Now.Ticks);
this.EnableCaptchas();
if (this.Page.IsPostBack)
{
}
if (!this.Page.IsPostBack && !this.Page.IsCallback)
{
if (Security.IsAuthorizedTo(Rights.ModerateComments))
{
if (this.Request.QueryString["deletecomment"] != null)
{
this.DeleteComment();
}
else if (this.Request.QueryString["deletecommentandchildren"] != null)
{
this.DeleteCommentAndChildren();
}
else if (!string.IsNullOrEmpty(this.Request.QueryString["approvecomment"]))
{
this.ApproveComment();
}
else if (!string.IsNullOrEmpty(this.Request.QueryString["approveallcomments"]))
{
this.ApproveAllComments();
}
}
var path = string.Format(
"{0}themes/{1}/CommentView.ascx", Utils.ApplicationRelativeWebRoot, BlogSettings.Instance.GetThemeWithAdjustments(null));
bool canViewUnpublishedPosts = Security.IsAuthorizedTo(AuthorizationCheck.HasAny, new[] { Rights.ViewUnmoderatedComments, Rights.ModerateComments });
if (this.NestingSupported)
{
// newer, nested comments
if (this.Post != null)
{
this.AddNestedComments(path, this.Post.NestedComments, this.phComments, canViewUnpublishedPosts);
}
}
else
{
// old, non nested code
// Add approved Comments
isOdd = true;
foreach (var comment in
this.Post.Comments.Where(
comment => comment.Email != "pingback" && comment.Email != "trackback"))
{
if (comment.IsApproved)
{
this.CommentCounter++;
}
if (!comment.IsApproved && BlogSettings.Instance.EnableCommentsModeration)
{
continue;
}
isOdd = !isOdd;
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
this.phComments.Controls.Add(control);
}
// Add unapproved comments
if (canViewUnpublishedPosts)
{
foreach (var comment in this.Post.Comments)
{
if (comment.Email == "pingback" || comment.Email == "trackback")
{
continue;
}
if (comment.IsApproved)
{
continue;
}
isOdd = !isOdd;
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
this.phComments.Controls.Add(control);
}
}
}
var pingbacks = new List<CommentViewBase>();
isOdd = true;
foreach (var comment in this.Post.Comments)
{
var control = (CommentViewBase)this.LoadControl(path);
if (comment.Email != "pingback" && comment.Email != "trackback")
{
continue;
}
isOdd = !isOdd;
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
pingbacks.Add(control);
}
if (pingbacks.Count > 0)
{
var litTrackback = new Literal();
var sb = new StringBuilder();
sb.AppendFormat("<h3 id=\"trackbackheader\">Pingbacks and trackbacks ({0})", pingbacks.Count);
sb.Append(
"<a id=\"trackbacktoggle\" style=\"float:right;width:20px;height:20px;border:1px solid #ccc;text-decoration:none;text-align:center\"");
sb.Append(" href=\"javascript:toggle_visibility('trackbacks','trackbacktoggle');\">+</a>");
sb.Append("</h3><div id=\"trackbacks\" style=\"display:none\">");
litTrackback.Text = sb.ToString();
this.phTrckbacks.Controls.Add(litTrackback);
foreach (var c in pingbacks)
{
this.phTrckbacks.Controls.Add(c);
}
var closingDiv = new Literal { Text = @"</div>" };
this.phTrckbacks.Controls.Add(closingDiv);
}
else
{
this.phTrckbacks.Visible = false;
}
if (BlogSettings.Instance.IsCommentsEnabled && Security.IsAuthorizedTo(Rights.CreateComments))
{
if (this.Post != null &&
(!this.Post.HasCommentsEnabled ||
(BlogSettings.Instance.DaysCommentsAreEnabled > 0 &&
this.Post.DateCreated.AddDays(BlogSettings.Instance.DaysCommentsAreEnabled) <
DateTime.Now.Date)))
{
this.phAddComment.Visible = false;
this.lbCommentsDisabled.Visible = true;
}
this.BindCountries();
this.GetCookie();
this.recaptcha.UserUniqueIdentifier = this.hfCaptcha.Value = Guid.NewGuid().ToString();
}
else
{
this.phAddComment.Visible = false;
}
}
this.Page.ClientScript.GetCallbackEventReference(this, "arg", null, string.Empty);
}
/// <summary>
/// Adds the nested comments.
/// </summary>
/// <param name="path">
/// The path string.
/// </param>
/// <param name="nestedComments">
/// The nested comments.
/// </param>
/// <param name="commentsPlaceHolder">
/// The comments place holder.
/// </param>
private void AddNestedComments(string path, IEnumerable<Comment> nestedComments, Control commentsPlaceHolder, bool canViewUnpublishedPosts)
{
bool enableCommentModeration = BlogSettings.Instance.EnableCommentsModeration;
bool isOdd = true;
foreach (var comment in nestedComments)
{
if ((!comment.IsApproved && enableCommentModeration) &&
(comment.IsApproved || !canViewUnpublishedPosts))
{
continue;
}
// if comment is spam, only authorized can see it
if (comment.IsSpam && !canViewUnpublishedPosts)
{
continue;
}
if (comment.Email == "pingback" || comment.Email == "trackback")
{
continue;
}
isOdd = !isOdd;
var control = (CommentViewBase)this.LoadControl(path);
control.Comment = comment;
control.Post = this.Post;
control.IsOdd = isOdd;
if (comment.IsApproved)
{
this.CommentCounter++;
}
if (comment.Comments.Count > 0)
{
// find the next placeholder and add the subcomments to it
var subCommentsPlaceHolder = control.FindControl("phSubComments") as PlaceHolder;
if (subCommentsPlaceHolder != null)
{
this.AddNestedComments(path, comment.Comments, subCommentsPlaceHolder, canViewUnpublishedPosts);
}
}
commentsPlaceHolder.Controls.Add(control);
}
}
/// <summary>
/// Approves all comments.
/// </summary>
private void ApproveAllComments()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
this.Post.ApproveAllComments();
var index = this.Request.RawUrl.IndexOf("?");
var url = this.Request.RawUrl.Substring(0, index);
this.Response.Redirect(url, true);
}
/// <summary>
/// Approves the comment.
/// </summary>
private void ApproveComment()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
foreach (var comment in
this.Post.NotApprovedComments.Where(
comment => comment.Id == new Guid(this.Request.QueryString["approvecomment"])))
{
this.Post.ApproveComment(comment);
var index = this.Request.RawUrl.IndexOf("?");
var url = this.Request.RawUrl.Substring(0, index);
this.Response.Redirect(url, true);
}
}
/// <summary>
/// Collects the comment to delete.
/// </summary>
/// <param name="comment">
/// The comment.
/// </param>
/// <param name="commentsToDelete">
/// The comments to delete.
/// </param>
private void CollectCommentToDelete(Comment comment, List<Comment> commentsToDelete)
{
commentsToDelete.Add(comment);
// recursive collection
foreach (var subComment in comment.Comments)
{
this.CollectCommentToDelete(subComment, commentsToDelete);
}
}
/// <summary>
/// Deletes the comment.
/// </summary>
private void DeleteComment()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
foreach (var comment in
this.Post.Comments.Where(comment => comment.Id == new Guid(this.Request.QueryString["deletecomment"])))
{
this.Post.RemoveComment(comment);
var index = this.Request.RawUrl.IndexOf("?");
var url = string.Format("{0}#comment", this.Request.RawUrl.Substring(0, index));
this.Response.Redirect(url, true);
}
}
/// <summary>
/// Deletes the comment and children.
/// </summary>
private void DeleteCommentAndChildren()
{
Security.DemandUserHasRight(Rights.ModerateComments, true);
var deletecommentandchildren = new Guid(this.Request.QueryString["deletecommentandchildren"]);
foreach (var comment in this.Post.Comments)
{
if (comment.Id != deletecommentandchildren)
{
continue;
}
// collect comments to delete first so the Nesting isn't lost
var commentsToDelete = new List<Comment>();
this.CollectCommentToDelete(comment, commentsToDelete);
foreach (var commentToDelete in commentsToDelete)
{
this.Post.RemoveComment(commentToDelete);
}
var index = this.Request.RawUrl.IndexOf("?");
var url = string.Format("{0}#comment", this.Request.RawUrl.Substring(0, index));
this.Response.Redirect(url, true);
}
}
/// <summary>
/// Enables the captchas.
/// </summary>
private void EnableCaptchas()
{
this.ReCaptchaEnabled = ExtensionManager.ExtensionEnabled("Recaptcha");
this.SimpleCaptchaEnabled = ExtensionManager.ExtensionEnabled("SimpleCaptcha");
if (this.ReCaptchaEnabled && this.SimpleCaptchaEnabled)
{
var simpleCaptchaExtension = ExtensionManager.GetExtension("SimpleCaptcha");
var recaptchaExtension = ExtensionManager.GetExtension("Recaptcha");
if (simpleCaptchaExtension.Priority < recaptchaExtension.Priority)
{
this.EnableRecaptcha();
}
else
{
this.EnableSimpleCaptcha();
}
}
else if (this.ReCaptchaEnabled)
{
this.EnableRecaptcha();
}
else if (this.SimpleCaptchaEnabled)
{
this.EnableSimpleCaptcha();
}
}
/// <summary>
/// Enables the recaptcha.
/// </summary>
private void EnableRecaptcha()
{
this.AnyCaptchaEnabled = true;
this.AnyCaptchaNecessary = this.recaptcha.RecaptchaNecessary;
this.recaptcha.Visible = true;
this.simplecaptcha.Visible = false;
this.SimpleCaptchaEnabled = false;
}
/// <summary>
/// Enables the simple captcha.
/// </summary>
private void EnableSimpleCaptcha()
{
this.AnyCaptchaEnabled = true;
this.AnyCaptchaNecessary = this.simplecaptcha.SimpleCaptchaNecessary;
this.simplecaptcha.Visible = true;
this.recaptcha.Visible = false;
this.ReCaptchaEnabled = false;
}
/// <summary>
/// Gets the cookie with visitor information if any is set.
/// Then fills the contact information fields in the form.
/// </summary>
private void GetCookie()
{
var cookie = this.Request.Cookies["comment"];
try
{
if (cookie != null)
{
this.DefaultName = this.Server.UrlDecode(cookie.Values["name"]);
this.txtEmail.Text = cookie.Values["email"];
this.txtWebsite.Text = cookie.Values["url"];
this.ddlCountry.SelectedValue = cookie.Values["country"];
this.SetFlagImageUrl();
}
else if (Security.IsAuthenticated)
{
var user = Membership.GetUser();
if (user != null)
{
this.DefaultName = user.UserName;
this.txtEmail.Text = user.Email;
}
this.txtWebsite.Text = this.Request.Url.Host;
}
}
catch (Exception)
{
// Couldn't retrieve info on the visitor/user
}
}
/// <summary>
/// Sets a cookie with the entered visitor information
/// so it can be prefilled on next visit.
/// </summary>
/// <param name="name">
/// The cookie name.
/// </param>
/// <param name="email">
/// The email.
/// </param>
/// <param name="website">
/// The website.
/// </param>
/// <param name="country">
/// The country.
/// </param>
private void SetCookie(string name, string email, string website, string country)
{
var cookie = new HttpCookie("comment") { Expires = DateTime.Now.AddMonths(24) };
cookie.Values.Add("name", this.Server.UrlEncode(name.Trim()));
cookie.Values.Add("email", email.Trim());
cookie.Values.Add("url", website.Trim());
cookie.Values.Add("country", country);
this.Response.Cookies.Add(cookie);
}
/// <summary>
/// Sets the flag image URL.
/// </summary>
private void SetFlagImageUrl()
{
//this.imgFlag.ImageUrl = !string.IsNullOrEmpty(this.ddlCountry.SelectedValue)
// ? string.Format(
// "{0}pics/flags/{1}.png",
// Utils.RelativeWebRoot,
// this.ddlCountry.SelectedValue)
// : string.Format("{0}pics/pixel.png", Utils.RelativeWebRoot);
}
#endregion
}
}
| |
using System;
/// <summary>
/// ToInt16(System.Double)
/// </summary>
public class ConvertToInt16_5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt16(0<double<0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d >= 0.5);
Int16 actual = Convert.ToInt16(d);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt16(1>double>=0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d < 0.5);
Int16 actual = Convert.ToInt16(d);
Int16 expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt16(0)");
try
{
double d = 0d;
Int16 actual = Convert.ToInt16(d);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt16(int16.max)");
try
{
double d = Int16.MaxValue;
Int16 actual = Convert.ToInt16(d);
Int16 expected = Int16.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt16(int16.min)");
try
{
double d = Int16.MinValue;
Int16 actual = Convert.ToInt16(d);
Int16 expected = Int16.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
double d = Int16.MaxValue + 1;
Int16 i = Convert.ToInt16(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
double d = Int16.MinValue - 1;
Int16 i = Convert.ToInt16(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
public static int Main()
{
ConvertToInt16_5 test = new ConvertToInt16_5();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt16_5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Utilities;
using NBitcoin.BouncyCastle.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Digests
{
/**
* implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
*
* It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
* is the "endianness" of the word processing!
*/
internal class Sha1Digest
: GeneralDigest
{
private const int DigestLength = 20;
private uint H1, H2, H3, H4, H5;
private uint[] X = new uint[80];
private int xOff;
public Sha1Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha1Digest(Sha1Digest t)
: base(t)
{
CopyIn(t);
}
private void CopyIn(Sha1Digest t)
{
base.CopyIn(t);
this.H1 = t.H1;
this.H2 = t.H2;
this.H3 = t.H3;
this.H4 = t.H4;
this.H5 = t.H5;
Array.Copy(t.X, 0, this.X, 0, t.X.Length);
this.xOff = t.xOff;
}
public override string AlgorithmName
{
get
{
return "SHA-1";
}
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
this.X[this.xOff] = Pack.BE_To_UInt32(input, inOff);
if(++this.xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(long bitLength)
{
if(this.xOff > 14)
{
ProcessBlock();
}
this.X[14] = (uint)((ulong)bitLength >> 32);
this.X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE(this.H1, output, outOff);
Pack.UInt32_To_BE(this.H2, output, outOff + 4);
Pack.UInt32_To_BE(this.H3, output, outOff + 8);
Pack.UInt32_To_BE(this.H4, output, outOff + 12);
Pack.UInt32_To_BE(this.H5, output, outOff + 16);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
this.H1 = 0x67452301;
this.H2 = 0xefcdab89;
this.H3 = 0x98badcfe;
this.H4 = 0x10325476;
this.H5 = 0xc3d2e1f0;
this.xOff = 0;
Array.Clear(this.X, 0, this.X.Length);
}
//
// Additive constants
//
private const uint Y1 = 0x5a827999;
private const uint Y2 = 0x6ed9eba1;
private const uint Y3 = 0x8f1bbcdc;
private const uint Y4 = 0xca62c1d6;
private static uint F(uint u, uint v, uint w)
{
return (u & v) | (~u & w);
}
private static uint H(uint u, uint v, uint w)
{
return u ^ v ^ w;
}
private static uint G(uint u, uint v, uint w)
{
return (u & v) | (u & w) | (v & w);
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 80 word block.
//
for(int i = 16; i < 80; i++)
{
uint t = this.X[i - 3] ^ this.X[i - 8] ^ this.X[i - 14] ^ this.X[i - 16];
this.X[i] = t << 1 | t >> 31;
}
//
// set up working variables.
//
uint A = this.H1;
uint B = this.H2;
uint C = this.H3;
uint D = this.H4;
uint E = this.H5;
//
// round 1
//
int idx = 0;
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + F(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + F(B, C, D) + this.X[idx++] + Y1;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + F(A, B, C) + this.X[idx++] + Y1;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + F(E, A, B) + this.X[idx++] + Y1;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + F(D, E, A) + this.X[idx++] + Y1;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + F(C, D, E) + this.X[idx++] + Y1;
C = C << 30 | (C >> 2);
}
//
// round 2
//
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + this.X[idx++] + Y2;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + this.X[idx++] + Y2;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + this.X[idx++] + Y2;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + this.X[idx++] + Y2;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + this.X[idx++] + Y2;
C = C << 30 | (C >> 2);
}
//
// round 3
//
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + G(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + G(B, C, D) + this.X[idx++] + Y3;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + G(A, B, C) + this.X[idx++] + Y3;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + G(E, A, B) + this.X[idx++] + Y3;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + G(D, E, A) + this.X[idx++] + Y3;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + G(C, D, E) + this.X[idx++] + Y3;
C = C << 30 | (C >> 2);
}
//
// round 4
//
for(int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + H(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | (A >> 27)) + H(B, C, D) + this.X[idx++] + Y4;
B = B << 30 | (B >> 2);
D += (E << 5 | (E >> 27)) + H(A, B, C) + this.X[idx++] + Y4;
A = A << 30 | (A >> 2);
C += (D << 5 | (D >> 27)) + H(E, A, B) + this.X[idx++] + Y4;
E = E << 30 | (E >> 2);
B += (C << 5 | (C >> 27)) + H(D, E, A) + this.X[idx++] + Y4;
D = D << 30 | (D >> 2);
A += (B << 5 | (B >> 27)) + H(C, D, E) + this.X[idx++] + Y4;
C = C << 30 | (C >> 2);
}
this.H1 += A;
this.H2 += B;
this.H3 += C;
this.H4 += D;
this.H5 += E;
//
// reset start of the buffer.
//
this.xOff = 0;
Array.Clear(this.X, 0, 16);
}
public override IMemoable Copy()
{
return new Sha1Digest(this);
}
public override void Reset(IMemoable other)
{
var d = (Sha1Digest)other;
CopyIn(d);
}
}
}
| |
using System;
namespace OGE.MeasurementStream
{
internal class PointMetaDataInt32
: PointMetaData
{
public class Codes32
{
public const byte Value1 = 32;
public const byte Value2 = 33;
public const byte Value3 = 34;
public const byte ValueZero = 35;
public const byte ValueXOR4 = 36;
public const byte ValueXOR8 = 37;
public const byte ValueXOR12 = 38;
public const byte ValueXOR16 = 39;
public const byte ValueXOR20 = 40;
public const byte ValueXOR24 = 41;
public const byte ValueXOR28 = 42;
public const byte ValueXOR32 = 43;
}
const uint Bits28 = 0xFFFFFFFu;
const uint Bits24 = 0xFFFFFFu;
const uint Bits20 = 0xFFFFFu;
const uint Bits16 = 0xFFFFu;
const uint Bits12 = 0xFFFu;
const uint Bits8 = 0xFFu;
const uint Bits4 = 0xFu;
const uint Bits0 = 0x0u;
public uint PrevValue1;
public uint PrevValue2;
public uint PrevValue3;
public PointMetaDataInt32(ByteBuffer buffer, BitStream bitStream, MeasurementTypeCode code, int referenceId)
: base(buffer, bitStream, code, referenceId)
{
Mode = 4;
Mode4_1 = Codes32.Value1;
Mode4_01 = Codes32.Value2;
Mode4_001 = Codes32.Value3;
}
public override void ReadValue(int code, UnionValues outValue)
{
uint valueRaw = 0;
if (code == Codes32.Value1)
{
valueRaw = PrevValue1;
}
else if (code == Codes32.Value2)
{
valueRaw = PrevValue2;
PrevValue2 = PrevValue1;
PrevValue1 = valueRaw;
}
else if (code == Codes32.Value3)
{
valueRaw = PrevValue3;
PrevValue3 = PrevValue2;
PrevValue2 = PrevValue1;
PrevValue1 = valueRaw;
}
else if (code == Codes32.ValueZero)
{
valueRaw = 0;
PrevValue3 = PrevValue2;
PrevValue2 = PrevValue1;
PrevValue1 = valueRaw;
}
else
{
switch (code)
{
case Codes32.ValueXOR4:
valueRaw = (uint)BitStream.ReadBits4() ^ PrevValue1;
break;
case Codes32.ValueXOR8:
valueRaw = Buffer.Data[Buffer.Position] ^ PrevValue1;
Buffer.Position = Buffer.Position + 1;
break;
case Codes32.ValueXOR12:
valueRaw = (uint)BitStream.ReadBits4() ^ (uint)(Buffer.Data[Buffer.Position] << 4) ^ PrevValue1;
Buffer.Position = Buffer.Position + 1;
break;
case Codes32.ValueXOR16:
valueRaw = Buffer.Data[Buffer.Position] ^ (uint)(Buffer.Data[Buffer.Position + 1] << 8) ^ PrevValue1;
Buffer.Position = Buffer.Position + 2;
break;
case Codes32.ValueXOR20:
valueRaw = (uint)BitStream.ReadBits4() ^ (uint)(Buffer.Data[Buffer.Position] << 4) ^ (uint)(Buffer.Data[Buffer.Position + 1] << 12) ^ PrevValue1;
Buffer.Position = Buffer.Position + 2;
break;
case Codes32.ValueXOR24:
valueRaw = Buffer.Data[Buffer.Position] ^ (uint)(Buffer.Data[Buffer.Position + 1] << 8) ^ (uint)(Buffer.Data[Buffer.Position + 2] << 16) ^ PrevValue1;
Buffer.Position = Buffer.Position + 3;
break;
case Codes32.ValueXOR28:
valueRaw = (uint)BitStream.ReadBits4() ^ (uint)(Buffer.Data[Buffer.Position] << 4) ^ (uint)(Buffer.Data[Buffer.Position + 1] << 12) ^ (uint)(Buffer.Data[Buffer.Position + 2] << 20) ^ PrevValue1;
Buffer.Position = Buffer.Position + 3;
break;
case Codes32.ValueXOR32:
valueRaw = Buffer.Data[Buffer.Position] ^ (uint)(Buffer.Data[Buffer.Position + 1] << 8) ^ (uint)(Buffer.Data[Buffer.Position + 2] << 16) ^ (uint)(Buffer.Data[Buffer.Position + 3] << 24) ^ PrevValue1;
Buffer.Position = Buffer.Position + 4;
break;
default:
throw new Exception("Code not valid");
}
PrevValue3 = PrevValue2;
PrevValue2 = PrevValue1;
PrevValue1 = valueRaw;
}
outValue.ValueUInt32 = valueRaw;
}
public override void WriteValue(UnionValues currentValue)
{
uint value = currentValue.ValueUInt32;
if (PrevValue1 == value)
{
BitStream.WriteCode(Codes32.Value1);
}
else if (PrevValue2 == value)
{
BitStream.WriteCode(Codes32.Value2);
PrevValue2 = PrevValue1;
PrevValue1 = value;
}
else if (PrevValue3 == value)
{
BitStream.WriteCode(Codes32.Value3);
PrevValue3 = PrevValue2;
PrevValue2 = PrevValue1;
PrevValue1 = value;
}
else if (value == 0)
{
BitStream.WriteCode(Codes32.ValueZero);
PrevValue3 = PrevValue2;
PrevValue2 = PrevValue1;
PrevValue1 = 0;
}
else
{
uint bitsChanged = value ^ PrevValue1;
if (bitsChanged == Bits0)
{
throw new Exception("Programming Error");
}
else if (bitsChanged <= Bits4)
{
BitStream.WriteCode4(Codes32.ValueXOR4, (byte)bitsChanged);
}
else if (bitsChanged <= Bits8)
{
BitStream.WriteCode(Codes32.ValueXOR8);
Buffer.Data[Buffer.Position] = (byte)bitsChanged;
Buffer.Position++;
}
else if (bitsChanged <= Bits12)
{
BitStream.WriteCode4(Codes32.ValueXOR12, (byte)bitsChanged);
Buffer.Data[Buffer.Position] = (byte)(bitsChanged >> 4);
Buffer.Position++;
}
else if (bitsChanged <= Bits16)
{
BitStream.WriteCode(Codes32.ValueXOR16);
Buffer.Data[Buffer.Position] = (byte)bitsChanged;
Buffer.Data[Buffer.Position + 1] = (byte)(bitsChanged >> 8);
Buffer.Position = Buffer.Position + 2;
}
else if (bitsChanged <= Bits20)
{
BitStream.WriteCode4(Codes32.ValueXOR20, (byte)bitsChanged);
Buffer.Data[Buffer.Position] = (byte)(bitsChanged >> 4);
Buffer.Data[Buffer.Position + 1] = (byte)(bitsChanged >> 12);
Buffer.Position = Buffer.Position + 2;
}
else if (bitsChanged <= Bits24)
{
BitStream.WriteCode(Codes32.ValueXOR24);
Buffer.Data[Buffer.Position] = (byte)bitsChanged;
Buffer.Data[Buffer.Position + 1] = (byte)(bitsChanged >> 8);
Buffer.Data[Buffer.Position + 2] = (byte)(bitsChanged >> 16);
Buffer.Position = Buffer.Position + 3;
}
else if (bitsChanged <= Bits28)
{
BitStream.WriteCode4(Codes32.ValueXOR28, (byte)bitsChanged);
Buffer.Data[Buffer.Position] = (byte)(bitsChanged >> 4);
Buffer.Data[Buffer.Position + 1] = (byte)(bitsChanged >> 12);
Buffer.Data[Buffer.Position + 2] = (byte)(bitsChanged >> 20);
Buffer.Position = Buffer.Position + 3;
}
else
{
BitStream.WriteCode(Codes32.ValueXOR32);
Buffer.Data[Buffer.Position] = (byte)bitsChanged;
Buffer.Data[Buffer.Position + 1] = (byte)(bitsChanged >> 8);
Buffer.Data[Buffer.Position + 2] = (byte)(bitsChanged >> 16);
Buffer.Data[Buffer.Position + 3] = (byte)(bitsChanged >> 24);
Buffer.Position = Buffer.Position + 4;
}
PrevValue3 = PrevValue2;
PrevValue2 = PrevValue1;
PrevValue1 = value;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal sealed class XPathScanner
{
private string _xpathExpr;
private int _xpathExprIndex;
private LexKind _kind;
private char _currentChar;
private string _name;
private string _prefix;
private string _stringValue;
private double _numberValue = double.NaN;
private bool _canBeFunction;
private XmlCharType _xmlCharType = XmlCharType.Instance;
public XPathScanner(string xpathExpr)
{
if (xpathExpr == null)
{
throw XPathException.Create(SR.Xp_ExprExpected, string.Empty);
}
_xpathExpr = xpathExpr;
NextChar();
NextLex();
}
public string SourceText { get { return _xpathExpr; } }
private char CurrentChar { get { return _currentChar; } }
private bool NextChar()
{
Debug.Assert(0 <= _xpathExprIndex && _xpathExprIndex <= _xpathExpr.Length);
if (_xpathExprIndex < _xpathExpr.Length)
{
_currentChar = _xpathExpr[_xpathExprIndex++];
return true;
}
else
{
_currentChar = '\0';
return false;
}
}
#if XML10_FIFTH_EDITION
private char PeekNextChar()
{
Debug.Assert(0 <= xpathExprIndex && xpathExprIndex <= xpathExpr.Length);
if (xpathExprIndex < xpathExpr.Length)
{
return xpathExpr[xpathExprIndex];
}
else
{
Debug.Assert(xpathExprIndex == xpathExpr.Length);
return '\0';
}
}
#endif
public LexKind Kind { get { return _kind; } }
public string Name
{
get
{
Debug.Assert(_kind == LexKind.Name || _kind == LexKind.Axe);
Debug.Assert(_name != null);
return _name;
}
}
public string Prefix
{
get
{
Debug.Assert(_kind == LexKind.Name);
Debug.Assert(_prefix != null);
return _prefix;
}
}
public string StringValue
{
get
{
Debug.Assert(_kind == LexKind.String);
Debug.Assert(_stringValue != null);
return _stringValue;
}
}
public double NumberValue
{
get
{
Debug.Assert(_kind == LexKind.Number);
Debug.Assert(!double.IsNaN(_numberValue));
return _numberValue;
}
}
// To parse PathExpr we need a way to distinct name from function.
// THis distinction can't be done without context: "or (1 != 0)" this this a function or 'or' in OrExp
public bool CanBeFunction
{
get
{
Debug.Assert(_kind == LexKind.Name);
return _canBeFunction;
}
}
void SkipSpace()
{
while (_xmlCharType.IsWhiteSpace(this.CurrentChar) && NextChar()) ;
}
public bool NextLex()
{
SkipSpace();
switch (this.CurrentChar)
{
case '\0':
_kind = LexKind.Eof;
return false;
case ',':
case '@':
case '(':
case ')':
case '|':
case '*':
case '[':
case ']':
case '+':
case '-':
case '=':
case '#':
case '$':
_kind = (LexKind)Convert.ToInt32(this.CurrentChar, CultureInfo.InvariantCulture);
NextChar();
break;
case '<':
_kind = LexKind.Lt;
NextChar();
if (this.CurrentChar == '=')
{
_kind = LexKind.Le;
NextChar();
}
break;
case '>':
_kind = LexKind.Gt;
NextChar();
if (this.CurrentChar == '=')
{
_kind = LexKind.Ge;
NextChar();
}
break;
case '!':
_kind = LexKind.Bang;
NextChar();
if (this.CurrentChar == '=')
{
_kind = LexKind.Ne;
NextChar();
}
break;
case '.':
_kind = LexKind.Dot;
NextChar();
if (this.CurrentChar == '.')
{
_kind = LexKind.DotDot;
NextChar();
}
else if (XmlCharType.IsDigit(this.CurrentChar))
{
_kind = LexKind.Number;
_numberValue = ScanFraction();
}
break;
case '/':
_kind = LexKind.Slash;
NextChar();
if (this.CurrentChar == '/')
{
_kind = LexKind.SlashSlash;
NextChar();
}
break;
case '"':
case '\'':
_kind = LexKind.String;
_stringValue = ScanString();
break;
default:
if (XmlCharType.IsDigit(this.CurrentChar))
{
_kind = LexKind.Number;
_numberValue = ScanNumber();
}
else if (_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
)
{
_kind = LexKind.Name;
_name = ScanName();
_prefix = string.Empty;
// "foo:bar" is one lexem not three because it doesn't allow spaces in between
// We should distinct it from "foo::" and need process "foo ::" as well
if (this.CurrentChar == ':')
{
NextChar();
// can be "foo:bar" or "foo::"
if (this.CurrentChar == ':')
{ // "foo::"
NextChar();
_kind = LexKind.Axe;
}
else
{ // "foo:*", "foo:bar" or "foo: "
_prefix = _name;
if (this.CurrentChar == '*')
{
NextChar();
_name = "*";
}
else if (_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
)
{
_name = ScanName();
}
else
{
throw XPathException.Create(SR.Xp_InvalidName, SourceText);
}
}
}
else
{
SkipSpace();
if (this.CurrentChar == ':')
{
NextChar();
// it can be "foo ::" or just "foo :"
if (this.CurrentChar == ':')
{
NextChar();
_kind = LexKind.Axe;
}
else
{
throw XPathException.Create(SR.Xp_InvalidName, SourceText);
}
}
}
SkipSpace();
_canBeFunction = (this.CurrentChar == '(');
}
else
{
throw XPathException.Create(SR.Xp_InvalidToken, SourceText);
}
break;
}
return true;
}
private double ScanNumber()
{
Debug.Assert(this.CurrentChar == '.' || XmlCharType.IsDigit(this.CurrentChar));
int start = _xpathExprIndex - 1;
int len = 0;
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
if (this.CurrentChar == '.')
{
NextChar(); len++;
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
}
return XmlConvert.ToXPathDouble(_xpathExpr.Substring(start, len));
}
private double ScanFraction()
{
Debug.Assert(XmlCharType.IsDigit(this.CurrentChar));
int start = _xpathExprIndex - 2;
Debug.Assert(0 <= start && _xpathExpr[start] == '.');
int len = 1; // '.'
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
return XmlConvert.ToXPathDouble(_xpathExpr.Substring(start, len));
}
private string ScanString()
{
char endChar = this.CurrentChar;
NextChar();
int start = _xpathExprIndex - 1;
int len = 0;
while (this.CurrentChar != endChar)
{
if (!NextChar())
{
throw XPathException.Create(SR.Xp_UnclosedString);
}
len++;
}
Debug.Assert(this.CurrentChar == endChar);
NextChar();
return _xpathExpr.Substring(start, len);
}
private string ScanName()
{
Debug.Assert(_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
);
int start = _xpathExprIndex - 1;
int len = 0;
for (; ;)
{
if (_xmlCharType.IsNCNameSingleChar(this.CurrentChar))
{
NextChar();
len++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(this.PeekNextChar(), this.CurerntChar))
{
NextChar();
NextChar();
len += 2;
}
#endif
else
{
break;
}
}
return _xpathExpr.Substring(start, len);
}
public enum LexKind
{
Comma = ',',
Slash = '/',
At = '@',
Dot = '.',
LParens = '(',
RParens = ')',
LBracket = '[',
RBracket = ']',
Star = '*',
Plus = '+',
Minus = '-',
Eq = '=',
Lt = '<',
Gt = '>',
Bang = '!',
Dollar = '$',
Apos = '\'',
Quote = '"',
Union = '|',
Ne = 'N', // !=
Le = 'L', // <=
Ge = 'G', // >=
And = 'A', // &&
Or = 'O', // ||
DotDot = 'D', // ..
SlashSlash = 'S', // //
Name = 'n', // XML _Name
String = 's', // Quoted string constant
Number = 'd', // _Number constant
Axe = 'a', // Axe (like child::)
Eof = 'E',
};
}
}
| |
/*
* OEML - REST API
*
* This section will provide necessary information about the `CoinAPI OEML REST API` protocol. <br/> This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a> <br/><br/> Implemented Standards: * [HTTP1.0](https://datatracker.ietf.org/doc/html/rfc1945) * [HTTP1.1](https://datatracker.ietf.org/doc/html/rfc2616) * [HTTP2.0](https://datatracker.ietf.org/doc/html/rfc7540)
*
* The version of the OpenAPI document: v1
* Contact: support@coinapi.io
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = CoinAPI.OMS.REST.V1.Client.OpenAPIDateConverter;
namespace CoinAPI.OMS.REST.V1.Model
{
/// <summary>
/// The Position object.
/// </summary>
[DataContract]
public partial class PositionData : IEquatable<PositionData>, IValidatableObject
{
/// <summary>
/// Gets or Sets Side
/// </summary>
[DataMember(Name="side", EmitDefaultValue=false)]
public OrdSide? Side { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PositionData" /> class.
/// </summary>
/// <param name="symbolIdExchange">Exchange symbol..</param>
/// <param name="symbolIdCoinapi">CoinAPI symbol..</param>
/// <param name="avgEntryPrice">Calculated average price of all fills on this position..</param>
/// <param name="quantity">The current position quantity..</param>
/// <param name="side">side.</param>
/// <param name="unrealizedPnl">Unrealised profit or loss (PNL) of this position..</param>
/// <param name="leverage">Leverage for this position reported by the exchange..</param>
/// <param name="crossMargin">Is cross margin mode enable for this position?.</param>
/// <param name="liquidationPrice">Liquidation price. If mark price will reach this value, the position will be liquidated..</param>
/// <param name="rawData">rawData.</param>
public PositionData(string symbolIdExchange = default(string), string symbolIdCoinapi = default(string), decimal avgEntryPrice = default(decimal), decimal quantity = default(decimal), OrdSide? side = default(OrdSide?), decimal unrealizedPnl = default(decimal), decimal leverage = default(decimal), bool crossMargin = default(bool), decimal liquidationPrice = default(decimal), Object rawData = default(Object))
{
this.SymbolIdExchange = symbolIdExchange;
this.SymbolIdCoinapi = symbolIdCoinapi;
this.AvgEntryPrice = avgEntryPrice;
this.Quantity = quantity;
this.Side = side;
this.UnrealizedPnl = unrealizedPnl;
this.Leverage = leverage;
this.CrossMargin = crossMargin;
this.LiquidationPrice = liquidationPrice;
this.RawData = rawData;
}
/// <summary>
/// Exchange symbol.
/// </summary>
/// <value>Exchange symbol.</value>
[DataMember(Name="symbol_id_exchange", EmitDefaultValue=false)]
public string SymbolIdExchange { get; set; }
/// <summary>
/// CoinAPI symbol.
/// </summary>
/// <value>CoinAPI symbol.</value>
[DataMember(Name="symbol_id_coinapi", EmitDefaultValue=false)]
public string SymbolIdCoinapi { get; set; }
/// <summary>
/// Calculated average price of all fills on this position.
/// </summary>
/// <value>Calculated average price of all fills on this position.</value>
[DataMember(Name="avg_entry_price", EmitDefaultValue=false)]
public decimal AvgEntryPrice { get; set; }
/// <summary>
/// The current position quantity.
/// </summary>
/// <value>The current position quantity.</value>
[DataMember(Name="quantity", EmitDefaultValue=false)]
public decimal Quantity { get; set; }
/// <summary>
/// Unrealised profit or loss (PNL) of this position.
/// </summary>
/// <value>Unrealised profit or loss (PNL) of this position.</value>
[DataMember(Name="unrealized_pnl", EmitDefaultValue=false)]
public decimal UnrealizedPnl { get; set; }
/// <summary>
/// Leverage for this position reported by the exchange.
/// </summary>
/// <value>Leverage for this position reported by the exchange.</value>
[DataMember(Name="leverage", EmitDefaultValue=false)]
public decimal Leverage { get; set; }
/// <summary>
/// Is cross margin mode enable for this position?
/// </summary>
/// <value>Is cross margin mode enable for this position?</value>
[DataMember(Name="cross_margin", EmitDefaultValue=false)]
public bool CrossMargin { get; set; }
/// <summary>
/// Liquidation price. If mark price will reach this value, the position will be liquidated.
/// </summary>
/// <value>Liquidation price. If mark price will reach this value, the position will be liquidated.</value>
[DataMember(Name="liquidation_price", EmitDefaultValue=false)]
public decimal LiquidationPrice { get; set; }
/// <summary>
/// Gets or Sets RawData
/// </summary>
[DataMember(Name="raw_data", EmitDefaultValue=false)]
public Object RawData { 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 PositionData {\n");
sb.Append(" SymbolIdExchange: ").Append(SymbolIdExchange).Append("\n");
sb.Append(" SymbolIdCoinapi: ").Append(SymbolIdCoinapi).Append("\n");
sb.Append(" AvgEntryPrice: ").Append(AvgEntryPrice).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" Side: ").Append(Side).Append("\n");
sb.Append(" UnrealizedPnl: ").Append(UnrealizedPnl).Append("\n");
sb.Append(" Leverage: ").Append(Leverage).Append("\n");
sb.Append(" CrossMargin: ").Append(CrossMargin).Append("\n");
sb.Append(" LiquidationPrice: ").Append(LiquidationPrice).Append("\n");
sb.Append(" RawData: ").Append(RawData).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PositionData);
}
/// <summary>
/// Returns true if PositionData instances are equal
/// </summary>
/// <param name="input">Instance of PositionData to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PositionData input)
{
if (input == null)
return false;
return
(
this.SymbolIdExchange == input.SymbolIdExchange ||
(this.SymbolIdExchange != null &&
this.SymbolIdExchange.Equals(input.SymbolIdExchange))
) &&
(
this.SymbolIdCoinapi == input.SymbolIdCoinapi ||
(this.SymbolIdCoinapi != null &&
this.SymbolIdCoinapi.Equals(input.SymbolIdCoinapi))
) &&
(
this.AvgEntryPrice == input.AvgEntryPrice ||
(this.AvgEntryPrice != null &&
this.AvgEntryPrice.Equals(input.AvgEntryPrice))
) &&
(
this.Quantity == input.Quantity ||
(this.Quantity != null &&
this.Quantity.Equals(input.Quantity))
) &&
(
this.Side == input.Side ||
(this.Side != null &&
this.Side.Equals(input.Side))
) &&
(
this.UnrealizedPnl == input.UnrealizedPnl ||
(this.UnrealizedPnl != null &&
this.UnrealizedPnl.Equals(input.UnrealizedPnl))
) &&
(
this.Leverage == input.Leverage ||
(this.Leverage != null &&
this.Leverage.Equals(input.Leverage))
) &&
(
this.CrossMargin == input.CrossMargin ||
(this.CrossMargin != null &&
this.CrossMargin.Equals(input.CrossMargin))
) &&
(
this.LiquidationPrice == input.LiquidationPrice ||
(this.LiquidationPrice != null &&
this.LiquidationPrice.Equals(input.LiquidationPrice))
) &&
(
this.RawData == input.RawData ||
(this.RawData != null &&
this.RawData.Equals(input.RawData))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.SymbolIdExchange != null)
hashCode = hashCode * 59 + this.SymbolIdExchange.GetHashCode();
if (this.SymbolIdCoinapi != null)
hashCode = hashCode * 59 + this.SymbolIdCoinapi.GetHashCode();
if (this.AvgEntryPrice != null)
hashCode = hashCode * 59 + this.AvgEntryPrice.GetHashCode();
if (this.Quantity != null)
hashCode = hashCode * 59 + this.Quantity.GetHashCode();
if (this.Side != null)
hashCode = hashCode * 59 + this.Side.GetHashCode();
if (this.UnrealizedPnl != null)
hashCode = hashCode * 59 + this.UnrealizedPnl.GetHashCode();
if (this.Leverage != null)
hashCode = hashCode * 59 + this.Leverage.GetHashCode();
if (this.CrossMargin != null)
hashCode = hashCode * 59 + this.CrossMargin.GetHashCode();
if (this.LiquidationPrice != null)
hashCode = hashCode * 59 + this.LiquidationPrice.GetHashCode();
if (this.RawData != null)
hashCode = hashCode * 59 + this.RawData.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using FailureTroubleshooting.Areas.HelpPage.ModelDescriptions;
using FailureTroubleshooting.Areas.HelpPage.Models;
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;
namespace FailureTroubleshooting.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);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/speech/v1/cloud_speech.proto
// Original file comments:
// Copyright 2017 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.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace Google.Cloud.Speech.V1 {
/// <summary>
/// Service that implements Google Cloud Speech API.
/// </summary>
public static partial class Speech
{
static readonly string __ServiceName = "google.cloud.speech.v1.Speech";
static readonly grpc::Marshaller<global::Google.Cloud.Speech.V1.RecognizeRequest> __Marshaller_RecognizeRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1.RecognizeRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Speech.V1.RecognizeResponse> __Marshaller_RecognizeResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1.RecognizeResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest> __Marshaller_LongRunningRecognizeRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.LongRunning.Operation> __Marshaller_Operation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.Operation.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Speech.V1.StreamingRecognizeRequest> __Marshaller_StreamingRecognizeRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1.StreamingRecognizeRequest.Parser.ParseFrom);
static readonly grpc::Marshaller<global::Google.Cloud.Speech.V1.StreamingRecognizeResponse> __Marshaller_StreamingRecognizeResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Speech.V1.StreamingRecognizeResponse.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Cloud.Speech.V1.RecognizeRequest, global::Google.Cloud.Speech.V1.RecognizeResponse> __Method_Recognize = new grpc::Method<global::Google.Cloud.Speech.V1.RecognizeRequest, global::Google.Cloud.Speech.V1.RecognizeResponse>(
grpc::MethodType.Unary,
__ServiceName,
"Recognize",
__Marshaller_RecognizeRequest,
__Marshaller_RecognizeResponse);
static readonly grpc::Method<global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest, global::Google.LongRunning.Operation> __Method_LongRunningRecognize = new grpc::Method<global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest, global::Google.LongRunning.Operation>(
grpc::MethodType.Unary,
__ServiceName,
"LongRunningRecognize",
__Marshaller_LongRunningRecognizeRequest,
__Marshaller_Operation);
static readonly grpc::Method<global::Google.Cloud.Speech.V1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1.StreamingRecognizeResponse> __Method_StreamingRecognize = new grpc::Method<global::Google.Cloud.Speech.V1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1.StreamingRecognizeResponse>(
grpc::MethodType.DuplexStreaming,
__ServiceName,
"StreamingRecognize",
__Marshaller_StreamingRecognizeRequest,
__Marshaller_StreamingRecognizeResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Speech.V1.CloudSpeechReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of Speech</summary>
public abstract partial class SpeechBase
{
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Speech.V1.RecognizeResponse> Recognize(global::Google.Cloud.Speech.V1.RecognizeRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> LongRunningRecognize(global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Performs bidirectional streaming speech recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
/// <param name="requestStream">Used for reading requests from the client.</param>
/// <param name="responseStream">Used for sending responses back to the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>A task indicating completion of the handler.</returns>
public virtual global::System.Threading.Tasks.Task StreamingRecognize(grpc::IAsyncStreamReader<global::Google.Cloud.Speech.V1.StreamingRecognizeRequest> requestStream, grpc::IServerStreamWriter<global::Google.Cloud.Speech.V1.StreamingRecognizeResponse> responseStream, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for Speech</summary>
public partial class SpeechClient : grpc::ClientBase<SpeechClient>
{
/// <summary>Creates a new client for Speech</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public SpeechClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for Speech that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public SpeechClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected SpeechClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected SpeechClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Speech.V1.RecognizeResponse Recognize(global::Google.Cloud.Speech.V1.RecognizeRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Recognize(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Cloud.Speech.V1.RecognizeResponse Recognize(global::Google.Cloud.Speech.V1.RecognizeRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Recognize, null, options, request);
}
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Speech.V1.RecognizeResponse> RecognizeAsync(global::Google.Cloud.Speech.V1.RecognizeRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return RecognizeAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Performs synchronous speech recognition: receive results after all audio
/// has been sent and processed.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Speech.V1.RecognizeResponse> RecognizeAsync(global::Google.Cloud.Speech.V1.RecognizeRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Recognize, null, options, request);
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.LongRunning.Operation LongRunningRecognize(global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return LongRunningRecognize(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.LongRunning.Operation LongRunningRecognize(global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_LongRunningRecognize, null, options, request);
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> LongRunningRecognizeAsync(global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return LongRunningRecognizeAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Performs asynchronous speech recognition: receive results via the
/// google.longrunning.Operations interface. Returns either an
/// `Operation.error` or an `Operation.response` which contains
/// a `LongRunningRecognizeResponse` message.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> LongRunningRecognizeAsync(global::Google.Cloud.Speech.V1.LongRunningRecognizeRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_LongRunningRecognize, null, options, request);
}
/// <summary>
/// Performs bidirectional streaming speech recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Google.Cloud.Speech.V1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1.StreamingRecognizeResponse> StreamingRecognize(grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return StreamingRecognize(new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Performs bidirectional streaming speech recognition: receive results while
/// sending audio. This method is only available via the gRPC API (not REST).
/// </summary>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncDuplexStreamingCall<global::Google.Cloud.Speech.V1.StreamingRecognizeRequest, global::Google.Cloud.Speech.V1.StreamingRecognizeResponse> StreamingRecognize(grpc::CallOptions options)
{
return CallInvoker.AsyncDuplexStreamingCall(__Method_StreamingRecognize, null, options);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override SpeechClient NewInstance(ClientBaseConfiguration configuration)
{
return new SpeechClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(SpeechBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_Recognize, serviceImpl.Recognize)
.AddMethod(__Method_LongRunningRecognize, serviceImpl.LongRunningRecognize)
.AddMethod(__Method_StreamingRecognize, serviceImpl.StreamingRecognize).Build();
}
}
}
#endregion
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BeBlueTodoApp.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);
}
}
}
}
| |
// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2014, SIL International. All Rights Reserved.
// <copyright from='2008' to='2014' company='SIL International'>
// Copyright (c) 2014, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (http://sil.mit-license.org/)
// </copyright>
#endregion
//
// This class originated in FieldWorks (under the GNU Lesser General Public License), but we
// have decided to make it avaialble in SIL.ScriptureUtils as part of Palaso so it will be more
// readily available to other projects.
// ---------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace SIL.ScriptureUtils
{
/// <summary>
/// Manipulate information for standard chatper/verse schemes
/// </summary>
public class VersificationTable
{
private readonly ScrVers scrVers;
private List<int[]> bookList;
private Dictionary<string, string> toStandard;
private Dictionary<string, string> fromStandard;
private static string baseDir;
private static VersificationTable[] versifications = null;
// Names of the versificaiton files. These are in "\My Paratext Projects"
private static string[] versificationFiles = new string[] { "",
"org.vrs", "lxx.vrs", "vul.vrs", "eng.vrs", "rsc.vrs", "rso.vrs", "oth.vrs",
"oth2.vrs", "oth3.vrs", "oth4.vrs", "oth5.vrs", "oth6.vrs", "oth7.vrs", "oth8.vrs",
"oth9.vrs", "oth10.vrs", "oth11.vrs", "oth12.vrs", "oth13.vrs", "oth14.vrs",
"oth15.vrs", "oth16.vrs", "oth17.vrs", "oth18.vrs", "oth19.vrs", "oth20.vrs",
"oth21.vrs", "oth22.vrs", "oth23.vrs", "oth24.vrs" };
/// ------------------------------------------------------------------------------------
/// <summary>
/// This method should be called once before an application accesses anything that
/// requires versification info.
/// TODO: Paratext needs to call this with ScrTextCollection.SettingsDirectory.
/// </summary>
/// <param name="vrsFolder">Path to the folder containing the .vrs files</param>
/// ------------------------------------------------------------------------------------
public static void Initialize(string vrsFolder)
{
baseDir = vrsFolder;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Get the versification table for this versification
/// </summary>
/// <param name="vers"></param>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public static VersificationTable Get(ScrVers vers)
{
Debug.Assert(vers != ScrVers.Unknown);
if (versifications == null)
versifications = new VersificationTable[versificationFiles.GetUpperBound(0)];
// Read versification table if not already read
if (versifications[(int)vers] == null)
{
versifications[(int)vers] = new VersificationTable(vers);
ReadVersificationFile(FileName(vers), versifications[(int)vers]);
}
return versifications[(int)vers];
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Read versification file and "add" its entries.
/// At the moment we only do this once. Eventually we will call this twice.
/// Once for the standard versification, once for custom entries in versification.vrs
/// file for this project.
/// </summary>
/// <param name="fileName"></param>
/// <param name="versification"></param>
/// ------------------------------------------------------------------------------------
private static void ReadVersificationFile(string fileName, VersificationTable versification)
{
using (TextReader reader = new StreamReader(fileName))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
line = line.Trim();
if (line == "" || line[0] == '#')
continue;
if (line.Contains("="))
ParseMappingLine(fileName, versification, line);
else
ParseChapterVerseLine(fileName, versification, line);
}
}
}
// Parse lines mapping from this versification to standard versification
// GEN 1:10 = GEN 2:11
// GEN 1:10-13 = GEN 2:11-14
private static void ParseChapterVerseLine(string fileName, VersificationTable versification, string line)
{
string[] parts = line.Split(' ');
int bookNum = BCVRef.BookToNumber(parts[0]);
if (bookNum == -1)
return; // Deuterocanonical books not supported
if (bookNum == 0)
throw new Exception("Invalid [" + parts[0] + "] " + fileName);
while (versification.bookList.Count < bookNum)
versification.bookList.Add(new int[1] { 1 });
List<int> verses = new List<int>();
for (int i = 1; i <= parts.GetUpperBound(0); ++i)
{
string[] pieces = parts[i].Split(':');
int verseCount;
if (pieces.GetUpperBound(0) != 1 ||
!int.TryParse(pieces[1], out verseCount) || verseCount <= 0)
{
throw new Exception("Invalid [" + line + "] " + fileName);
}
verses.Add(verseCount);
}
versification.bookList[bookNum - 1] = verses.ToArray();
}
// Parse lines giving number of verses for each chapter like
// GEN 1:10 2:23 ...
private static void ParseMappingLine(string fileName, VersificationTable versification, string line)
{
try
{
string[] parts = line.Split('=');
string[] leftPieces = parts[0].Trim().Split('-');
string[] rightPieces = parts[1].Trim().Split('-');
BCVRef left = new BCVRef(leftPieces[0]);
int leftLimit = leftPieces.GetUpperBound(0) == 0 ? 0 : int.Parse(leftPieces[1]);
BCVRef right = new BCVRef(rightPieces[0]);
while (true)
{
versification.toStandard[left.ToString()] = right.ToString();
versification.fromStandard[right.ToString()] = left.ToString();
if (left.Verse >= leftLimit)
break;
left.Verse = left.Verse + 1;
right.Verse = right.Verse + 1;
}
}
catch
{
// ENHANCE: Make it so the TE version of Localizer can have its own resources for stuff
// like this.
throw new Exception("Invalid [" + line + "] " + fileName);
}
}
/// <summary>
/// Gets the name of this requested versification file.
/// </summary>
/// <param name="vers">Versification scheme</param>
public static string GetFileNameForVersification(ScrVers vers)
{
return versificationFiles[(int)vers];
}
// Get path of this versification file.
// Fall back to eng.vrs if not present.
private static string FileName(ScrVers vers)
{
if (baseDir == null)
throw new InvalidOperationException("VersificationTable.Initialize must be called first");
string fileName = Path.Combine(baseDir, GetFileNameForVersification(vers));
if (!File.Exists(fileName))
fileName = Path.Combine(baseDir, GetFileNameForVersification(ScrVers.English));
return fileName;
}
// Create empty versification table
private VersificationTable(ScrVers vers)
{
this.scrVers = vers;
bookList = new List<int[]>();
toStandard = new Dictionary<string, string>();
fromStandard = new Dictionary<string, string>();
}
public int LastBook()
{
return bookList.Count;
}
/// <summary>
/// Last chapter number in this book.
/// </summary>
/// <param name="bookNum"></param>
/// <returns></returns>
public int LastChapter(int bookNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
return chapters.GetUpperBound(0) + 1;
}
/// <summary>
/// Last verse number in this book/chapter.
/// </summary>
/// <param name="bookNum"></param>
/// <param name="chapterNum"></param>
/// <returns></returns>
public int LastVerse(int bookNum, int chapterNum)
{
if (bookNum <= 0)
return 0;
if (bookNum - 1 >= bookList.Count)
return 1;
int[] chapters = bookList[bookNum - 1];
// Chapter "0" is the intro material. Pretend that it has 1 verse.
if (chapterNum - 1 > chapters.GetUpperBound(0) || chapterNum < 1)
return 1;
return chapters[chapterNum - 1];
}
/// <summary>
/// Change the passed VerseRef to be this versification.
/// </summary>
/// <param name="vref"></param>
public void ChangeVersification(IVerseReference vref)
{
if (vref.Versification == scrVers)
return;
// Map from existing to standard versification
string verse = vref.ToString();
string verse2;
Get(vref.Versification).toStandard.TryGetValue(verse, out verse2);
if (verse2 == null)
verse2 = verse;
// Map from standard versification to this versification
string verse3;
fromStandard.TryGetValue(verse2, out verse3);
if (verse3 == null)
verse3 = verse2;
// If verse has changed, parse new value
if (verse != verse3)
vref.Parse(verse3);
vref.Versification = scrVers;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ExcelImporter.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);
}
}
}
}
| |
/* ====================================================================
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 TestCases.SS.Formula.Functions
{
using System;
using NUnit.Framework;
using NPOI.SS.Formula.Eval;
using TestCases.SS.Formula.Functions;
using NPOI.SS.Formula.Functions;
/**
* Test cases for MATCH()
*
* @author Josh Micich
*/
[TestFixture]
public class TestMatch
{
/** less than or equal to */
private static NumberEval MATCH_LARGEST_LTE = new NumberEval(1);
private static NumberEval MATCH_EXACT = new NumberEval(0);
/** greater than or equal to */
private static NumberEval MATCH_SMALLEST_GTE = new NumberEval(-1);
private static StringEval MATCH_INVALID = new StringEval("blabla");
private static ValueEval invokeMatch(ValueEval Lookup_value, ValueEval Lookup_array, ValueEval match_type)
{
ValueEval[] args = { Lookup_value, Lookup_array, match_type, };
return new Match().Evaluate(args, -1, (short)-1);
}
private static ValueEval invokeMatch(ValueEval lookup_value, ValueEval lookup_array)
{
ValueEval[] args = { lookup_value, lookup_array, };
return new Match().Evaluate(args, -1, (short)-1);
}
private static void ConfirmInt(int expected, ValueEval actualEval)
{
if (!(actualEval is NumericValueEval))
{
Assert.Fail("Expected numeric result but had " + actualEval);
}
NumericValueEval nve = (NumericValueEval)actualEval;
Assert.AreEqual(expected, nve.NumberValue, 0);
}
[Test]
public void TestSimpleNumber()
{
ValueEval[] values = {
new NumberEval(4),
new NumberEval(5),
new NumberEval(10),
new NumberEval(10),
new NumberEval(25),
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values);
ConfirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE));
ConfirmInt(2, invokeMatch(new NumberEval(5), ae));
ConfirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new NumberEval(10), ae, MATCH_LARGEST_LTE));
ConfirmInt(3, invokeMatch(new NumberEval(10), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new NumberEval(20), ae, MATCH_LARGEST_LTE));
Assert.AreEqual(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT));
}
[Test]
public void TestReversedNumber()
{
ValueEval[] values = {
new NumberEval(25),
new NumberEval(10),
new NumberEval(10),
new NumberEval(10),
new NumberEval(4),
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values);
ConfirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_SMALLEST_GTE));
ConfirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new NumberEval(9), ae, MATCH_SMALLEST_GTE));
ConfirmInt(1, invokeMatch(new NumberEval(20), ae, MATCH_SMALLEST_GTE));
ConfirmInt(5, invokeMatch(new NumberEval(3), ae, MATCH_SMALLEST_GTE));
Assert.AreEqual(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT));
Assert.AreEqual(ErrorEval.NA, invokeMatch(new NumberEval(26), ae, MATCH_SMALLEST_GTE));
}
[Test]
public void TestSimpleString()
{
ValueEval[] values = {
new StringEval("Albert"),
new StringEval("Charles"),
new StringEval("Ed"),
new StringEval("Greg"),
new StringEval("Ian"),
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values);
// Note String comparisons are case insensitive
ConfirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_LARGEST_LTE));
ConfirmInt(3, invokeMatch(new StringEval("eD"), ae, MATCH_LARGEST_LTE));
ConfirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_EXACT));
ConfirmInt(3, invokeMatch(new StringEval("ed"), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE));
Assert.AreEqual(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT));
}
[Test]
public void TestSimpleWildcardValuesString()
{
// Arrange
ValueEval[] values = {
new StringEval("Albert"),
new StringEval("Charles"),
new StringEval("Ed"),
new StringEval("Greg"),
new StringEval("Ian"),
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values);
// Note String comparisons are case insensitive
ConfirmInt(3, invokeMatch(new StringEval("e*"), ae, MATCH_EXACT));
ConfirmInt(3, invokeMatch(new StringEval("*d"), ae, MATCH_EXACT));
ConfirmInt(1, invokeMatch(new StringEval("Al*"), ae, MATCH_EXACT));
ConfirmInt(2, invokeMatch(new StringEval("Char*"), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new StringEval("*eg"), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new StringEval("G?eg"), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new StringEval("??eg"), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new StringEval("G*?eg"), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE));
ConfirmInt(5, invokeMatch(new StringEval("*Ian*"), ae, MATCH_EXACT));
ConfirmInt(5, invokeMatch(new StringEval("*Ian*"), ae, MATCH_LARGEST_LTE));
}
[Test]
public void TestTildeString()
{
ValueEval[] values = {
new StringEval("what?"),
new StringEval("all*")
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A2", values);
ConfirmInt(1, invokeMatch(new StringEval("what~?"), ae, MATCH_EXACT));
ConfirmInt(2, invokeMatch(new StringEval("all~*"), ae, MATCH_EXACT));
}
[Test]
public void TestSimpleBoolean()
{
ValueEval[] values = {
BoolEval.FALSE,
BoolEval.FALSE,
BoolEval.TRUE,
BoolEval.TRUE,
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A4", values);
// Note String comparisons are case insensitive
ConfirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE));
ConfirmInt(1, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE));
ConfirmInt(3, invokeMatch(BoolEval.TRUE, ae, MATCH_EXACT));
}
[Test]
public void TestHeterogeneous()
{
ValueEval[] values = {
new NumberEval(4),
BoolEval.FALSE,
new NumberEval(5),
new StringEval("Albert"),
BoolEval.FALSE,
BoolEval.TRUE,
new NumberEval(10),
new StringEval("Charles"),
new StringEval("Ed"),
new NumberEval(10),
new NumberEval(25),
BoolEval.TRUE,
new StringEval("Ed"),
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A13", values);
Assert.AreEqual(ErrorEval.NA, invokeMatch(new StringEval("Aaron"), ae, MATCH_LARGEST_LTE));
ConfirmInt(5, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE));
ConfirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT));
ConfirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE));
ConfirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_EXACT));
ConfirmInt(8, invokeMatch(new StringEval("CHARLES"), ae, MATCH_EXACT));
ConfirmInt(4, invokeMatch(new StringEval("Ben"), ae, MATCH_LARGEST_LTE));
ConfirmInt(13, invokeMatch(new StringEval("ED"), ae, MATCH_LARGEST_LTE));
ConfirmInt(9, invokeMatch(new StringEval("ED"), ae, MATCH_EXACT));
ConfirmInt(13, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE));
Assert.AreEqual(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT));
ConfirmInt(11, invokeMatch(new NumberEval(30), ae, MATCH_LARGEST_LTE));
ConfirmInt(12, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE));
}
/**
* Ensures that the match_type argument can be an <c>AreaEval</c>.<br/>
* Bugzilla 44421
*/
[Test]
public void TestMatchArgTypeArea()
{
ValueEval[] values = {
new NumberEval(4),
new NumberEval(5),
new NumberEval(10),
new NumberEval(10),
new NumberEval(25),
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values);
AreaEval matchAE = EvalFactory.CreateAreaEval("C1:C1", new ValueEval[] { MATCH_LARGEST_LTE, });
try
{
ConfirmInt(4, invokeMatch(new NumberEval(10), ae, matchAE));
}
catch (Exception e)
{
if (e.Message.StartsWith("Unexpected match_type type"))
{
// identified bug 44421
Assert.Fail(e.Message);
}
// some other error ??
throw e;
}
}
[Test]
public void TestInvalidMatchType()
{
ValueEval[] values = {
new NumberEval(4),
new NumberEval(5),
new NumberEval(10),
new NumberEval(10),
new NumberEval(25),
};
AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values);
ConfirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE));
Assert.AreEqual(ErrorEval.REF_INVALID, invokeMatch(new StringEval("Ben"), ae, MATCH_INVALID), "Should return #REF! for invalid match type");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.