context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Buffers.Tests { public class CtorArrayReadOnlyBuffer { [Fact] public static void CtorArrayInt() { int[] a = { 91, 92, -93, 94 }; ReadOnlyBuffer<int> buffer; buffer = new ReadOnlyBuffer<int>(a); TestHelpers.SequenceEqualValueType(buffer, 91, 92, -93, 94); buffer = new ReadOnlyBuffer<int>(a, 0); TestHelpers.SequenceEqualValueType(buffer, 91, 92, -93, 94); buffer = new ReadOnlyBuffer<int>(a, 0, a.Length); TestHelpers.SequenceEqualValueType(buffer, 91, 92, -93, 94); } [Fact] public static void CtorArrayLong() { long[] a = { 91, -92, 93, 94, -95 }; ReadOnlyBuffer<long> buffer; buffer = new ReadOnlyBuffer<long>(a); TestHelpers.SequenceEqualValueType(buffer, 91, -92, 93, 94, -95); buffer = new ReadOnlyBuffer<long>(a, 0); TestHelpers.SequenceEqualValueType(buffer, 91, -92, 93, 94, -95); buffer = new ReadOnlyBuffer<long>(a, 0, a.Length); TestHelpers.SequenceEqualValueType(buffer, 91, -92, 93, 94, -95); } [Fact] public static void CtorArrayObject() { object o1 = new object(); object o2 = new object(); object[] a = { o1, o2 }; ReadOnlyBuffer<object> buffer; buffer = new ReadOnlyBuffer<object>(a); TestHelpers.SequenceEqual(buffer, o1, o2); buffer = new ReadOnlyBuffer<object>(a, 0); TestHelpers.SequenceEqual(buffer, o1, o2); buffer = new ReadOnlyBuffer<object>(a, 0, a.Length); TestHelpers.SequenceEqual(buffer, o1, o2); } [Fact] public static void CtorArrayZeroLength() { int[] empty = Array.Empty<int>(); ReadOnlyBuffer<int> buffer; buffer = new ReadOnlyBuffer<int>(empty); TestHelpers.SequenceEqualValueType(buffer); buffer = new ReadOnlyBuffer<int>(empty, 0); TestHelpers.SequenceEqualValueType(buffer); buffer = new ReadOnlyBuffer<int>(empty, 0, empty.Length); TestHelpers.SequenceEqualValueType(buffer); } [Fact] public static void CtorArrayNullArray() { Assert.Throws<ArgumentNullException>(() => new ReadOnlyBuffer<int>(null)); Assert.Throws<ArgumentNullException>(() => new ReadOnlyBuffer<int>(null, 0)); Assert.Throws<ArgumentNullException>(() => new ReadOnlyBuffer<int>(null, 0, 0)); } [Fact] public static void CtorArrayWrongValueType() { // Can pass variant array, if array type is a valuetype. uint[] a = { 42u, 0xffffffffu }; int[] aAsIntArray = (int[])(object)a; ReadOnlyBuffer<int> buffer; buffer = new ReadOnlyBuffer<int>(aAsIntArray); TestHelpers.SequenceEqualValueType(buffer, 42, -1); buffer = new ReadOnlyBuffer<int>(aAsIntArray, 0); TestHelpers.SequenceEqualValueType(buffer, 42, -1); buffer = new ReadOnlyBuffer<int>(aAsIntArray, 0, aAsIntArray.Length); TestHelpers.SequenceEqualValueType(buffer, 42, -1); } [Fact] public static void CtorVariantArrayType() { // For ReadOnlyBuffer<T>, variant arrays are allowed for string to object // and reference type to object. ReadOnlyBuffer<object> buffer; string[] strArray = { "Hello" }; buffer = new ReadOnlyBuffer<object>(strArray); TestHelpers.SequenceEqual(buffer, "Hello"); buffer = new ReadOnlyBuffer<object>(strArray, 0); TestHelpers.SequenceEqual(buffer, "Hello"); buffer = new ReadOnlyBuffer<object>(strArray, 0, strArray.Length); TestHelpers.SequenceEqual(buffer, "Hello"); TestHelpers.TestClass c1 = new TestHelpers.TestClass(); TestHelpers.TestClass c2 = new TestHelpers.TestClass(); TestHelpers.TestClass[] clsArray = { c1, c2 }; buffer = new ReadOnlyBuffer<object>(clsArray); TestHelpers.SequenceEqual(buffer, c1, c2); buffer = new ReadOnlyBuffer<object>(clsArray, 0); TestHelpers.SequenceEqual(buffer, c1, c2); buffer = new ReadOnlyBuffer<object>(clsArray, 0, clsArray.Length); TestHelpers.SequenceEqual(buffer, c1, c2); } [Fact] public static void CtorArrayWithStartInt() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; var buffer = new ReadOnlyBuffer<int>(a, 3); TestHelpers.SequenceEqualValueType(buffer, 93, 94, 95, 96, 97, 98); } [Fact] public static void CtorArrayWithStartLong() { long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; var buffer = new ReadOnlyBuffer<long>(a, 3); TestHelpers.SequenceEqualValueType(buffer, 93, 94, 95, 96, 97, 98); } [Fact] public static void CtorArrayWithNegativeStart() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, -1)); } [Fact] public static void CtorArrayWithStartTooLarge() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, 4)); } [Fact] public static void CtorArrayWithStartEqualsLength() { // Valid for start to equal the array length. This returns an empty buffer that starts "just past the array." int[] a = { 91, 92, 93 }; var buffer = new ReadOnlyBuffer<int>(a, 3); TestHelpers.SequenceEqualValueType(buffer); } [Fact] public static void CtorArrayWithStartAndLengthInt() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; var buffer = new ReadOnlyBuffer<int>(a, 3, 2); TestHelpers.SequenceEqualValueType(buffer, 93, 94); } [Fact] public static void CtorArrayWithStartAndLengthLong() { long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; var buffer = new ReadOnlyBuffer<long>(a, 4, 3); TestHelpers.SequenceEqualValueType(buffer, 94, 95, 96); } [Fact] public static void CtorArrayWithStartAndLengthRangeExtendsToEndOfArray() { long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; var buffer = new ReadOnlyBuffer<long>(a, 4, 5); TestHelpers.SequenceEqualValueType(buffer, 94, 95, 96, 97, 98); } [Fact] public static void CtorArrayWithNegativeStartAndLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, -1, 0)); } [Fact] public static void CtorArrayWithStartTooLargeAndLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, 4, 0)); } [Fact] public static void CtorArrayWithStartAndNegativeLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, 0, -1)); } [Fact] public static void CtorArrayWithStartAndLengthTooLarge() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, 3, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, 2, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, 1, 3)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, 0, 4)); Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyBuffer<int>(a, int.MaxValue, int.MaxValue)); } [Fact] public static void CtorArrayWithStartAndLengthBothEqual() { // Valid for start to equal the array length. This returns an empty buffer that starts "just past the array." int[] a = { 91, 92, 93 }; var buffer = new ReadOnlyBuffer<int>(a, 3, 0); TestHelpers.SequenceEqualValueType(buffer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit01.explicit01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit01.explicit01; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(10,39\).*CS1066</Expects> public class Derived { public static explicit operator int (Derived d = null) { if (d != null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); int result = (int)tf; return result; } } //</code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit02.explicit02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit02.explicit02; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(12,41\).*CS1066</Expects> public class Derived { public static explicit operator int (Derived d = default(Derived)) { if (d == null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = null; dynamic tf = p; try { int result = (int)tf; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.ValueCantBeNull, e.Message, "int"); if (ret) return 0; } return 1; } } //</code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit04.explicit04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit04.explicit04; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(11,39\).*CS1066</Expects> public class Derived { private const Derived x = null; public static explicit operator int (Derived d = x) { if (d != null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); int result = (int)tf; return result; } } //</code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit05.explicit05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.explicit05.explicit05; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(11,39\).*CS1066</Expects> public class Derived { private const Derived x = null; public static explicit operator int (Derived d = true ? x : x) { if (d != null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); int result = (int)tf; return result; } } //</code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit01.implicit01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit01.implicit01; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(10,39\).*CS1066</Expects> public class Derived { public static implicit operator int (Derived d = null) { if (d != null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); int result = tf; return result; } } //</code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit02.implicit02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit02.implicit02; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <RelatedBugs></RelatedBugs> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(11,39\).*CS1066</Expects> public class Derived { public static implicit operator int (Derived d = default(Derived)) { if (d == null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived p = null; dynamic tf = p; try { int result = tf; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.ValueCantBeNull, e.Message, "int"); if (ret) return 0; } return 1; } } //</code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit04.implicit04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit04.implicit04; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(11,39\).*CS1066</Expects> public class Derived { private const Derived x = null; public static implicit operator int (Derived d = x) { if (d != null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); int result = tf; return result; } } //</code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit05.implicit05 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.opOverload.implicit05.implicit05; // <Area>Declaration of Optional Params</Area> // <Title> Explicit User defined conversions</Title> // <Description>User-defined conversions with defaults</Description> // <Expects status=success></Expects> // <Code> //<Expects Status=warning>\(11,39\).*CS1066</Expects> public class Derived { private const Derived x = null; public static implicit operator int (Derived d = true ? x : x) { if (d != null) return 0; return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); int result = tf; return result; } } //</code> }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using FunWithPostgres.Data; namespace FunWithPostgres.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.2"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("FunWithPostgres.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("FunWithPostgres.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("FunWithPostgres.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("FunWithPostgres.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
#if !NOT_UNITY3D using System; using System.Collections.Generic; using System.Linq; using ModestTree; using UnityEngine; using UnityEngine.Serialization; using Zenject.Internal; #if UNITY_EDITOR using UnityEditor; #endif namespace Zenject { public abstract class Context : MonoBehaviour { [FormerlySerializedAs("Installers")] [SerializeField] List<MonoInstaller> _installers = new List<MonoInstaller>(); [SerializeField] List<MonoInstaller> _installerPrefabs = new List<MonoInstaller>(); [SerializeField] List<ScriptableObjectInstaller> _scriptableObjectInstallers = new List<ScriptableObjectInstaller>(); List<InstallerBase> _normalInstallers = new List<InstallerBase>(); List<Type> _normalInstallerTypes = new List<Type>(); public IEnumerable<MonoInstaller> Installers { get { return _installers; } set { _installers.Clear(); _installers.AddRange(value); } } public IEnumerable<MonoInstaller> InstallerPrefabs { get { return _installerPrefabs; } set { _installerPrefabs.Clear(); _installerPrefabs.AddRange(value); } } public IEnumerable<ScriptableObjectInstaller> ScriptableObjectInstallers { get { return _scriptableObjectInstallers; } set { _scriptableObjectInstallers.Clear(); _scriptableObjectInstallers.AddRange(value); } } // Unlike other installer types this has to be set through code public IEnumerable<Type> NormalInstallerTypes { get { return _normalInstallerTypes; } set { Assert.That(value.All(x => x != null && x.DerivesFrom<InstallerBase>())); _normalInstallerTypes.Clear(); _normalInstallerTypes.AddRange(value); } } // Unlike other installer types this has to be set through code public IEnumerable<InstallerBase> NormalInstallers { get { return _normalInstallers; } set { _normalInstallers.Clear(); _normalInstallers.AddRange(value); } } public abstract DiContainer Container { get; } public abstract IEnumerable<GameObject> GetRootGameObjects(); public void AddNormalInstallerType(Type installerType) { Assert.IsNotNull(installerType); Assert.That(installerType.DerivesFrom<InstallerBase>()); _normalInstallerTypes.Add(installerType); } public void AddNormalInstaller(InstallerBase installer) { _normalInstallers.Add(installer); } void CheckInstallerPrefabTypes(List<MonoInstaller> installers, List<MonoInstaller> installerPrefabs) { foreach (var installer in installers) { Assert.IsNotNull(installer, "Found null installer in Context '{0}'", this.name); #if UNITY_EDITOR Assert.That(PrefabUtility.GetPrefabType(installer.gameObject) != PrefabType.Prefab, "Found prefab with name '{0}' in the Installer property of Context '{1}'. You should use the property 'InstallerPrefabs' for this instead.", installer.name, this.name); #endif } foreach (var installerPrefab in installerPrefabs) { Assert.IsNotNull(installerPrefab, "Found null prefab in Context"); #if UNITY_EDITOR Assert.That(PrefabUtility.GetPrefabType(installerPrefab.gameObject) == PrefabType.Prefab, "Found non-prefab with name '{0}' in the InstallerPrefabs property of Context '{1}'. You should use the property 'Installer' for this instead", installerPrefab.name, this.name); #endif Assert.That(installerPrefab.GetComponent<MonoInstaller>() != null, "Expected to find component with type 'MonoInstaller' on given installer prefab '{0}'", installerPrefab.name); } } protected void InstallInstallers() { InstallInstallers( _normalInstallers, _normalInstallerTypes, _scriptableObjectInstallers, _installers, _installerPrefabs); } protected void InstallInstallers( List<InstallerBase> normalInstallers, List<Type> normalInstallerTypes, List<ScriptableObjectInstaller> scriptableObjectInstallers, List<MonoInstaller> installers, List<MonoInstaller> installerPrefabs) { CheckInstallerPrefabTypes(installers, installerPrefabs); // Ideally we would just have one flat list of all the installers // since that way the user has complete control over the order, but // that's not possible since Unity does not allow serializing lists of interfaces // (and it has to be an inteface since the scriptable object installers only share // the interface) // // So the best we can do is have a hard-coded order in terms of the installer type // // The order is: // - Normal installers given directly via code // - ScriptableObject installers // - MonoInstallers in the scene // - Prefab Installers // // We put ScriptableObject installers before the MonoInstallers because // ScriptableObjectInstallers are often used for settings (including settings // that are injected into other installers like MonoInstallers) var allInstallers = normalInstallers.Cast<IInstaller>() .Concat(scriptableObjectInstallers.Cast<IInstaller>()) .Concat(installers.Cast<IInstaller>()).ToList(); foreach (var installerPrefab in installerPrefabs) { Assert.IsNotNull(installerPrefab, "Found null installer prefab in '{0}'", this.GetType()); var installerGameObject = GameObject.Instantiate(installerPrefab.gameObject); installerGameObject.transform.SetParent(this.transform, false); var installer = installerGameObject.GetComponent<MonoInstaller>(); Assert.IsNotNull(installer, "Could not find installer component on prefab '{0}'", installerPrefab.name); allInstallers.Add(installer); } foreach (var installerType in normalInstallerTypes) { ((InstallerBase)Container.Instantiate(installerType)).InstallBindings(); } foreach (var installer in allInstallers) { Assert.IsNotNull(installer, "Found null installer in '{0}'", this.GetType()); Container.Inject(installer); installer.InstallBindings(); } } protected void InstallSceneBindings(List<MonoBehaviour> injectableMonoBehaviours) { foreach (var binding in injectableMonoBehaviours.OfType<ZenjectBinding>()) { if (binding == null) { continue; } if (binding.Context == null) { InstallZenjectBinding(binding); } } // We'd prefer to use GameObject.FindObjectsOfType<ZenjectBinding>() here // instead but that doesn't find inactive gameobjects // TODO: Consider changing this // Maybe ZenjectBinding could add itself to a registry class on Awake/OnEnable // then we could avoid calling the slow Resources.FindObjectsOfTypeAll here foreach (var binding in Resources.FindObjectsOfTypeAll<ZenjectBinding>()) { if (binding == null) { continue; } if (binding.Context == this) { InstallZenjectBinding(binding); } } } void InstallZenjectBinding(ZenjectBinding binding) { if (!binding.enabled) { return; } if (binding.Components == null || binding.Components.IsEmpty()) { ModestTree.Log.Warn("Found empty list of components on ZenjectBinding on object '{0}'", binding.name); return; } string identifier = null; if (binding.Identifier.Trim().Length > 0) { identifier = binding.Identifier; } foreach (var component in binding.Components) { var bindType = binding.BindType; if (component == null) { ModestTree.Log.Warn("Found null component in ZenjectBinding on object '{0}'", binding.name); continue; } var componentType = component.GetType(); switch (bindType) { case ZenjectBinding.BindTypes.Self: { Container.Bind(componentType).WithId(identifier).FromInstance(component); break; } case ZenjectBinding.BindTypes.BaseType: { Container.Bind(componentType.BaseType()).WithId(identifier).FromInstance(component); break; } case ZenjectBinding.BindTypes.AllInterfaces: { Container.Bind(componentType.Interfaces().ToArray()).WithId(identifier).FromInstance(component); break; } case ZenjectBinding.BindTypes.AllInterfacesAndSelf: { Container.Bind(componentType.Interfaces().Concat(new[] { componentType }).ToArray()).WithId(identifier).FromInstance(component); break; } default: { throw Assert.CreateException(); } } } } protected abstract void GetInjectableMonoBehaviours(List<MonoBehaviour> components); } } #endif
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Text; using System.Web; using AjaxPro; using ASC.Core; using ASC.Notify.Model; using ASC.Notify.Recipients; using ASC.Web.Community.Modules.Blogs.Core.Resources; using ASC.Web.Community.Resources; using ASC.Web.Studio.Utility; namespace ASC.Web.Community.Blogs { [AjaxNamespace("Subscriber")] public class Subscriber { private readonly ISubscriptionProvider _subscriptionProvider; private readonly IRecipientProvider _recipientProvider; public IDirectRecipient IAmAsRecipient { get { return (IDirectRecipient)_recipientProvider.GetRecipient(SecurityContext.CurrentAccount.ID.ToString()); } } public Subscriber() { var engine = BasePage.GetEngine(); _subscriptionProvider = engine.NotifySource.GetSubscriptionProvider(); _recipientProvider = engine.NotifySource.GetRecipientsProvider(); } #region Comments [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeOnComments(Guid postID, int statusNotify) { var resp = new AjaxResponse(); try { if (statusNotify == 1) { _subscriptionProvider.Subscribe( ASC.Blogs.Core.Constants.NewComment, postID.ToString(), IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderCommentsSubscription(false, postID); } else { _subscriptionProvider.UnSubscribe( ASC.Blogs.Core.Constants.NewComment, postID.ToString(), IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderCommentsSubscription(true, postID); } } catch (Exception e) { resp.rs1 = "0"; resp.rs2 = HttpUtility.HtmlEncode(e.Message); } return resp; } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeOnBlogComments(Guid postID, int statusNotify) { var resp = new AjaxResponse(); try { if (statusNotify == 1) { _subscriptionProvider.Subscribe( ASC.Blogs.Core.Constants.NewComment, postID.ToString(), IAmAsRecipient ); resp.rs1 = "0"; resp.rs2 = RenderCommentsSubscriptionLink(false, postID); resp.rs3 = String.Format("({0})", CommunityResource.Subscribed.ToLower()); } else { _subscriptionProvider.UnSubscribe( ASC.Blogs.Core.Constants.NewComment, postID.ToString(), IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderCommentsSubscriptionLink(true, postID); resp.rs3 = ""; } } catch (Exception e) { resp.rs1 = "0"; resp.rs2 = HttpUtility.HtmlEncode(e.Message); } return resp; } public string RenderCommentsSubscription(bool isSubscribe, Guid postID) { var sb = new StringBuilder(); sb.Append("<div id=\"blogs_subcribeOnCommentsBox\">"); sb.AppendFormat("<a class='linkAction' title='{3}' href=\"#\" onclick=\"BlogSubscriber.SubscribeOnComments('{0}', {1}); return false;\">{2}</a>", postID, (isSubscribe ? 1 : 0), (!isSubscribe ? BlogsResource.UnSubscribeOnNewCommentsAction : BlogsResource.SubscribeOnNewCommentsAction), BlogsResource.SubscribeOnNewCommentsDescription); sb.Append("</div>"); return sb.ToString(); } public string RenderCommentsSubscriptionLink(bool isSubscribe, Guid postID) { var sb = new StringBuilder(); sb.AppendFormat("<a id=\"statusSubscribe\" class=\"" + (!isSubscribe ? "subscribed" : "unsubscribed") + " follow-status\" title=\"{2}\" href=\"#\" onclick=\"BlogSubscriber.SubscribeOnBlogComments('{0}', {1}, this); return false;\"></a>", postID, (isSubscribe ? 1 : 0), (!isSubscribe ? BlogsResource.UnSubscribeOnNewCommentsAction : BlogsResource.SubscribeOnNewCommentsAction) ); return sb.ToString(); } public bool IsCommentsSubscribe(Guid postID) { return _subscriptionProvider.IsSubscribed( ASC.Blogs.Core.Constants.NewComment, IAmAsRecipient, postID.ToString()); } #endregion #region PersonalBlog [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeOnPersonalBlog(Guid userID, int statusNotify) { var resp = new AjaxResponse(); try { if (statusNotify == 1) { _subscriptionProvider.Subscribe( ASC.Blogs.Core.Constants.NewPostByAuthor, userID.ToString(), IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderPersonalBlogSubscription(false, userID); } else { _subscriptionProvider.UnSubscribe( ASC.Blogs.Core.Constants.NewPostByAuthor, userID.ToString(), IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderPersonalBlogSubscription(true, userID); } } catch (Exception e) { resp.rs1 = "0"; resp.rs2 = HttpUtility.HtmlEncode(e.Message); } return resp; } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribePersonalBlog(Guid userID, int statusNotify) { var resp = new AjaxResponse(); try { if (statusNotify == 1) { _subscriptionProvider.Subscribe( ASC.Blogs.Core.Constants.NewPostByAuthor, userID.ToString(), IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderPersonalBlogSubscriptionLink(false, userID); } else { _subscriptionProvider.UnSubscribe( ASC.Blogs.Core.Constants.NewPostByAuthor, userID.ToString(), IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderPersonalBlogSubscriptionLink(true, userID); } } catch (Exception e) { resp.rs1 = "0"; resp.rs2 = HttpUtility.HtmlEncode(e.Message); } return resp; } public string RenderPersonalBlogSubscription(bool isSubscribe, Guid userID) { var sb = new StringBuilder(); sb.Append("<div id=\"blogs_subcribeOnPersonalBlogBox\">"); sb.AppendFormat("<a class='linkAction' title='{3}' href=\"#\" onclick=\"BlogSubscriber.SubscribeOnPersonalBlog('{0}', {1}); return false;\">{2}</a>", userID, (isSubscribe ? 1 : 0), (!isSubscribe ? BlogsResource.UnSubscribeOnAuthorAction : BlogsResource.SubscribeOnAuthorAction), BlogsResource.SubscribeOnAuthorDescription); sb.Append("</div>"); return sb.ToString(); } public string RenderPersonalBlogSubscriptionLink(bool isSubscribe, Guid userID) { var sb = new StringBuilder(); sb.AppendFormat("<li><a class='dropdown-item' title='{3}' href=\"#\" onclick=\"BlogSubscriber.SubscribePersonalBlog('{0}', {1}, this); return false;\">{2}</a></li>", userID, (isSubscribe ? 1 : 0), (!isSubscribe ? BlogsResource.UnSubscribeOnAuthorAction : BlogsResource.SubscribeOnAuthorAction), BlogsResource.SubscribeOnAuthorDescription); return sb.ToString(); } public bool IsPersonalBlogSubscribe(Guid userID) { return _subscriptionProvider.IsSubscribed( ASC.Blogs.Core.Constants.NewPostByAuthor, IAmAsRecipient, userID.ToString()); } #endregion #region NewPosts [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public AjaxResponse SubscribeOnNewPosts(int statusNotify) { var resp = new AjaxResponse(); try { if (statusNotify == 1) { _subscriptionProvider.Subscribe( ASC.Blogs.Core.Constants.NewPost, null, IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderNewPostsSubscription(false); } else { _subscriptionProvider.UnSubscribe( ASC.Blogs.Core.Constants.NewPost, null, IAmAsRecipient ); resp.rs1 = "1"; resp.rs2 = RenderNewPostsSubscription(true); } } catch (Exception e) { resp.rs1 = "0"; resp.rs2 = HttpUtility.HtmlEncode(e.Message); } return resp; } public string RenderNewPostsSubscription(bool isSubscribe) { var sb = new StringBuilder(); sb.Append("<div id=\"blogs_subcribeOnNewPostsBox\">"); sb.AppendFormat("<a class='linkAction' title='{2}' href=\"#\" onclick=\"BlogSubscriber.SubscribeOnNewPosts({0}); return false;\">{1}</a>", (isSubscribe ? 1 : 0), (!isSubscribe ? BlogsResource.UnSubscribeOnNewPostAction : BlogsResource.SubscribeOnNewPostAction), BlogsResource.SubscribeOnNewPostDescription); sb.Append("</div>"); return sb.ToString(); } public bool IsNewPostsSubscribe() { return _subscriptionProvider.IsSubscribed( ASC.Blogs.Core.Constants.NewPost, IAmAsRecipient, null); } #endregion } }
namespace Ads.Web.Areas.HelpPage.ModelDescriptions { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> annotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return string.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return string.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return string.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return string.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { var dataType = (DataTypeAttribute)a; return string.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { var regularExpression = (RegularExpressionAttribute)a; return string.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> defaultTypeDocumentation = new Dictionary<Type, string> { { typeof(short), "integer" }, { typeof(int), "integer" }, { typeof(long), "integer" }, { typeof(ushort), "unsigned integer" }, { typeof(uint), "unsigned integer" }, { typeof(ulong), "unsigned integer" }, { typeof(byte), "byte" }, { typeof(char), "character" }, { typeof(sbyte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(float), "decimal number" }, { typeof(double), "decimal number" }, { typeof(decimal), "decimal number" }, { typeof(string), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(bool), "boolean" }, }; private readonly Lazy<IModelDocumentationProvider> documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } this.documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); this.GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return this.documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (this.GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (this.defaultTypeDocumentation.ContainsKey(modelType)) { return this.GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return this.GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return this.GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return this.GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return this.GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return this.GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return this.GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return this.GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return this.GenerateCollectionModelDescription(modelType, typeof(object)); } return this.GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { var jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !string.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { var dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !string.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { var jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); var xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); var ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); var nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); var apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (this.defaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (this.DocumentationProvider != null) { documentation = this.DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { var annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (this.annotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return string.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = this.GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { var complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = this.CreateDefaultDocumentation(modelType) }; this.GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); var hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; var properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { var propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (this.DocumentationProvider != null) { propertyModel.Documentation = this.DocumentationProvider.GetDocumentation(property); } this.GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = this.GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { var propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (this.DocumentationProvider != null) { propertyModel.Documentation = this.DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = this.GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = this.GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = this.GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { var enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = this.CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { var enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (this.DocumentationProvider != null) { enumValue.Documentation = this.DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } this.GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = this.GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = this.GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { var simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = this.CreateDefaultDocumentation(modelType) }; this.GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; using FreeEverything.Annotations; namespace FreeEverything { public sealed class GarbageCan : INotifyPropertyChanged { private readonly ObservableCollection<Garbage> m_GarbageList = new ObservableCollection<Garbage>(); private Filter m_SelectedFilter; private string m_FilterName; private string m_FilterRegular; private string m_FilterInclude; private string m_FilterExclude; private bool m_FilterContainFile; private bool m_FilterContainContainDirectory; public GarbageCan() { FilterList = new ObservableCollection<Filter>(); } public ObservableCollection<Filter> FilterList { get; private set; } [System.Xml.Serialization.XmlIgnore] public Filter SelectedFilter { get { return m_SelectedFilter; } set { if (value != null && value != m_SelectedFilter) { m_SelectedFilter = value; OnPropertyChanged("SelectedFilter"); m_FilterName = m_SelectedFilter.Name; OnPropertyChanged("FilterName"); m_FilterRegular = m_SelectedFilter.RegularExpression; OnPropertyChanged("FilterRegular"); m_FilterInclude = m_SelectedFilter.Include; OnPropertyChanged("FilterInclude"); m_FilterExclude = m_SelectedFilter.Exclude; OnPropertyChanged("FilterExclude"); m_FilterContainFile = m_SelectedFilter.ContainFile; OnPropertyChanged("FilterContainFile"); m_FilterContainContainDirectory = m_SelectedFilter.ContainDirectory; OnPropertyChanged("FilterContainDirectory"); } } } [System.Xml.Serialization.XmlIgnore] public bool FilterContainDirectory { get { return m_FilterContainContainDirectory; } set { m_FilterContainContainDirectory = value; m_SelectedFilter.ContainDirectory = m_FilterContainContainDirectory; } } [System.Xml.Serialization.XmlIgnore] public bool FilterContainFile { get { return m_FilterContainFile; } set { m_FilterContainFile = value; m_SelectedFilter.ContainFile = m_FilterContainFile; } } [System.Xml.Serialization.XmlIgnore] public string FilterExclude { get { return m_FilterExclude; } set { m_FilterExclude = value; m_SelectedFilter.Exclude = m_FilterExclude; } } [System.Xml.Serialization.XmlIgnore] public string FilterInclude { get { return m_FilterInclude; } set { m_FilterInclude = value; m_SelectedFilter.Include = m_FilterInclude; } } [System.Xml.Serialization.XmlIgnore] public string FilterRegular { get { return m_FilterRegular; } set { m_FilterRegular = value; m_SelectedFilter.RegularExpression = m_FilterRegular; } } [System.Xml.Serialization.XmlIgnore] public string FilterName { get { return m_FilterName; } set { m_FilterName = value; m_SelectedFilter.Name = m_FilterName; OnPropertyChanged("FilterList"); OnPropertyChanged("SelectedFilter"); } } [System.Xml.Serialization.XmlIgnore] public ObservableCollection<Garbage> GarbageList { get { return m_GarbageList; } } [System.Xml.Serialization.XmlIgnore] public int GarbageCount { get { return m_GarbageList.Count; } } public async void Scan() { try { Progress = 0; OnPropertyChanged("Progress"); startTimer(); GarbageList.Clear(); OnPropertyChanged("GarbageCount"); int round = 100 / FilterList.Count; foreach (var filter in FilterList) { if (filter.IsChecked) { filter.Waiting = Visibility.Visible; List<Garbage> result = await Task<List<Garbage>>.Factory.StartNew(()=>ScanByEverything(filter)); foreach (var garbage in result) { GarbageList.Add(garbage); } OnPropertyChanged("GarbageList"); OnPropertyChanged("GarbageCount"); filter.Waiting = Visibility.Collapsed; Progress += round; OnPropertyChanged("Progress"); } } Progress = 100; OnPropertyChanged("Progress"); } finally { stopTimer(); } } private List<Garbage> ScanByEverything(Filter filter) { List<Garbage> result = new List<Garbage>(); EverythingWraper.Everything_SetRegex(true); EverythingWraper.Everything_SetSearch(filter.RegularExpression); EverythingWraper.Everything_Query(true); // sort by path EverythingWraper.Everything_SortResultsByPath(); int bufsize = 260; StringBuilder buf = new StringBuilder(bufsize); // loop through the results, adding each result to the list box. int totalNumber = EverythingWraper.Everything_GetNumResults(); for (int i = 0; i < totalNumber; i++) { if (EverythingWraper.Everything_IsFolderResult(i) && !filter.ContainDirectory) { continue; } if (EverythingWraper.Everything_IsFileResult(i) && !filter.ContainFile) { continue; } EverythingWraper.Everything_GetResultFullPathName(i, buf, bufsize); string path = buf.ToString(); if (filter.ShouldSkip(path)) { continue; } Garbage garbage = new Garbage(path); result.Add(garbage); } return result; } public void CalculateSize() { List<Task> tasks = new List<Task>(); foreach (var garbage in GarbageList) { tasks.Add(Task.Factory.StartNew(() => garbage.CalculateSize())); } Task.WaitAll(tasks.ToArray()); double size = 0; foreach (var garbage in GarbageList) { size += garbage.Size >= 0 ? garbage.Size : 0; } TotalSize = FileHandler.GetSizeString(size); OnPropertyChanged("TotalSize"); OnPropertyChanged("GarbageList"); } [System.Xml.Serialization.XmlIgnore] public string TotalSize { get; private set; } public void Free() { List<string> toDelete = new List<string>(); for (int i = GarbageList.Count-1; i >= 0; i--) { if(GarbageList[i].IsChecked) { toDelete.Add(GarbageList[i].Path); } } Parallel.ForEach(toDelete, FileHandler.DeletePath); GarbageList.Clear(); } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } [System.Xml.Serialization.XmlIgnore] public int Progress { get; private set; } [System.Xml.Serialization.XmlIgnore] public string ElapseTime { get; private set; } private void startTimer() { m_Timer = new DispatcherTimer(); m_Timer.Tick += updateElapseTime; m_Timer.Interval = new TimeSpan(0, 0, 0, 0, 1); m_StopWatch = new Stopwatch(); m_StopWatch.Start(); m_Timer.Start(); } private void stopTimer() { m_Timer.Tick -= updateElapseTime; m_Timer.Stop(); m_StopWatch.Stop(); } private Stopwatch m_StopWatch; private DispatcherTimer m_Timer; private void updateElapseTime(object sender, EventArgs e) { ElapseTime = m_StopWatch.Elapsed.TotalSeconds.ToString("F2"); OnPropertyChanged("ElapseTime"); } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Jovian.Compiler { class LocalizationCompiler { private List<string> LocalizationKeys; private string Code; public LocalizationCompiler(string code, List<string> lKeys) { LocalizationKeys = lKeys; Code = code; } public void AddKey(string x) { if (!LocalizationKeys.Contains(x)) { LocalizationKeys.Add(x); } } public string CleanTxt(string x) { string y = x; for(int k = 0; k < 256; k++) { y = y.Replace("" + (char)13, ""); y = y.Replace("" + (char)10, " "); y = y.Replace(" ", " "); } return y; } public string htmlEXTRACT(string html,string param) { string srch = param + "="; int k = html.IndexOf(srch); if (k >= 0) { string head = html.Substring(k + srch.Length); if (head.Length > 0) { if (head[0] == '"') { int s = 1; int k2 = head.IndexOf('"', s); bool Good = true; while (k2 >= 0 && Good) { int k3 = System.Math.Min(head.IndexOf("!>"),head.IndexOf("*>")); int k4 = System.Math.Min(head.IndexOf("@>"),head.IndexOf("^>")); int k5 = System.Math.Min(System.Math.Min(k3,k4),head.IndexOf("=>")); if (k5 > k2) { s = k5 + 2; k2 = head.IndexOf('"', s); Good = true; } else { Good = false; } } if (Good) { throw new Exception("Encoder Error"); } else { return srch + head.Substring(0,k2 + 1); } } return ""; } else { return ""; } } else { return ""; } } public string valueEXTRACT(string pair) { int k = pair.IndexOf('"'); string r = pair.Substring(k + 1); return r.Substring(0, r.Length - 1); } public string runHTML(string htmlTag) { //Jovian.CascadePro.Just.Check(".InlineStyle {" string rez = htmlTag; string paramSTYLE = htmlEXTRACT(rez, "style"); if (paramSTYLE.Length > 0) { } string paramTITLE = htmlEXTRACT(rez, "title"); if (paramTITLE.Length > 0) { string Interior = "param=\"" + RewriteEncoderLanguage(valueEXTRACT(paramTITLE), LocalizationKeys) + "\""; rez = rez.Replace(paramTITLE, Interior); } return rez; } public bool isSymbolic(string x) { for(int k = 0; k < x.Length; k++) if(Char.IsLetterOrDigit(x[k])) return false; return true; } public string run() { string L = Code; string O = ""; int kFirstAngle = L.IndexOf("<"); while (kFirstAngle >= 0) { if (kFirstAngle > 0) { string Txt = L.Substring(0, kFirstAngle); string TxtT = CleanTxt(Txt.Trim()); if (TxtT.Length > 0) { int PadLeft = Txt.IndexOf(TxtT); int PadRight = Txt.Length - PadLeft - TxtT.Length; if (PadLeft > 0) O += " "; AddKey(TxtT); PadLeft = System.Math.Min(PadLeft, 1); PadRight = System.Math.Min(PadRight, 1); if (isSymbolic(TxtT)) { O += TxtT; } else { O += "<! LANG('" + TxtT.Replace("'", "\\'").Replace("{","") + "') !>"; } if (PadRight > 0) O += " "; } else { if(Txt.Length > 0) O += " "; } L = L.Substring(kFirstAngle); } kFirstAngle = 0; if (L.Length > 1) { char SecondLetter = L[1]; if (SecondLetter == '!' || SecondLetter == '@' || SecondLetter == '*' || SecondLetter == '^') { int kEndFirstAngle = L.IndexOf("" + SecondLetter + ">"); if (kEndFirstAngle >= 0) { string encCode = L.Substring(0, kEndFirstAngle + 2); O += encCode; L = L.Substring(kEndFirstAngle + 2); } else { throw new Exception("Encoder Lang Problem"); } } else { int endFirstAngle = L.IndexOf(">"); char PriorLetter = L[endFirstAngle - 1]; while ((PriorLetter == '!' || PriorLetter == '@' || PriorLetter == '*' || PriorLetter == '^' || PriorLetter == '=') && endFirstAngle >= 0) { endFirstAngle = L.IndexOf(">",endFirstAngle+1); PriorLetter = L[endFirstAngle - 1]; } if (endFirstAngle >= 0) { string HTML = L.Substring(0, endFirstAngle + 1); O += runHTML(HTML); L = L.Substring(endFirstAngle + 1); } else { throw new Exception("Encoder Lang Problem"); } } } else { throw new Exception("Encoder Lang Problem, start brace and not enough follow threw"); } kFirstAngle = L.IndexOf("<"); } if (L.Length > 0) { string Txt = L; string TxtT = CleanTxt(Txt.Trim()); if (TxtT.Length > 0) { int PadLeft = Txt.IndexOf(TxtT); int PadRight = Txt.Length - PadLeft - TxtT.Length; PadLeft = System.Math.Min(PadLeft, 1); PadRight = System.Math.Min(PadRight, 1); for (int k = 0; k < PadLeft; k++) O += " "; AddKey(TxtT); if (isSymbolic(TxtT)) { O += TxtT; } else { O += "<! LANG('" + TxtT.Replace("'", "\\'").Replace("{","") + "') !>"; ; } for (int k = 0; k < PadRight; k++) O += " "; } else { if(Txt.Length > 0) O += " "; } } return O; } public static string RewriteEncoderLanguage(string code, List<string> LocalizationKeys) { return (new LocalizationCompiler(code, LocalizationKeys)).run(); } /* public static string RewriteTooltip(string tooltip, List<string> LocalizationKeys) { int k = tooltip.IndexOf("|"); if (k >= 0) { return new LocalizationCompiler(tooltip.Substring(0, k), LocalizationKeys).run()+ "|" + (new LocalizationCompiler(tooltip.Substring(k + 1), LocalizationKeys)).run(); } else { return (new LocalizationCompiler(tooltip, LocalizationKeys)).run(); } } */ } }
// // System.Web.Security.MembershipUser // // Authors: // Ben Maurer (bmaurer@users.sourceforge.net) // // (C) 2003 Ben Maurer // // // 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. // #if NET_2_0 namespace System.Web.Security { [Serializable] public class MembershipUser { string providerName; string name; object providerUserKey; string email; string passwordQuestion; string comment; bool isApproved; bool isLockedOut; DateTime creationDate; DateTime lastLoginDate; DateTime lastActivityDate; DateTime lastPasswordChangedDate; DateTime lastLockoutDate; protected MembershipUser () { } public MembershipUser (string providerName, string name, object providerUserKey, string email, string passwordQuestion, string comment, bool isApproved, bool isLockedOut, DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate, DateTime lastPasswordChangedDate, DateTime lastLockoutDate) { this.providerName = providerName; this.name = name; this.providerUserKey = providerUserKey; this.email = email; this.passwordQuestion = passwordQuestion; this.comment = comment; this.isApproved = isApproved; this.isLockedOut = isLockedOut; this.creationDate = creationDate; this.lastLoginDate = lastLoginDate; this.lastActivityDate = lastActivityDate; this.lastPasswordChangedDate = lastPasswordChangedDate; this.lastLockoutDate = lastLockoutDate; } public virtual bool ChangePassword (string oldPassword, string newPassword) { bool success = Provider.ChangePassword (UserName, oldPassword, newPassword); if (success) lastPasswordChangedDate = DateTime.Now; return success; } public virtual bool ChangePasswordQuestionAndAnswer (string password, string newPasswordQuestion, string newPasswordAnswer) { bool success = Provider.ChangePasswordQuestionAndAnswer (UserName, password, newPasswordQuestion, newPasswordAnswer); if (success) passwordQuestion = newPasswordQuestion; return success; } public virtual string GetPassword () { return GetPassword (null); } public virtual string GetPassword (string answer) { return Provider.GetPassword (UserName, answer); } public virtual string ResetPassword () { return ResetPassword (null); } public virtual string ResetPassword (string answer) { string newPass = Provider.ResetPassword (UserName, answer); if (newPass != null) lastPasswordChangedDate = DateTime.Now; return newPass; } public virtual string Comment { get { return comment; } set { comment = value; } } public virtual DateTime CreationDate { get { return creationDate; } } public virtual string Email { get { return email; } set { email = value; } } public virtual bool IsApproved { get { return isApproved; } set { isApproved = value; } } public virtual bool IsLockedOut { get { return isLockedOut; } } public bool IsOnline { get { return LastActivityDate > DateTime.Now - TimeSpan.FromMinutes (Membership.UserIsOnlineTimeWindow); } } public virtual DateTime LastActivityDate { get { return lastActivityDate; } set { lastActivityDate = value; } } public virtual DateTime LastLoginDate { get { return lastLoginDate; } set { lastLoginDate = value; } } public virtual DateTime LastPasswordChangedDate { get { return lastPasswordChangedDate; } } public virtual DateTime LastLockoutDate { get { return lastLockoutDate; } } public virtual string PasswordQuestion { get { return passwordQuestion; } } public virtual string ProviderName { get { return providerName; } } public virtual string UserName { get { return name; } } public virtual object ProviderUserKey { get { return providerUserKey; } } public override string ToString () { return UserName; } public virtual bool UnlockUser () { if (Provider.UnlockUser (UserName)) { isLockedOut = false; return true; } return false; } MembershipProvider Provider { get { MembershipProvider p = Membership.Providers [ProviderName]; if (p == null) throw new InvalidOperationException ("Membership provider '" + ProviderName + "' not found."); return p; } } } } #endif
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Threading.Tasks; namespace Quartz.Examples.Example13 { /// <summary> /// This example will demonstrate the clustering features of AdoJobStore. /// </summary> /// <remarks> /// /// <para> /// All instances MUST use a different properties file, because their instance /// Ids must be different, however all other properties should be the same. /// </para> /// /// <para> /// If you want it to clear out existing jobs & triggers, pass a command-line /// argument called "clearJobs". /// </para> /// /// <para> /// You should probably start with a "fresh" set of tables (assuming you may /// have some data lingering in it from other tests), since mixing data from a /// non-clustered setup with a clustered one can be bad. /// </para> /// /// <para> /// Try killing one of the cluster instances while they are running, and see /// that the remaining instance(s) recover the in-progress jobs. Note that /// detection of the failure may take up to 15 or so seconds with the default /// settings. /// </para> /// /// <para> /// Also try running it with/without the shutdown-hook plugin registered with /// the scheduler. (quartz.plugins.management.ShutdownHookPlugin). /// </para> /// /// <para> /// <i>Note:</i> Never run clustering on separate machines, unless their /// clocks are synchronized using some form of time-sync service (daemon). /// </para> /// </remarks> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> public class ClusteringJobsExecutionExample : IExample { public virtual async Task Run(bool inClearJobs, bool inScheduleJobs) { // First we must get a reference to a scheduler IScheduler sched = await SchedulerBuilder.Create() .WithId("instance_one") .WithName("TestScheduler") .UseDefaultThreadPool(x => x.MaxConcurrency = 5) .WithMisfireThreshold(TimeSpan.FromSeconds(60)) .UsePersistentStore(x => { x.UseProperties = true; x.UseClustering(); x.UseSqlServer(TestConstants.SqlServerConnectionString); x.UseJsonSerializer(); }) .BuildScheduler(); // if running SQLite we need this // properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz"; if (inClearJobs) { Console.WriteLine("***** Deleting existing jobs/triggers *****"); await sched.Clear(); } Console.WriteLine("------- Initialization Complete -----------"); if (inScheduleJobs) { Console.WriteLine("------- Scheduling Jobs ------------------"); string schedId = sched.SchedulerInstanceId; int count = 1; IJobDetail job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); Console.WriteLine("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds); count++; job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(2, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create<SimpleRecoveryStatefulJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(3))) .Build(); Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(4))) .Build(); Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create<SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromMilliseconds(4500))) .Build(); Console.WriteLine($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}"); await sched.ScheduleJob(job, trigger); } // jobs don't start firing until start() has been called... Console.WriteLine("------- Starting Scheduler ---------------"); await sched.Start(); Console.WriteLine("------- Started Scheduler ----------------"); Console.WriteLine("------- Waiting for one hour... ----------"); await Task.Delay(TimeSpan.FromHours(1)); Console.WriteLine("------- Shutting Down --------------------"); await sched.Shutdown(); Console.WriteLine("------- Shutdown Complete ----------------"); } public Task Run() { bool clearJobs = true; bool scheduleJobs = true; /* TODO for (int i = 0; i < args.Length; i++) { if (args[i].ToUpper().Equals("clearJobs".ToUpper())) { clearJobs = true; } else if (args[i].ToUpper().Equals("dontScheduleJobs".ToUpper())) { scheduleJobs = false; } } */ ClusteringJobsExecutionExample example = new ClusteringJobsExecutionExample(); return example.Run(clearJobs, scheduleJobs); } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.IO { public partial class BinaryReader : System.IDisposable { public BinaryReader(System.IO.Stream input) { } public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding) { } public BinaryReader(System.IO.Stream input, System.Text.Encoding encoding, bool leaveOpen) { } public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } protected virtual void FillBuffer(int numBytes) { } public virtual int PeekChar() { return default(int); } public virtual int Read() { return default(int); } public virtual int Read(byte[] buffer, int index, int count) { return default(int); } public virtual int Read(char[] buffer, int index, int count) { return default(int); } protected internal int Read7BitEncodedInt() { return default(int); } public virtual bool ReadBoolean() { return default(bool); } public virtual byte ReadByte() { return default(byte); } public virtual byte[] ReadBytes(int count) { return default(byte[]); } public virtual char ReadChar() { return default(char); } public virtual char[] ReadChars(int count) { return default(char[]); } public virtual decimal ReadDecimal() { return default(decimal); } public virtual double ReadDouble() { return default(double); } public virtual short ReadInt16() { return default(short); } public virtual int ReadInt32() { return default(int); } public virtual long ReadInt64() { return default(long); } [System.CLSCompliantAttribute(false)] public virtual sbyte ReadSByte() { return default(sbyte); } public virtual float ReadSingle() { return default(float); } public virtual string ReadString() { return default(string); } [System.CLSCompliantAttribute(false)] public virtual ushort ReadUInt16() { return default(ushort); } [System.CLSCompliantAttribute(false)] public virtual uint ReadUInt32() { return default(uint); } [System.CLSCompliantAttribute(false)] public virtual ulong ReadUInt64() { return default(ulong); } } public partial class BinaryWriter : System.IDisposable { public static readonly System.IO.BinaryWriter Null; protected System.IO.Stream OutStream; protected BinaryWriter() { } public BinaryWriter(System.IO.Stream output) { } public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding) { } public BinaryWriter(System.IO.Stream output, System.Text.Encoding encoding, bool leaveOpen) { } public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual void Flush() { } public virtual long Seek(int offset, System.IO.SeekOrigin origin) { return default(long); } public virtual void Write(bool value) { } public virtual void Write(byte value) { } public virtual void Write(byte[] buffer) { } public virtual void Write(byte[] buffer, int index, int count) { } public virtual void Write(char ch) { } public virtual void Write(char[] chars) { } public virtual void Write(char[] chars, int index, int count) { } public virtual void Write(decimal value) { } public virtual void Write(double value) { } public virtual void Write(short value) { } public virtual void Write(int value) { } public virtual void Write(long value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(sbyte value) { } public virtual void Write(float value) { } public virtual void Write(string value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(ushort value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(uint value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(ulong value) { } protected void Write7BitEncodedInt(int value) { } } public sealed partial class BufferedStream : System.IO.Stream { public BufferedStream(Stream stream) { } public BufferedStream(Stream stream, int bufferSize) { } public override bool CanRead { get { return default(bool); } } public override bool CanSeek { get { return default(bool); } } public override bool CanWrite { get { return default(bool); } } public override long Length { get { return default(long); } } public override long Position { get { return default(long); } set { } } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } protected override void Dispose(bool disposing) { } public override int EndRead(System.IAsyncResult asyncResult) { return 0; } public override void EndWrite(System.IAsyncResult asyncResult) { return; } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public override int Read(byte[] array, int offset, int count) { return default(int); } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); } public override int ReadByte() { return default(int); } public override long Seek(long offset, SeekOrigin origin) { return default(long); } public override void SetLength(long value) { } public override void Write(byte[] array, int offset, int count) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public override void WriteByte(byte value) { } } public partial class EndOfStreamException : System.IO.IOException { public EndOfStreamException() { } public EndOfStreamException(string message) { } public EndOfStreamException(string message, System.Exception innerException) { } } public sealed partial class InvalidDataException : System.Exception { public InvalidDataException() { } public InvalidDataException(string message) { } public InvalidDataException(string message, System.Exception innerException) { } } public partial class MemoryStream : System.IO.Stream { public MemoryStream() { } public MemoryStream(byte[] buffer) { } public MemoryStream(byte[] buffer, bool writable) { } public MemoryStream(byte[] buffer, int index, int count) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { } public MemoryStream(int capacity) { } public override bool CanRead { get { return default(bool); } } public override bool CanSeek { get { return default(bool); } } public override bool CanWrite { get { return default(bool); } } public virtual int Capacity { get { return default(int); } set { } } public override long Length { get { return default(long); } } public override long Position { get { return default(long); } set { } } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } public override System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } protected override void Dispose(bool disposing) { } public override int EndRead(System.IAsyncResult asyncResult) { return 0; } public override void EndWrite(System.IAsyncResult asyncResult) { return; } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public override int Read(byte[] buffer, int offset, int count) { buffer = default(byte[]); return default(int); } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); } public override int ReadByte() { return default(int); } public override long Seek(long offset, System.IO.SeekOrigin loc) { return default(long); } public override void SetLength(long value) { } public virtual byte[] ToArray() { return default(byte[]); } public virtual bool TryGetBuffer(out System.ArraySegment<byte> buffer) { buffer = default(System.ArraySegment<byte>); return default(bool); } public override void Write(byte[] buffer, int offset, int count) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public override void WriteByte(byte value) { } public virtual void WriteTo(System.IO.Stream stream) { } } public enum SeekOrigin { Begin = 0, Current = 1, End = 2, } public abstract partial class Stream : System.IDisposable { public static readonly System.IO.Stream Null; protected Stream() { } public abstract bool CanRead { get; } public abstract bool CanSeek { get; } public virtual bool CanTimeout { get { return default(bool); } } public abstract bool CanWrite { get; } public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get { return default(int); } set { } } public virtual int WriteTimeout { get { return default(int); } set { } } public virtual System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } public virtual System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { return default(System.IAsyncResult); } public void CopyTo(System.IO.Stream destination) { } public void CopyTo(System.IO.Stream destination, int bufferSize) { } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize) { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual int EndRead(System.IAsyncResult asyncResult) { return 0; } public virtual void EndWrite(System.IAsyncResult asyncResult) { return; } public abstract void Flush(); public System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public abstract int Read(byte[] buffer, int offset, int count); public System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count) { return default(System.Threading.Tasks.Task<int>); } public virtual System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); } public virtual int ReadByte() { return default(int); } public abstract long Seek(long offset, System.IO.SeekOrigin origin); public abstract void SetLength(long value); public abstract void Write(byte[] buffer, int offset, int count); public System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count) { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); } public virtual void WriteByte(byte value) { } } public partial class StreamReader : System.IO.TextReader { public static readonly new System.IO.StreamReader Null; public StreamReader(System.IO.Stream stream) { } public StreamReader(System.IO.Stream stream, bool detectEncodingFromByteOrderMarks) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize) { } public StreamReader(System.IO.Stream stream, System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen) { } public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } } public virtual System.Text.Encoding CurrentEncoding { get { return default(System.Text.Encoding); } } public bool EndOfStream { get { return default(bool); } } public void DiscardBufferedData() { } protected override void Dispose(bool disposing) { } public override int Peek() { return default(int); } public override int Read() { return default(int); } public override int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); } public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public override int ReadBlock(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); } public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public override string ReadLine() { return default(string); } public override System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); } public override string ReadToEnd() { return default(string); } public override System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); } } public partial class StreamWriter : System.IO.TextWriter { public static readonly new System.IO.StreamWriter Null; public StreamWriter(System.IO.Stream stream) { } public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding) { } public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize) { } public StreamWriter(System.IO.Stream stream, System.Text.Encoding encoding, int bufferSize, bool leaveOpen) { } public virtual bool AutoFlush { get { return default(bool); } set { } } public virtual System.IO.Stream BaseStream { get { return default(System.IO.Stream); } } public override System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } } protected override void Dispose(bool disposing) { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); } public override void Write(char value) { } public override void Write(char[] buffer) { } public override void Write(char[] buffer, int index, int count) { } public override void Write(string value) { } public override System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteLineAsync() { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); } } public partial class StringReader : System.IO.TextReader { public StringReader(string s) { } protected override void Dispose(bool disposing) { } public override int Peek() { return default(int); } public override int Read() { return default(int); } public override int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); } public override System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public override System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public override string ReadLine() { return default(string); } public override System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); } public override string ReadToEnd() { return default(string); } public override System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); } } public partial class StringWriter : System.IO.TextWriter { public StringWriter() { } public StringWriter(System.IFormatProvider formatProvider) { } public StringWriter(System.Text.StringBuilder sb) { } public StringWriter(System.Text.StringBuilder sb, System.IFormatProvider formatProvider) { } public override System.Text.Encoding Encoding { get { return default(System.Text.Encoding); } } protected override void Dispose(bool disposing) { } public override System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); } public virtual System.Text.StringBuilder GetStringBuilder() { return default(System.Text.StringBuilder); } public override string ToString() { return default(string); } public override void Write(char value) { } public override void Write(char[] buffer, int index, int count) { } public override void Write(string value) { } public override System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public override System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); } } public abstract partial class TextReader : System.IDisposable { public static readonly System.IO.TextReader Null; protected TextReader() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual int Peek() { return default(int); } public virtual int Read() { return default(int); } public virtual int Read(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); } public virtual System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public virtual int ReadBlock(char[] buffer, int index, int count) { buffer = default(char[]); return default(int); } public virtual System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task<int>); } public virtual string ReadLine() { return default(string); } public virtual System.Threading.Tasks.Task<string> ReadLineAsync() { return default(System.Threading.Tasks.Task<string>); } public virtual string ReadToEnd() { return default(string); } public virtual System.Threading.Tasks.Task<string> ReadToEndAsync() { return default(System.Threading.Tasks.Task<string>); } } public abstract partial class TextWriter : System.IDisposable { protected char[] CoreNewLine; public static readonly System.IO.TextWriter Null; protected TextWriter() { } protected TextWriter(System.IFormatProvider formatProvider) { } public abstract System.Text.Encoding Encoding { get; } public virtual System.IFormatProvider FormatProvider { get { return default(System.IFormatProvider); } } public virtual string NewLine { get { return default(string); } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual void Flush() { } public virtual System.Threading.Tasks.Task FlushAsync() { return default(System.Threading.Tasks.Task); } public virtual void Write(bool value) { } public abstract void Write(char value); public virtual void Write(char[] buffer) { } public virtual void Write(char[] buffer, int index, int count) { } public virtual void Write(decimal value) { } public virtual void Write(double value) { } public virtual void Write(int value) { } public virtual void Write(long value) { } public virtual void Write(object value) { } public virtual void Write(float value) { } public virtual void Write(string value) { } public virtual void Write(string format, object arg0) { } public virtual void Write(string format, object arg0, object arg1) { } public virtual void Write(string format, object arg0, object arg1, object arg2) { } public virtual void Write(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public virtual void Write(uint value) { } [System.CLSCompliantAttribute(false)] public virtual void Write(ulong value) { } public virtual System.Threading.Tasks.Task WriteAsync(char value) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task WriteAsync(char[] buffer) { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteAsync(string value) { return default(System.Threading.Tasks.Task); } public virtual void WriteLine() { } public virtual void WriteLine(bool value) { } public virtual void WriteLine(char value) { } public virtual void WriteLine(char[] buffer) { } public virtual void WriteLine(char[] buffer, int index, int count) { } public virtual void WriteLine(decimal value) { } public virtual void WriteLine(double value) { } public virtual void WriteLine(int value) { } public virtual void WriteLine(long value) { } public virtual void WriteLine(object value) { } public virtual void WriteLine(float value) { } public virtual void WriteLine(string value) { } public virtual void WriteLine(string format, object arg0) { } public virtual void WriteLine(string format, object arg0, object arg1) { } public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { } public virtual void WriteLine(string format, params object[] arg) { } [System.CLSCompliantAttribute(false)] public virtual void WriteLine(uint value) { } [System.CLSCompliantAttribute(false)] public virtual void WriteLine(ulong value) { } public virtual System.Threading.Tasks.Task WriteLineAsync() { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteLineAsync(char value) { return default(System.Threading.Tasks.Task); } public System.Threading.Tasks.Task WriteLineAsync(char[] buffer) { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteLineAsync(char[] buffer, int index, int count) { return default(System.Threading.Tasks.Task); } public virtual System.Threading.Tasks.Task WriteLineAsync(string value) { return default(System.Threading.Tasks.Task); } } }
// <copyright file="MeterMetricTests.cs" company="App Metrics Contributors"> // Copyright (c) App Metrics Contributors. All rights reserved. // </copyright> using App.Metrics.Facts.TestHelpers; using App.Metrics.FactsCommon; using App.Metrics.Meter; using FluentAssertions; using Xunit; namespace App.Metrics.Facts.Meter { public class MeterMetricTests { private readonly IClock _clock; private readonly DefaultMeterMetric _meter; public MeterMetricTests() { _clock = new TestClock(); var schedular = new TestMeterTickerScheduler(_clock); _meter = new DefaultMeterMetric(_clock, schedular); } [Fact] public void Can_calculate_mean_rate() { _meter.Mark(); _clock.Advance(TimeUnit.Seconds, 1); _meter.Value.MeanRate.Should().Be(1); _clock.Advance(TimeUnit.Seconds, 1); _meter.Value.MeanRate.Should().Be(0.5); } [Fact] public void Can_compute_multiple_rates() { _meter.Mark(); _clock.Advance(TimeUnit.Seconds, 10); _meter.Mark(2); var value = _meter.Value; value.MeanRate.Should().BeApproximately(0.3, 0.001); value.OneMinuteRate.Should().BeApproximately(0.1840, 0.001); value.FiveMinuteRate.Should().BeApproximately(0.1966, 0.001); value.FifteenMinuteRate.Should().BeApproximately(0.1988, 0.001); } [Fact] public void Can_compute_percent_with_zero_total() { _meter.Mark("A"); _meter.Mark("A", -1); _meter.Value.Count.Should().Be(0); _meter.Value.Items[0].Item.Should().Be("A"); _meter.Value.Items[0].Value.Count.Should().Be(0); _meter.Value.Items[0].Percent.Should().Be(0); } [Fact] public void Can_count() { _meter.Mark(); _meter.Value.Count.Should().Be(1L); _meter.Mark(); _meter.Value.Count.Should().Be(2L); _meter.Mark(8L); _meter.Value.Count.Should().Be(10L); } [Fact] public void Can_count_for_multiple_set_items() { _meter.Mark("A"); _meter.Mark("B"); _meter.Value.Count.Should().Be(2L); _meter.Value.Items.Should().HaveCount(2); _meter.Value.Items[0].Item.Should().Be("A"); _meter.Value.Items[0].Value.Count.Should().Be(1); _meter.Value.Items[0].Percent.Should().Be(50); _meter.Value.Items[1].Item.Should().Be("B"); _meter.Value.Items[1].Value.Count.Should().Be(1); _meter.Value.Items[1].Percent.Should().Be(50); } [Fact] public void Can_count_for_set_item() { _meter.Mark("A"); _meter.Value.Count.Should().Be(1L); _meter.Value.Items.Should().HaveCount(1); _meter.Value.Items[0].Item.Should().Be("A"); _meter.Value.Items[0].Value.Count.Should().Be(1); _meter.Value.Items[0].Percent.Should().Be(100); } [Fact] public void Can_reset() { _meter.Mark(); _meter.Mark(); _clock.Advance(TimeUnit.Seconds, 10); _meter.Mark(2); _meter.Reset(); _meter.Value.Count.Should().Be(0L); _meter.Value.OneMinuteRate.Should().Be(0); _meter.Value.FiveMinuteRate.Should().Be(0); _meter.Value.FifteenMinuteRate.Should().Be(0); } [Fact] public void Can_reset_set_item() { _meter.Mark("A"); _meter.Value.Items[0].Value.Count.Should().Be(1); _meter.Reset(); _meter.Value.Items[0].Value.Count.Should().Be(0L); } [Fact] public void Can_get_value() { _meter.Mark(); var value = _meter.GetValue(); value.Count.Should().Be(1); _meter.Value.Count.Should().Be(1); } [Fact] public void Can_get_value_and_reset() { _meter.Mark(); var value = _meter.GetValue(true); value.Count.Should().Be(1); _meter.Value.Count.Should().Be(0L); } [Fact] public void Rates_should_start_at_zero() { _meter.Value.MeanRate.Should().Be(0L); _meter.Value.OneMinuteRate.Should().Be(0L); _meter.Value.FiveMinuteRate.Should().Be(0L); _meter.Value.FifteenMinuteRate.Should().Be(0L); } [Fact] public void Returns_empty_meter_if_not_meter_metric() { var meter = new CustomMeter(); var value = meter.GetValueOrDefault(); value.Should().NotBeNull(); } [Fact] public void Value_can_scale_down() { _meter.Mark(); _clock.Advance(TimeUnit.Milliseconds, 1); _meter.Mark(); _clock.Advance(TimeUnit.Milliseconds, 1); var scaledValue = _meter.Value.Scale(TimeUnit.Milliseconds); scaledValue.MeanRate.Should().Be(1); } [Fact] public void Value_can_scale_down_to_decimal() { _meter.Mark(); _clock.Advance(TimeUnit.Seconds, 1); _meter.Mark(); _clock.Advance(TimeUnit.Seconds, 1); var scaledValue = _meter.Value.Scale(TimeUnit.Milliseconds); scaledValue.MeanRate.Should().Be(0.001); } [Fact] public void Value_can_scale_up() { _meter.Mark(); _clock.Advance(TimeUnit.Minutes, 1); _meter.Mark(); _clock.Advance(TimeUnit.Minutes, 1); var scaledValue = _meter.GetValueOrDefault().Scale(TimeUnit.Minutes); scaledValue.MeanRate.Should().Be(1); } } }
using Signum.Entities.Disconnected; using System.IO; using System.Data.Common; using Signum.Utilities.DataStructures; using Signum.Entities.Authorization; using Signum.Entities.Basics; namespace Signum.Engine.Disconnected; public class ImportManager { static object SyncLock = new object(); class UploadTable { public Type Type; public Table Table; public IDisconnectedStrategy Strategy; public UploadTable(Type type, Table table, IDisconnectedStrategy strategy) { Type = type; Table = table; Strategy = strategy; } public override string ToString() { return Table.ToString(); } } public void Initialize() { var tables = Schema.Current.Tables.Values .Select(t => new UploadTable(t.Type, t, DisconnectedLogic.GetStrategy(t.Type))) .Where(p => p.Strategy.Upload != Upload.None) .ToList(); var dic = tables.ToDictionary(a => a.Table); DirectedGraph<Table> graph = DirectedGraph<Table>.Generate( dic.Keys, t => t.DependentTables().Select(a => a.Key).Where(tab => dic.ContainsKey(tab))); var feedback = graph.FeedbackEdgeSet(); foreach (var edge in feedback.Edges) { var strategy = dic[edge.From].Strategy; if (strategy.DisableForeignKeys == null) strategy.DisableForeignKeys = true; } foreach (var item in dic.Values.Where(a => a.Strategy.DisableForeignKeys == null)) item.Strategy.DisableForeignKeys = false; graph.RemoveEdges(feedback.Edges); uploadTables = graph.CompilationOrder().Select(t => dic[t]).ToList(); } List<UploadTable> uploadTables = null!; class RunningImports { public Task Task; public CancellationTokenSource CancelationSource; public RunningImports(Task task, CancellationTokenSource cancelationSource) { Task = task; CancelationSource = cancelationSource; } } Dictionary<Lite<DisconnectedImportEntity>, RunningImports> runningImports = new Dictionary<Lite<DisconnectedImportEntity>, RunningImports>(); public virtual Lite<DisconnectedImportEntity> BeginImportDatabase(DisconnectedMachineEntity machine, Stream? file = null) { Lite<DisconnectedImportEntity> import = new DisconnectedImportEntity { Machine = machine.ToLite(), Copies = uploadTables.Select(t => new DisconnectedImportTableEmbedded { Type = t.Type.ToTypeEntity().ToLite(), DisableForeignKeys = t.Strategy.DisableForeignKeys!.Value, }).ToMList() }.Save().ToLite(); if (file != null) using (FileStream fs = File.OpenWrite(BackupNetworkFileName(machine, import))) { file.CopyTo(fs); file.Close(); } var threadContext = Statics.ExportThreadContext(); var cancelationSource = new CancellationTokenSource(); var user = UserEntity.Current; var token = cancelationSource.Token; var task = Task.Factory.StartNew(() => { lock (SyncLock) using (UserHolder.UserSession(user)) { OnStartImporting(machine); DisconnectedMachineEntity.Current = machine.ToLite(); try { if (file != null) { using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s=>s.RestoreDatabase, s=>l).Execute())) { DropDatabaseIfExists(machine); RestoreDatabase(machine, import); } } string connectionString = GetImportConnectionString(machine); var newDatabase = new SqlServerConnector(connectionString, Schema.Current, ((SqlServerConnector)Connector.Current).Version); using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.SynchronizeSchema, s => l).Execute())) using (Connector.Override(newDatabase)) using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true })) using (ExecutionMode.DisableCache()) { var script = Administrator.TotalSynchronizeScript(interactive: false, schemaOnly: true); if (script != null) { string fileName = BackupNetworkFileName(machine, import) + ".sql"; script.Save(fileName); throw new InvalidOperationException("The schema has changed since the last export. A schema sync script has been saved on: {0}".FormatWith(fileName)); } } try { using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.DisableForeignKeys, s => l).Execute())) foreach (var item in uploadTables.Where(u => u.Strategy.DisableForeignKeys!.Value)) { DisableForeignKeys(item.Table); } foreach (var tuple in uploadTables) { ImportResult? result = null; using (token.MeasureTime(l => { if (result != null) import.MListElementsLite(_ => _.Copies).Where(mle => mle.Element.Type.Is(tuple.Type.ToTypeEntity())).UnsafeUpdateMList() .Set(mle => mle.Element.CopyTable, mle => l) .Set(mle => mle.Element.DisableForeignKeys, mle => tuple.Strategy.DisableForeignKeys!.Value) .Set(mle => mle.Element.InsertedRows, mle => result.Inserted) .Set(mle => mle.Element.UpdatedRows, mle => result.Updated) .Execute(); })) { result = tuple.Strategy.Importer!.Import(machine, tuple.Table, tuple.Strategy, newDatabase); } } using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.Unlock, s => l).Execute())) UnlockTables(machine.ToLite()); } finally { using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.EnableForeignKeys, s => l).Execute())) foreach (var item in uploadTables.Where(u => u.Strategy.DisableForeignKeys!.Value)) { EnableForeignKeys(item.Table); } } using (token.MeasureTime(l => import.InDB().UnsafeUpdate().Set(s => s.DropDatabase, s => l).Execute())) DropDatabase(newDatabase); token.ThrowIfCancellationRequested(); import.InDB().UnsafeUpdate() .Set(s => s.State,s=> DisconnectedImportState.Completed) .Set(s => s.Total,s=> s.CalculateTotal()) .Execute(); machine.InDB().UnsafeUpdate() .Set(m => m.State, m => file == null ? DisconnectedMachineState.Fixed : DisconnectedMachineState.Connected) .Execute(); } catch (Exception e) { var ex = e.LogException(); import.InDB().UnsafeUpdate() .Set(m => m.Exception, m => ex.ToLite()) .Set(m => m.State, m => DisconnectedImportState.Error) .Execute(); machine.InDB().UnsafeUpdate() .Set(m => m.State, m => DisconnectedMachineState.Faulted) .Execute(); OnImportingError(machine, import, e); } finally { runningImports.Remove(import); DisconnectedMachineEntity.Current = null; OnEndImporting(); } } }); runningImports.Add(import, new RunningImports(task, cancelationSource)); return import; } public virtual void SkipExport(Lite<DisconnectedMachineEntity> machine) { UnlockTables(machine); machine.InDB().UnsafeUpdate().Set(m => m.State, m => DisconnectedMachineState.Connected).Execute(); } public virtual void ConnectAfterFix(Lite<DisconnectedMachineEntity> machine) { machine.InDB().UnsafeUpdate().Set(m => m.State, m => DisconnectedMachineState.Connected).Execute(); } protected virtual void OnStartImporting(DisconnectedMachineEntity machine) { } protected virtual void OnEndImporting() { } protected virtual void OnImportingError(DisconnectedMachineEntity machine, Lite<DisconnectedImportEntity> import, Exception exception) { } private void DropDatabaseIfExists(DisconnectedMachineEntity machine) { DisconnectedTools.DropIfExists(DatabaseName(machine)); } private void DropDatabase(SqlServerConnector newDatabase) { var isPostgres = Schema.Current.Settings.IsPostgres; DisconnectedTools.DropDatabase(new DatabaseName(null, newDatabase.DatabaseName(), isPostgres)); } protected virtual void EnableForeignKeys(Table table) { DisconnectedTools.EnableForeignKeys(table); foreach (var rt in table.TablesMList()) DisconnectedTools.EnableForeignKeys(rt); } protected virtual void DisableForeignKeys(Table table) { DisconnectedTools.DisableForeignKeys(table); foreach (var rt in table.TablesMList()) DisconnectedTools.DisableForeignKeys(rt); } private void RestoreDatabase(DisconnectedMachineEntity machine, Lite<DisconnectedImportEntity> import) { string backupFileName = Path.Combine(DisconnectedLogic.BackupFolder, BackupFileName(machine, import)); string fileName = DatabaseFileName(machine); string logFileName = DatabaseLogFileName(machine); DisconnectedTools.RestoreDatabase(DatabaseName(machine), backupFileName, fileName, logFileName); } private string GetImportConnectionString(DisconnectedMachineEntity machine) { return ((SqlServerConnector)Connector.Current).ConnectionString.Replace(Connector.Current.DatabaseName(), DatabaseName(machine).Name); } protected virtual string DatabaseFileName(DisconnectedMachineEntity machine) { return Path.Combine(DisconnectedLogic.DatabaseFolder, Connector.Current.DatabaseName() + "_Import_" + DisconnectedTools.CleanMachineName(machine.MachineName) + ".mdf"); } protected virtual string DatabaseLogFileName(DisconnectedMachineEntity machine) { return Path.Combine(DisconnectedLogic.DatabaseFolder, Connector.Current.DatabaseName() + "_Import_" + DisconnectedTools.CleanMachineName(machine.MachineName) + "_Log.ldf"); } protected virtual DatabaseName DatabaseName(DisconnectedMachineEntity machine) { var isPostgres = Schema.Current.Settings.IsPostgres; return new DatabaseName(null, Connector.Current.DatabaseName() + "_Import_" + DisconnectedTools.CleanMachineName(machine.MachineName), isPostgres); } public virtual string BackupNetworkFileName(DisconnectedMachineEntity machine, Lite<DisconnectedImportEntity> import) { return Path.Combine(DisconnectedLogic.BackupNetworkFolder, BackupFileName(machine, import)); } protected virtual string BackupFileName(DisconnectedMachineEntity machine, Lite<DisconnectedImportEntity> import) { return "{0}.{1}.Import.{2}.bak".FormatWith(Connector.Current.DatabaseName(), DisconnectedTools.CleanMachineName(machine.MachineName), import.Id); } private IQueryable<MListElement<DisconnectedImportEntity, DisconnectedImportTableEmbedded>> ImportTableQuery(Lite<DisconnectedImportEntity> import, TypeEntity type) { return Database.MListQuery((DisconnectedImportEntity s) => s.Copies).Where(dst => dst.Parent.ToLite().Is(import) && dst.Element.Type.Is(type)); } public void UnlockTables(Lite<DisconnectedMachineEntity> machine) { foreach (var kvp in DisconnectedLogic.strategies) { if (kvp.Value.Upload == Upload.Subset) miUnlockTable.MakeGenericMethod(kvp.Key).Invoke(null, new[] { machine }); } } static readonly MethodInfo miUnlockTable = typeof(ImportManager).GetMethod("UnlockTable", BindingFlags.NonPublic | BindingFlags.Static)!; static int UnlockTable<T>(Lite<DisconnectedMachineEntity> machine) where T : Entity { using (ExecutionMode.Global()) return Database.Query<T>().Where(a => a.Mixin<DisconnectedSubsetMixin>().DisconnectedMachine.Is(machine)) .UnsafeUpdate() .Set(a => a.Mixin<DisconnectedSubsetMixin>().DisconnectedMachine, a => null) .Set(a => a.Mixin<DisconnectedSubsetMixin>().LastOnlineTicks, a => null) .Execute(); } } public interface ICustomImporter { ImportResult Import(DisconnectedMachineEntity machine, Table table, IDisconnectedStrategy strategy, SqlServerConnector newDatabase); } public class BasicImporter<T> : ICustomImporter where T : Entity { public virtual ImportResult Import(DisconnectedMachineEntity machine, Table table, IDisconnectedStrategy strategy, SqlServerConnector newDatabase) { int inserts = Insert(machine, table, strategy, newDatabase); return new ImportResult { Inserted = inserts, Updated = 0 }; } protected virtual int Insert(DisconnectedMachineEntity machine, Table table, IDisconnectedStrategy strategy, SqlServerConnector newDatabase) { var isPostgres = Schema.Current.Settings.IsPostgres; DatabaseName newDatabaseName = new DatabaseName(null, newDatabase.DatabaseName(), isPostgres); var count = (int)CountNewItems(table, newDatabaseName).ExecuteScalar()!; if (count == 0) return 0; using (var tr = new Transaction()) { int result; using (DisableIdentityIfNecessary(table)) { SqlPreCommandSimple sql = InsertTableScript(table, newDatabaseName); result = Executor.ExecuteNonQuery(sql); } foreach (var rt in table.TablesMList()) { using (DisableIdentityIfNecessary(rt)) { SqlPreCommandSimple rsql = InsertRelationalTableScript(table, newDatabaseName, rt); Executor.ExecuteNonQuery(rsql); } } return tr.Commit(result); } } protected IDisposable? DisableIdentityIfNecessary(ITable table) { if (!table.PrimaryKey.Identity) return null; return Administrator.DisableIdentity(table); } protected virtual SqlPreCommandSimple InsertRelationalTableScript(Table table, DatabaseName newDatabaseName, TableMList rt) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var created = table.Mixins![typeof(DisconnectedCreatedMixin)].Columns().Single(); var isPostgres = Schema.Current.Settings.IsPostgres; string command = @"INSERT INTO {0} ({1}) SELECT {2} FROM {3} as [relationalTable] JOIN {4} [table] on [relationalTable].{5} = [table].{6} WHERE [table].{7} = 1".FormatWith( rt.Name, rt.Columns.Values.ToString(c => c.Name.SqlEscape(isPostgres), ", "), rt.Columns.Values.ToString(c => "[relationalTable]." + c.Name.SqlEscape(isPostgres), ", "), rt.Name.OnDatabase(newDatabaseName), table.Name.OnDatabase(newDatabaseName), rt.BackReference.Name.SqlEscape(isPostgres), table.PrimaryKey.Name.SqlEscape(isPostgres), created.Name.SqlEscape(isPostgres)); var sql = new SqlPreCommandSimple(command); return sql; } protected virtual SqlPreCommandSimple InsertTableScript(Table table, DatabaseName newDatabaseName) { var isPostgres = Schema.Current.Settings.IsPostgres; var created = table.Mixins![typeof(DisconnectedCreatedMixin)].Columns().Single(); string command = @"INSERT INTO {0} ({1}) SELECT {2} FROM {3} as [table] WHERE [table].{4} = 1".FormatWith( table.Name, table.Columns.Values.ToString(c => c.Name.SqlEscape(isPostgres), ", "), table.Columns.Values.ToString(c => created == c ? "0" : "[table]." + c.Name.SqlEscape(isPostgres), ", "), table.Name.OnDatabase(newDatabaseName), created.Name.SqlEscape(isPostgres)); return new SqlPreCommandSimple(command); } protected virtual SqlPreCommandSimple CountNewItems(Table table, DatabaseName newDatabaseName) { var isPostgres = Schema.Current.Settings.IsPostgres; string command = @"SELECT COUNT(*) FROM {1} as [table] LEFT OUTER JOIN {0} as [current_table] ON [table].{2} = [current_table].{2} WHERE [current_table].{2} IS NULL".FormatWith( table.Name, table.Name.OnDatabase(newDatabaseName), table.PrimaryKey.Name.SqlEscape(isPostgres)); return new SqlPreCommandSimple(command); } } public class UpdateImporter<T> : BasicImporter<T> where T : Entity { public override ImportResult Import(DisconnectedMachineEntity machine, Table table, IDisconnectedStrategy strategy, SqlServerConnector newDatabase) { var isPostgres = Schema.Current.Settings.IsPostgres; int update = strategy.Upload == Upload.Subset ? Update(machine, table, strategy, new DatabaseName(null, newDatabase.DatabaseName(), isPostgres)) : 0; int inserts = Insert(machine, table, strategy, newDatabase); return new ImportResult { Inserted = inserts, Updated = update }; } protected virtual int Update(DisconnectedMachineEntity machine, Table table, IDisconnectedStrategy strategy, DatabaseName newDatabaseName) { using (var tr = new Transaction()) { SqlPreCommandSimple command = UpdateTableScript(machine, table, newDatabaseName); int result = Executor.ExecuteNonQuery(command); foreach (var rt in table.TablesMList()) { SqlPreCommandSimple delete = DeleteUpdatedRelationalTableScript(machine, table, rt, newDatabaseName); Executor.ExecuteNonQuery(delete); using (DisableIdentityIfNecessary(rt)) { SqlPreCommandSimple insert = InsertUpdatedRelationalTableScript(machine, table, rt, newDatabaseName); Executor.ExecuteNonQuery(insert); } } return tr.Commit(result); } } protected virtual SqlPreCommandSimple InsertUpdatedRelationalTableScript(DisconnectedMachineEntity machine, Table table, TableMList rt, DatabaseName newDatabaseName) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var isPostgres = Schema.Current.Settings.IsPostgres; var insert = new SqlPreCommandSimple(@"INSERT INTO {0} ({1}) SELECT {2} FROM {3} as [relationalTable] INNER JOIN {4} as [table] ON [relationalTable].{5} = [table].{6}".FormatWith( rt.Name, rt.Columns.Values.ToString(c => c.Name.SqlEscape(isPostgres), ", "), rt.Columns.Values.ToString(c => "[relationalTable]." + c.Name.SqlEscape(isPostgres), ", "), rt.Name.OnDatabase(newDatabaseName), table.Name.OnDatabase(newDatabaseName), rt.BackReference.Name.SqlEscape(isPostgres), table.PrimaryKey.Name.SqlEscape(isPostgres)) + GetUpdateWhere(table), new List<DbParameter> { pb.CreateParameter("@machineId", machine.Id.Object, machine.Id.Object.GetType()) }); return insert; } protected virtual SqlPreCommandSimple DeleteUpdatedRelationalTableScript(DisconnectedMachineEntity machine, Table table, TableMList rt, DatabaseName newDatabaseName) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var isPostgres = Schema.Current.Settings.IsPostgres; var delete = new SqlPreCommandSimple(@"DELETE {0} FROM {0} INNER JOIN {1} as [table] ON {0}.{2} = [table].{3}".FormatWith( rt.Name, table.Name.OnDatabase(newDatabaseName), rt.BackReference.Name.SqlEscape(isPostgres), table.PrimaryKey.Name.SqlEscape(isPostgres)) + GetUpdateWhere(table), new List<DbParameter> { pb.CreateParameter("@machineId", machine.Id.Object, machine.Id.Object.GetType()) }); return delete; } protected virtual SqlPreCommandSimple UpdateTableScript(DisconnectedMachineEntity machine, Table table, DatabaseName newDatabaseName) { ParameterBuilder pb = Connector.Current.ParameterBuilder; var isPostgres = Schema.Current.Settings.IsPostgres; var command = new SqlPreCommandSimple(@"UPDATE {0} SET {2} FROM {0} INNER JOIN {1} as [table] ON {0}.{3} = [table].{3}".FormatWith( table.Name, table.Name.OnDatabase(newDatabaseName), table.Columns.Values.Where(c => !c.PrimaryKey).ToString(c => " {0} = [table].{0}".FormatWith(c.Name.SqlEscape(isPostgres)), ",\r\n"), table.PrimaryKey.Name.SqlEscape(isPostgres)) + GetUpdateWhere(table), new List<DbParameter> { pb.CreateParameter("@machineId", machine.Id.Object, machine.Id.Object.GetType()) }); return command; } protected virtual string GetUpdateWhere(Table table) { var isPostgres = Schema.Current.Settings.IsPostgres; var s = Schema.Current; var where = "\r\nWHERE [table].{0} = @machineId AND [table].{1} != [table].{2}".FormatWith( ((FieldReference)s.Field((T t) => t.Mixin<DisconnectedSubsetMixin>().DisconnectedMachine)).Name.SqlEscape(isPostgres), ((FieldValue)s.Field((T t) => t.Ticks)).Name.SqlEscape(isPostgres), ((FieldValue)s.Field((T t) => t.Mixin<DisconnectedSubsetMixin>().LastOnlineTicks)).Name.SqlEscape(isPostgres)); return where; } } public class ImportResult { public int Inserted; public int Updated; }
// 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.Diagnostics.Contracts; using System.Text; namespace System.IO.Compression { //The disposable fields that this class owns get disposed when the ZipArchive it belongs to gets disposed [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public partial class ZipArchiveEntry { #region Fields private const UInt16 DefaultVersionToExtract = 10; //The maximum index of our buffers, from the maximum index of a byte array private const int MaxSingleBufferSize = 0x7FFFFFC7; private ZipArchive _archive; private readonly Boolean _originallyInArchive; private readonly Int32 _diskNumberStart; private readonly ZipVersionMadeByPlatform _versionMadeByPlatform; private readonly byte _versionMadeBySpecification; private ZipVersionNeededValues _versionToExtract; private BitFlagValues _generalPurposeBitFlag; private CompressionMethodValues _storedCompressionMethod; private DateTimeOffset _lastModified; private Int64 _compressedSize; private Int64 _uncompressedSize; private Int64 _offsetOfLocalHeader; private Int64? _storedOffsetOfCompressedData; private UInt32 _crc32; //An array of buffers, each a maximum of MaxSingleBufferSize in size private Byte[][] _compressedBytes; private MemoryStream _storedUncompressedData; private Boolean _currentlyOpenForWrite; private Boolean _everOpenedForWrite; private Stream _outstandingWriteStream; private String _storedEntryName; private Byte[] _storedEntryNameBytes; //only apply to update mode private List<ZipGenericExtraField> _cdUnknownExtraFields; private List<ZipGenericExtraField> _lhUnknownExtraFields; private Byte[] _fileComment; private CompressionLevel? _compressionLevel; #endregion Fields //Initializes, attaches it to archive internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd, CompressionLevel compressionLevel) : this(archive, cd) { _compressionLevel = compressionLevel; } //Initializes, attaches it to archive internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd) { _archive = archive; _originallyInArchive = true; _diskNumberStart = cd.DiskNumberStart; _versionMadeByPlatform = (ZipVersionMadeByPlatform)cd.VersionMadeByCompatibility; _versionMadeBySpecification = cd.VersionMadeBySpecification; _versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract; _generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag; CompressionMethod = (CompressionMethodValues)cd.CompressionMethod; _lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified)); _compressedSize = cd.CompressedSize; _uncompressedSize = cd.UncompressedSize; _offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader; /* we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength * but entryname/extra length could be different in LH */ _storedOffsetOfCompressedData = null; _crc32 = cd.Crc32; _compressedBytes = null; _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; _outstandingWriteStream = null; FullName = DecodeEntryName(cd.Filename); _lhUnknownExtraFields = null; //the cd should have these as null if we aren't in Update mode _cdUnknownExtraFields = cd.ExtraFields; _fileComment = cd.FileComment; _compressionLevel = null; } //Initializes new entry internal ZipArchiveEntry(ZipArchive archive, String entryName, CompressionLevel compressionLevel) : this(archive, entryName) { _compressionLevel = compressionLevel; } //Initializes new entry internal ZipArchiveEntry(ZipArchive archive, String entryName) { _archive = archive; _originallyInArchive = false; _diskNumberStart = 0; _versionMadeByPlatform = CurrentZipPlatform; _versionMadeBySpecification = 0; _versionToExtract = ZipVersionNeededValues.Default; //this must happen before following two assignment _generalPurposeBitFlag = 0; CompressionMethod = CompressionMethodValues.Deflate; _lastModified = DateTimeOffset.Now; _compressedSize = 0; //we don't know these yet _uncompressedSize = 0; _offsetOfLocalHeader = 0; _storedOffsetOfCompressedData = null; _crc32 = 0; _compressedBytes = null; _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; _outstandingWriteStream = null; FullName = entryName; _cdUnknownExtraFields = null; _lhUnknownExtraFields = null; _fileComment = null; _compressionLevel = null; if (_storedEntryNameBytes.Length > UInt16.MaxValue) throw new ArgumentException(SR.EntryNamesTooLong); //grab the stream if we're in create mode if (_archive.Mode == ZipArchiveMode.Create) { _archive.AcquireArchiveStream(this); } } /// <summary> /// The ZipArchive that this entry belongs to. If this entry has been deleted, this will return null. /// </summary> public ZipArchive Archive { get { return _archive; } } /// <summary> /// The compressed size of the entry. If the archive that the entry belongs to is in Create mode, attempts to get this property will always throw an exception. If the archive that the entry belongs to is in update mode, this property will only be valid if the entry has not been opened. /// </summary> /// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception> public Int64 CompressedLength { get { Contract.Ensures(Contract.Result<Int64>() >= 0); if (_everOpenedForWrite) throw new InvalidOperationException(SR.LengthAfterWrite); return _compressedSize; } } /// <summary> /// The relative path of the entry as stored in the Zip archive. Note that Zip archives allow any string to be the path of the entry, including invalid and absolute paths. /// </summary> public String FullName { get { Contract.Ensures(Contract.Result<String>() != null); return _storedEntryName; } private set { if (value == null) throw new ArgumentNullException("FullName"); bool isUTF8; _storedEntryNameBytes = EncodeEntryName(value, out isUTF8); _storedEntryName = value; if (isUTF8) _generalPurposeBitFlag |= BitFlagValues.UnicodeFileName; else _generalPurposeBitFlag &= ~BitFlagValues.UnicodeFileName; if (ParseFileName(value, _versionMadeByPlatform) == "") VersionToExtractAtLeast(ZipVersionNeededValues.ExplicitDirectory); } } /// <summary> /// The last write time of the entry as stored in the Zip archive. When setting this property, the DateTime will be converted to the /// Zip timestamp format, which supports a resolution of two seconds. If the data in the last write time field is not a valid Zip timestamp, /// an indicator value of 1980 January 1 at midnight will be returned. /// </summary> /// <exception cref="NotSupportedException">An attempt to set this property was made, but the ZipArchive that this entry belongs to was /// opened in read-only mode.</exception> /// <exception cref="ArgumentOutOfRangeException">An attempt was made to set this property to a value that cannot be represented in the /// Zip timestamp format. The earliest date/time that can be represented is 1980 January 1 0:00:00 (midnight), and the last date/time /// that can be represented is 2107 December 31 23:59:58 (one second before midnight).</exception> public DateTimeOffset LastWriteTime { get { return _lastModified; } set { ThrowIfInvalidArchive(); if (_archive.Mode == ZipArchiveMode.Read) throw new NotSupportedException(SR.ReadOnlyArchive); if (_archive.Mode == ZipArchiveMode.Create && _everOpenedForWrite) throw new IOException(SR.FrozenAfterWrite); if (value.DateTime.Year < ZipHelper.ValidZipDate_YearMin || value.DateTime.Year > ZipHelper.ValidZipDate_YearMax) throw new ArgumentOutOfRangeException(nameof(value), SR.DateTimeOutOfRange); _lastModified = value; } } /// <summary> /// The uncompressed size of the entry. This property is not valid in Create mode, and it is only valid in Update mode if the entry has not been opened. /// </summary> /// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception> public Int64 Length { get { Contract.Ensures(Contract.Result<Int64>() >= 0); if (_everOpenedForWrite) throw new InvalidOperationException(SR.LengthAfterWrite); return _uncompressedSize; } } /// <summary> /// The filename of the entry. This is equivalent to the substring of Fullname that follows the final directory separator character. /// </summary> public String Name { get { return ParseFileName(FullName, _versionMadeByPlatform); } } /// <summary> /// Deletes the entry from the archive. /// </summary> /// <exception cref="IOException">The entry is already open for reading or writing.</exception> /// <exception cref="NotSupportedException">The ZipArchive that this entry belongs to was opened in a mode other than ZipArchiveMode.Update. </exception> /// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception> public void Delete() { if (_archive == null) return; if (_currentlyOpenForWrite) throw new IOException(SR.DeleteOpenEntry); if (_archive.Mode != ZipArchiveMode.Update) throw new NotSupportedException(SR.DeleteOnlyInUpdate); _archive.ThrowIfDisposed(); _archive.RemoveEntry(this); _archive = null; UnloadStreams(); } /// <summary> /// Opens the entry. If the archive that the entry belongs to was opened in Read mode, the returned stream will be readable, and it may or may not be seekable. If Create mode, the returned stream will be writeable and not seekable. If Update mode, the returned stream will be readable, writeable, seekable, and support SetLength. /// </summary> /// <returns>A Stream that represents the contents of the entry.</returns> /// <exception cref="IOException">The entry is already currently open for writing. -or- The entry has been deleted from the archive. -or- The archive that this entry belongs to was opened in ZipArchiveMode.Create, and this entry has already been written to once.</exception> /// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read. -or- The entry has been compressed using a compression method that is not supported.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception> public Stream Open() { Contract.Ensures(Contract.Result<Stream>() != null); ThrowIfInvalidArchive(); switch (_archive.Mode) { case ZipArchiveMode.Read: return OpenInReadMode(true); case ZipArchiveMode.Create: return OpenInWriteMode(); case ZipArchiveMode.Update: default: Debug.Assert(_archive.Mode == ZipArchiveMode.Update); return OpenInUpdateMode(); } } /// <summary> /// Returns the FullName of the entry. /// </summary> /// <returns>FullName of the entry</returns> public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FullName; } /* public void MoveTo(String destinationEntryName) { if (destinationEntryName == null) throw new ArgumentNullException("destinationEntryName"); if (String.IsNullOrEmpty(destinationEntryName)) throw new ArgumentException("destinationEntryName cannot be empty", "destinationEntryName"); if (_archive == null) throw new InvalidOperationException("Attempt to move a deleted entry"); if (_archive._isDisposed) throw new ObjectDisposedException(_archive.ToString()); if (_archive.Mode != ZipArchiveMode.Update) throw new NotSupportedException("MoveTo can only be used when the archive is in Update mode"); String oldFilename = _filename; _filename = destinationEntryName; if (_filenameLength > UInt16.MaxValue) { _filename = oldFilename; throw new ArgumentException("Archive entry names must be smaller than 2^16 bytes"); } } */ #region Privates // Only allow opening ZipArchives with large ZipArchiveEntries in update mode when running in a 64-bit process. // This is for compatibility with old behavior that threw an exception for all process bitnesses, because this // will not work in a 32-bit process. private static readonly bool s_allowLargeZipArchiveEntriesInUpdateMode = IntPtr.Size > 4; internal Boolean EverOpenedForWrite { get { return _everOpenedForWrite; } } private Int64 OffsetOfCompressedData { get { if (_storedOffsetOfCompressedData == null) { _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); //by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength //to find start of data, but still using central directory size information if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader)) throw new InvalidDataException(SR.LocalFileHeaderCorrupt); _storedOffsetOfCompressedData = _archive.ArchiveStream.Position; } return _storedOffsetOfCompressedData.Value; } } private MemoryStream UncompressedData { get { if (_storedUncompressedData == null) { //this means we have never opened it before //if _uncompressedSize > Int32.MaxValue, it's still okay, because MemoryStream will just //grow as data is copied into it _storedUncompressedData = new MemoryStream((Int32)_uncompressedSize); if (_originallyInArchive) { using (Stream decompressor = OpenInReadMode(false)) { try { decompressor.CopyTo(_storedUncompressedData); } catch (InvalidDataException) { /* this is the case where the archive say the entry is deflate, but deflateStream * throws an InvalidDataException. This property should only be getting accessed in * Update mode, so we want to make sure _storedUncompressedData stays null so * that later when we dispose the archive, this entry loads the compressedBytes, and * copies them straight over */ _storedUncompressedData.Dispose(); _storedUncompressedData = null; _currentlyOpenForWrite = false; _everOpenedForWrite = false; throw; } } } //if they start modifying it, we should make sure it will get deflated CompressionMethod = CompressionMethodValues.Deflate; } return _storedUncompressedData; } } private CompressionMethodValues CompressionMethod { get { return _storedCompressionMethod; } set { if (value == CompressionMethodValues.Deflate) VersionToExtractAtLeast(ZipVersionNeededValues.Deflate); _storedCompressionMethod = value; } } private Encoding DefaultSystemEncoding { // On the desktop, this was Encoding.GetEncoding(0), which gives you the encoding object // that corresponds too the default system codepage. // However, in ProjectN, not only Encoding.GetEncoding(Int32) is not exposed, but there is also // no guarantee that a notion of a default system code page exists on the OS. // In fact, we can really only rely on UTF8 and UTF16 being present on all platforms. // We fall back to UTF8 as this is what is used by ZIP when as the "unicode encoding". get { return Encoding.UTF8; // return Encoding.GetEncoding(0); } } private String DecodeEntryName(Byte[] entryNameBytes) { Debug.Assert(entryNameBytes != null); Encoding readEntryNameEncoding; if ((_generalPurposeBitFlag & BitFlagValues.UnicodeFileName) == 0) { readEntryNameEncoding = (_archive == null) ? DefaultSystemEncoding : _archive.EntryNameEncoding ?? DefaultSystemEncoding; } else { readEntryNameEncoding = Encoding.UTF8; } return readEntryNameEncoding.GetString(entryNameBytes); } private Byte[] EncodeEntryName(String entryName, out bool isUTF8) { Debug.Assert(entryName != null); Encoding writeEntryNameEncoding; if (_archive != null && _archive.EntryNameEncoding != null) writeEntryNameEncoding = _archive.EntryNameEncoding; else writeEntryNameEncoding = ZipHelper.RequiresUnicode(entryName) ? Encoding.UTF8 : DefaultSystemEncoding; isUTF8 = writeEntryNameEncoding.Equals(Encoding.UTF8); return writeEntryNameEncoding.GetBytes(entryName); } /* does almost everything you need to do to forget about this entry * writes the local header/data, gets rid of all the data, * closes all of the streams except for the very outermost one that * the user holds on to and is responsible for closing * * after calling this, and only after calling this can we be guaranteed * that we are reading to write the central directory * * should only throw an exception in extremely exceptional cases because it is called from dispose */ internal void WriteAndFinishLocalEntry() { CloseStreams(); WriteLocalFileHeaderAndDataIfNeeded(); UnloadStreams(); } //should only throw an exception in extremely exceptional cases because it is called from dispose internal void WriteCentralDirectoryFileHeader() { //This part is simple, because we should definitely know the sizes by this time BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); //_entryname only gets set when we read in or call moveTo. MoveTo does a check, and //reading in should not be able to produce a entryname longer than UInt16.MaxValue Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue); //decide if we need the Zip64 extra field: Zip64ExtraField zip64ExtraField = new Zip64ExtraField(); UInt32 compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated; Boolean zip64Needed = false; if (SizesTooLarge() #if DEBUG_FORCE_ZIP64 || _archive._forceZip64 #endif ) { zip64Needed = true; compressedSizeTruncated = ZipHelper.Mask32Bit; uncompressedSizeTruncated = ZipHelper.Mask32Bit; //If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways zip64ExtraField.CompressedSize = _compressedSize; zip64ExtraField.UncompressedSize = _uncompressedSize; } else { compressedSizeTruncated = (UInt32)_compressedSize; uncompressedSizeTruncated = (UInt32)_uncompressedSize; } if (_offsetOfLocalHeader > UInt32.MaxValue #if DEBUG_FORCE_ZIP64 || _archive._forceZip64 #endif ) { zip64Needed = true; offsetOfLocalHeaderTruncated = ZipHelper.Mask32Bit; //If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways zip64ExtraField.LocalHeaderOffset = _offsetOfLocalHeader; } else { offsetOfLocalHeaderTruncated = (UInt32)_offsetOfLocalHeader; } if (zip64Needed) VersionToExtractAtLeast(ZipVersionNeededValues.Zip64); //determine if we can fit zip64 extra field and original extra fields all in Int32 bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0) + (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0); UInt16 extraFieldLength; if (bigExtraFieldLength > UInt16.MaxValue) { extraFieldLength = (UInt16)(zip64Needed ? zip64ExtraField.TotalSize : 0); _cdUnknownExtraFields = null; } else { extraFieldLength = (UInt16)bigExtraFieldLength; } writer.Write(ZipCentralDirectoryFileHeader.SignatureConstant); // Central directory file header signature (4 bytes) writer.Write(_versionMadeBySpecification); // Version made by Specification (version) (1 byte) writer.Write((byte)CurrentZipPlatform); // Version made by Compatibility (type) (1 byte) writer.Write((UInt16)_versionToExtract); // Minimum version needed to extract (2 bytes) writer.Write((UInt16)_generalPurposeBitFlag); // General Purpose bit flag (2 bytes) writer.Write((UInt16)CompressionMethod); // The Compression method (2 bytes) writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // File last modification time and date (4 bytes) writer.Write(_crc32); // CRC-32 (4 bytes) writer.Write(compressedSizeTruncated); // Compressed Size (4 bytes) writer.Write(uncompressedSizeTruncated); // Uncompressed Size (4 bytes) writer.Write((UInt16)_storedEntryNameBytes.Length); // File Name Length (2 bytes) writer.Write(extraFieldLength); // Extra Field Length (2 bytes) // This should hold because of how we read it originally in ZipCentralDirectoryFileHeader: Debug.Assert((_fileComment == null) || (_fileComment.Length <= UInt16.MaxValue)); writer.Write(_fileComment != null ? (UInt16)_fileComment.Length : (UInt16)0); //file comment length writer.Write((UInt16)0); //disk number start writer.Write((UInt16)0); //internal file attributes writer.Write((UInt32)0); //external file attributes writer.Write(offsetOfLocalHeaderTruncated); //offset of local header writer.Write(_storedEntryNameBytes); //write extra fields if (zip64Needed) zip64ExtraField.WriteBlock(_archive.ArchiveStream); if (_cdUnknownExtraFields != null) ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream); if (_fileComment != null) writer.Write(_fileComment); } //returns false if fails, will get called on every entry before closing in update mode //can throw InvalidDataException internal Boolean LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded() { String message; //we should have made this exact call in _archive.Init through ThrowIfOpenable Debug.Assert(IsOpenable(false, true, out message)); //load local header's extra fields. it will be null if we couldn't read for some reason if (_originallyInArchive) { _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); _lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader); } if (!_everOpenedForWrite && _originallyInArchive) { //we know that it is openable at this point _compressedBytes = new Byte[(_compressedSize / MaxSingleBufferSize) + 1][]; for (int i = 0; i < _compressedBytes.Length - 1; i++) { _compressedBytes[i] = new Byte[MaxSingleBufferSize]; } _compressedBytes[_compressedBytes.Length - 1] = new Byte[_compressedSize % MaxSingleBufferSize]; _archive.ArchiveStream.Seek(OffsetOfCompressedData, SeekOrigin.Begin); for (int i = 0; i < _compressedBytes.Length - 1; i++) { ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[i], MaxSingleBufferSize); } ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[_compressedBytes.Length - 1], (Int32)(_compressedSize % MaxSingleBufferSize)); } return true; } internal void ThrowIfNotOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory) { String message; if (!IsOpenable(needToUncompress, needToLoadIntoMemory, out message)) throw new InvalidDataException(message); } private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, Boolean leaveBackingStreamOpen, EventHandler onClose) { //stream stack: backingStream -> DeflateStream -> CheckSumWriteStream //we should always be compressing with deflate. Stored is used for empty files, but we don't actually //call through this function for that - we just write the stored value in the header Debug.Assert(CompressionMethod == CompressionMethodValues.Deflate); Stream compressorStream = _compressionLevel.HasValue ? new DeflateStream(backingStream, _compressionLevel.Value, leaveBackingStreamOpen) : new DeflateStream(backingStream, CompressionMode.Compress, leaveBackingStreamOpen); Boolean isIntermediateStream = true; Boolean leaveCompressorStreamOpenOnClose = leaveBackingStreamOpen && !isIntermediateStream; var checkSumStream = new CheckSumAndSizeWriteStream( compressorStream, backingStream, leaveCompressorStreamOpenOnClose, this, onClose, (Int64 initialPosition, Int64 currentPosition, UInt32 checkSum, Stream backing, ZipArchiveEntry thisRef, EventHandler closeHandler) => { thisRef._crc32 = checkSum; thisRef._uncompressedSize = currentPosition; thisRef._compressedSize = backing.Position - initialPosition; if (closeHandler != null) closeHandler(thisRef, EventArgs.Empty); }); return checkSumStream; } private Stream GetDataDecompressor(Stream compressedStreamToRead) { Stream uncompressedStream = null; switch (CompressionMethod) { case CompressionMethodValues.Deflate: uncompressedStream = new DeflateStream(compressedStreamToRead, CompressionMode.Decompress); break; case CompressionMethodValues.Stored: default: //we can assume that only deflate/stored are allowed because we assume that //IsOpenable is checked before this function is called Debug.Assert(CompressionMethod == CompressionMethodValues.Stored); uncompressedStream = compressedStreamToRead; break; } return uncompressedStream; } private Stream OpenInReadMode(Boolean checkOpenable) { if (checkOpenable) ThrowIfNotOpenable(true, false); Stream compressedStream = new SubReadStream(_archive.ArchiveStream, OffsetOfCompressedData, _compressedSize); return GetDataDecompressor(compressedStream); } private Stream OpenInWriteMode() { if (_everOpenedForWrite) throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime); //we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed Debug.Assert(_archive.IsStillArchiveStreamOwner(this)); _everOpenedForWrite = true; CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true, (object o, EventArgs e) => { //release the archive stream var entry = (ZipArchiveEntry)o; entry._archive.ReleaseArchiveStream(entry); entry._outstandingWriteStream = null; }); _outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this); return new WrappedStream(baseStream: _outstandingWriteStream, closeBaseStream: true); } private Stream OpenInUpdateMode() { if (_currentlyOpenForWrite) throw new IOException(SR.UpdateModeOneStream); ThrowIfNotOpenable(true, true); _everOpenedForWrite = true; _currentlyOpenForWrite = true; //always put it at the beginning for them UncompressedData.Seek(0, SeekOrigin.Begin); return new WrappedStream(UncompressedData, this, thisRef => { //once they close, we know uncompressed length, but still not compressed length //so we don't fill in any size information //those fields get figured out when we call GetCompressor as we write it to //the actual archive thisRef._currentlyOpenForWrite = false; }); } private Boolean IsOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory, out String message) { message = null; if (_originallyInArchive) { if (needToUncompress) { if (CompressionMethod != CompressionMethodValues.Stored && CompressionMethod != CompressionMethodValues.Deflate) { message = SR.UnsupportedCompression; return false; } } if (_diskNumberStart != _archive.NumberOfThisDisk) { message = SR.SplitSpanned; return false; } if (_offsetOfLocalHeader > _archive.ArchiveStream.Length) { message = SR.LocalFileHeaderCorrupt; return false; } _archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin); if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader)) { message = SR.LocalFileHeaderCorrupt; return false; } //when this property gets called, some duplicated work if (OffsetOfCompressedData + _compressedSize > _archive.ArchiveStream.Length) { message = SR.LocalFileHeaderCorrupt; return false; } //This limitation originally existed because a) it is unreasonable to load > 4GB into memory //but also because the stream reading functions make it hard. This has been updated to handle //this scenario in a 64-bit process using multiple buffers, delivered first as an OOB for //compatibility. if (needToLoadIntoMemory) { if (_compressedSize > Int32.MaxValue) { if (!s_allowLargeZipArchiveEntriesInUpdateMode) { message = SR.EntryTooLarge; return false; } } } } return true; } private Boolean SizesTooLarge() { return _compressedSize > UInt32.MaxValue || _uncompressedSize > UInt32.MaxValue; } //return value is true if we allocated an extra field for 64 bit headers, un/compressed size private Boolean WriteLocalFileHeader(Boolean isEmptyFile) { BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); //_entryname only gets set when we read in or call moveTo. MoveTo does a check, and //reading in should not be able to produce a entryname longer than UInt16.MaxValue Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue); //decide if we need the Zip64 extra field: Zip64ExtraField zip64ExtraField = new Zip64ExtraField(); Boolean zip64Used = false; UInt32 compressedSizeTruncated, uncompressedSizeTruncated; //if we already know that we have an empty file don't worry about anything, just do a straight shot of the header if (isEmptyFile) { CompressionMethod = CompressionMethodValues.Stored; compressedSizeTruncated = 0; uncompressedSizeTruncated = 0; Debug.Assert(_compressedSize == 0); Debug.Assert(_uncompressedSize == 0); Debug.Assert(_crc32 == 0); } else { //if we have a non-seekable stream, don't worry about sizes at all, and just set the right bit //if we are using the data descriptor, then sizes and crc should be set to 0 in the header if (_archive.Mode == ZipArchiveMode.Create && _archive.ArchiveStream.CanSeek == false && !isEmptyFile) { _generalPurposeBitFlag |= BitFlagValues.DataDescriptor; zip64Used = false; compressedSizeTruncated = 0; uncompressedSizeTruncated = 0; //the crc should not have been set if we are in create mode, but clear it just to be sure Debug.Assert(_crc32 == 0); } else //if we are not in streaming mode, we have to decide if we want to write zip64 headers { if (SizesTooLarge() #if DEBUG_FORCE_ZIP64 || (_archive._forceZip64 && _archive.Mode == ZipArchiveMode.Update) #endif ) { zip64Used = true; compressedSizeTruncated = ZipHelper.Mask32Bit; uncompressedSizeTruncated = ZipHelper.Mask32Bit; //prepare Zip64 extra field object. If we have one of the sizes, the other must go in there zip64ExtraField.CompressedSize = _compressedSize; zip64ExtraField.UncompressedSize = _uncompressedSize; VersionToExtractAtLeast(ZipVersionNeededValues.Zip64); } else { zip64Used = false; compressedSizeTruncated = (UInt32)_compressedSize; uncompressedSizeTruncated = (UInt32)_uncompressedSize; } } } //save offset _offsetOfLocalHeader = writer.BaseStream.Position; //calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important Int32 bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0) + (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0); UInt16 extraFieldLength; if (bigExtraFieldLength > UInt16.MaxValue) { extraFieldLength = (UInt16)(zip64Used ? zip64ExtraField.TotalSize : 0); _lhUnknownExtraFields = null; } else { extraFieldLength = (UInt16)bigExtraFieldLength; } //write header writer.Write(ZipLocalFileHeader.SignatureConstant); writer.Write((UInt16)_versionToExtract); writer.Write((UInt16)_generalPurposeBitFlag); writer.Write((UInt16)CompressionMethod); writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); //UInt32 writer.Write(_crc32); //UInt32 writer.Write(compressedSizeTruncated); //UInt32 writer.Write(uncompressedSizeTruncated); //UInt32 writer.Write((UInt16)_storedEntryNameBytes.Length); writer.Write(extraFieldLength); //UInt16 writer.Write(_storedEntryNameBytes); if (zip64Used) zip64ExtraField.WriteBlock(_archive.ArchiveStream); if (_lhUnknownExtraFields != null) ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream); return zip64Used; } private void WriteLocalFileHeaderAndDataIfNeeded() { //_storedUncompressedData gets frozen here, and is what gets written to the file if (_storedUncompressedData != null || _compressedBytes != null) { if (_storedUncompressedData != null) { _uncompressedSize = _storedUncompressedData.Length; //The compressor fills in CRC and sizes //The DirectToArchiveWriterStream writes headers and such using (Stream entryWriter = new DirectToArchiveWriterStream( GetDataCompressor(_archive.ArchiveStream, true, null), this)) { _storedUncompressedData.Seek(0, SeekOrigin.Begin); _storedUncompressedData.CopyTo(entryWriter); _storedUncompressedData.Dispose(); _storedUncompressedData = null; } } else { // we know the sizes at this point, so just go ahead and write the headers if (_uncompressedSize == 0) CompressionMethod = CompressionMethodValues.Stored; WriteLocalFileHeader(false); foreach (Byte[] compressedBytes in _compressedBytes) { _archive.ArchiveStream.Write(compressedBytes, 0, compressedBytes.Length); } } } else //there is no data in the file, but if we are in update mode, we still need to write a header { if (_archive.Mode == ZipArchiveMode.Update || !_everOpenedForWrite) { _everOpenedForWrite = true; WriteLocalFileHeader(true); } } } /* Using _offsetOfLocalHeader, seeks back to where CRC and sizes should be in the header, * writes them, then seeks back to where you started * Assumes that the stream is currently at the end of the data */ private void WriteCrcAndSizesInLocalHeader(Boolean zip64HeaderUsed) { Int64 finalPosition = _archive.ArchiveStream.Position; BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); Boolean zip64Needed = SizesTooLarge() #if DEBUG_FORCE_ZIP64 || _archive._forceZip64 #endif ; Boolean pretendStreaming = zip64Needed && !zip64HeaderUsed; UInt32 compressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_compressedSize; UInt32 uncompressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_uncompressedSize; /* first step is, if we need zip64, but didn't allocate it, pretend we did a stream write, because * we can't go back and give ourselves the space that the extra field needs. * we do this by setting the correct property in the bit flag */ if (pretendStreaming) { _generalPurposeBitFlag |= BitFlagValues.DataDescriptor; _archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToBitFlagFromHeaderStart, SeekOrigin.Begin); writer.Write((UInt16)_generalPurposeBitFlag); } /* next step is fill out the 32-bit size values in the normal header. we can't assume that * they are correct. we also write the CRC */ _archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToCrcFromHeaderStart, SeekOrigin.Begin); if (!pretendStreaming) { writer.Write(_crc32); writer.Write(compressedSizeTruncated); writer.Write(uncompressedSizeTruncated); } else //but if we are pretending to stream, we want to fill in with zeroes { writer.Write((UInt32)0); writer.Write((UInt32)0); writer.Write((UInt32)0); } /* next step: if we wrote the 64 bit header initially, a different implementation might * try to read it, even if the 32-bit size values aren't masked. thus, we should always put the * correct size information in there. note that order of uncomp/comp is switched, and these are * 64-bit values * also, note that in order for this to be correct, we have to insure that the zip64 extra field * is alwasy the first extra field that is written */ if (zip64HeaderUsed) { _archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.SizeOfLocalHeader + _storedEntryNameBytes.Length + Zip64ExtraField.OffsetToFirstField, SeekOrigin.Begin); writer.Write(_uncompressedSize); writer.Write(_compressedSize); _archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin); } // now go to the where we were. assume that this is the end of the data _archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin); /* if we are pretending we did a stream write, we want to write the data descriptor out * the data descriptor can have 32-bit sizes or 64-bit sizes. In this case, we always use * 64-bit sizes */ if (pretendStreaming) { writer.Write(_crc32); writer.Write(_compressedSize); writer.Write(_uncompressedSize); } } private void WriteDataDescriptor() { // data descriptor can be 32-bit or 64-bit sizes. 32-bit is more compatible, so use that if possible // signature is optional but recommended by the spec BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream); writer.Write(ZipLocalFileHeader.DataDescriptorSignature); writer.Write(_crc32); if (SizesTooLarge()) { writer.Write(_compressedSize); writer.Write(_uncompressedSize); } else { writer.Write((UInt32)_compressedSize); writer.Write((UInt32)_uncompressedSize); } } private void UnloadStreams() { if (_storedUncompressedData != null) _storedUncompressedData.Dispose(); _compressedBytes = null; _outstandingWriteStream = null; } private void CloseStreams() { //if the user left the stream open, close the underlying stream for them if (_outstandingWriteStream != null) { _outstandingWriteStream.Dispose(); } } private void VersionToExtractAtLeast(ZipVersionNeededValues value) { if (_versionToExtract < value) { _versionToExtract = value; } } private void ThrowIfInvalidArchive() { if (_archive == null) throw new InvalidOperationException(SR.DeletedEntry); _archive.ThrowIfDisposed(); } /// <summary> /// Gets the file name of the path based on Windows path separator characters /// </summary> private static string GetFileName_Windows(string path) { int length = path.Length; for (int i = length; --i >= 0;) { char ch = path[i]; if (ch == '\\' || ch == '/' || ch == ':') return path.Substring(i + 1); } return path; } /// <summary> /// Gets the file name of the path based on Unix path separator characters /// </summary> private static string GetFileName_Unix(string path) { int length = path.Length; for (int i = length; --i >= 0;) if (path[i] == '/') return path.Substring(i + 1); return path; } #endregion Privates #region Nested Types private class DirectToArchiveWriterStream : Stream { #region fields private Int64 _position; private CheckSumAndSizeWriteStream _crcSizeStream; private Boolean _everWritten; private Boolean _isDisposed; private ZipArchiveEntry _entry; private Boolean _usedZip64inLH; private Boolean _canWrite; #endregion #region constructors //makes the assumption that somewhere down the line, crcSizeStream is eventually writing directly to the archive //this class calls other functions on ZipArchiveEntry that write directly to the archive public DirectToArchiveWriterStream(CheckSumAndSizeWriteStream crcSizeStream, ZipArchiveEntry entry) { _position = 0; _crcSizeStream = crcSizeStream; _everWritten = false; _isDisposed = false; _entry = entry; _usedZip64inLH = false; _canWrite = true; } #endregion #region properties public override Int64 Length { get { ThrowIfDisposed(); throw new NotSupportedException(SR.SeekingNotSupported); } } public override Int64 Position { get { Contract.Ensures(Contract.Result<Int64>() >= 0); ThrowIfDisposed(); return _position; } set { ThrowIfDisposed(); throw new NotSupportedException(SR.SeekingNotSupported); } } public override Boolean CanRead { get { return false; } } public override Boolean CanSeek { get { return false; } } public override Boolean CanWrite { get { return _canWrite; } } #endregion #region methods private void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(this.GetType().ToString(), SR.HiddenStreamName); } public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count) { ThrowIfDisposed(); throw new NotSupportedException(SR.ReadingNotSupported); } public override Int64 Seek(Int64 offset, SeekOrigin origin) { ThrowIfDisposed(); throw new NotSupportedException(SR.SeekingNotSupported); } public override void SetLength(Int64 value) { ThrowIfDisposed(); throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting); } //careful: assumes that write is the only way to write to the stream, if writebyte/beginwrite are implemented //they must set _everWritten, etc. public override void Write(Byte[] buffer, Int32 offset, Int32 count) { //we can't pass the argument checking down a level if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentNeedNonNegative); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentNeedNonNegative); if ((buffer.Length - offset) < count) throw new ArgumentException(SR.OffsetLengthInvalid); Contract.EndContractBlock(); ThrowIfDisposed(); Debug.Assert(CanWrite); //if we're not actually writing anything, we don't want to trigger the header if (count == 0) return; if (!_everWritten) { _everWritten = true; //write local header, we are good to go _usedZip64inLH = _entry.WriteLocalFileHeader(false); } _crcSizeStream.Write(buffer, offset, count); _position += count; } public override void Flush() { ThrowIfDisposed(); Debug.Assert(CanWrite); _crcSizeStream.Flush(); } protected override void Dispose(Boolean disposing) { if (disposing && !_isDisposed) { _crcSizeStream.Dispose(); //now we have size/crc info if (!_everWritten) { //write local header, no data, so we use stored _entry.WriteLocalFileHeader(true); } else { //go back and finish writing if (_entry._archive.ArchiveStream.CanSeek) //finish writing local header if we have seek capabilities _entry.WriteCrcAndSizesInLocalHeader(_usedZip64inLH); else //write out data descriptor if we don't have seek capabilities _entry.WriteDataDescriptor(); } _canWrite = false; _isDisposed = true; } base.Dispose(disposing); } #endregion } // DirectToArchiveWriterStream [Flags] private enum BitFlagValues : ushort { DataDescriptor = 0x8, UnicodeFileName = 0x800 } private enum CompressionMethodValues : ushort { Stored = 0x0, Deflate = 0x8 } private enum OpenableValues { Openable, FileNonExistent, FileTooLarge } #endregion Nested Types } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Errors; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal enum ACCESSERROR { ACCESSERROR_NOACCESS, ACCESSERROR_NOACCESSTHRU, ACCESSERROR_NOERROR }; // // Semantic check methods on SymbolLoader // internal static class CSemanticChecker { // Generate an error if CType is static. public static void CheckForStaticClass(CType type) { if (type.IsStaticClass) { throw ErrorHandling.Error(ErrorCode.ERR_ConvertToStaticClass, type); } } public static ACCESSERROR CheckAccess2(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { Debug.Assert(symCheck != null); Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.OwningAggregate); Debug.Assert(typeThru == null || typeThru is AggregateType || typeThru is TypeParameterType || typeThru is ArrayType || typeThru is NullableType); #if DEBUG switch (symCheck.getKind()) { case SYMKIND.SK_MethodSymbol: case SYMKIND.SK_PropertySymbol: case SYMKIND.SK_FieldSymbol: case SYMKIND.SK_EventSymbol: Debug.Assert(atsCheck != null); break; } #endif // DEBUG ACCESSERROR error = CheckAccessCore(symCheck, atsCheck, symWhere, typeThru); if (ACCESSERROR.ACCESSERROR_NOERROR != error) { return error; } // Check the accessibility of the return CType. CType type = symCheck.getType(); if (type == null) { return ACCESSERROR.ACCESSERROR_NOERROR; } // For members of AGGSYMs, atsCheck should always be specified! Debug.Assert(atsCheck != null); // Substitute on the CType. if (atsCheck.TypeArgsAll.Count > 0) { type = TypeManager.SubstType(type, atsCheck); } return CheckTypeAccess(type, symWhere) ? ACCESSERROR.ACCESSERROR_NOERROR : ACCESSERROR.ACCESSERROR_NOACCESS; } public static bool CheckTypeAccess(CType type, Symbol symWhere) { Debug.Assert(type != null); // Array, Ptr, Nub, etc don't matter. type = type.GetNakedType(true); if (!(type is AggregateType ats)) { Debug.Assert(type is VoidType || type is TypeParameterType); return true; } do { if (ACCESSERROR.ACCESSERROR_NOERROR != CheckAccessCore(ats.OwningAggregate, ats.OuterType, symWhere, null)) { return false; } ats = ats.OuterType; } while(ats != null); TypeArray typeArgs = ((AggregateType)type).TypeArgsAll; for (int i = 0; i < typeArgs.Count; i++) { if (!CheckTypeAccess(typeArgs[i], symWhere)) return false; } return true; } private static ACCESSERROR CheckAccessCore(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) { Debug.Assert(symCheck != null); Debug.Assert(atsCheck == null || symCheck.parent == atsCheck.OwningAggregate); Debug.Assert(typeThru == null || typeThru is AggregateType || typeThru is TypeParameterType || typeThru is ArrayType || typeThru is NullableType); switch (symCheck.GetAccess()) { default: throw Error.InternalCompilerError(); //return ACCESSERROR.ACCESSERROR_NOACCESS; case ACCESS.ACC_UNKNOWN: return ACCESSERROR.ACCESSERROR_NOACCESS; case ACCESS.ACC_PUBLIC: return ACCESSERROR.ACCESSERROR_NOERROR; case ACCESS.ACC_PRIVATE: case ACCESS.ACC_PROTECTED: if (symWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } break; case ACCESS.ACC_INTERNAL: case ACCESS.ACC_INTERNALPROTECTED: // Check internal, then protected. if (symWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } if (symWhere.SameAssemOrFriend(symCheck)) { return ACCESSERROR.ACCESSERROR_NOERROR; } if (symCheck.GetAccess() == ACCESS.ACC_INTERNAL) { return ACCESSERROR.ACCESSERROR_NOACCESS; } break; case ACCESS.ACC_INTERNAL_AND_PROTECTED: if (symWhere == null || !symWhere.SameAssemOrFriend(symCheck)) { return ACCESSERROR.ACCESSERROR_NOACCESS; } break; } // Find the inner-most enclosing AggregateSymbol. AggregateSymbol aggWhere = null; for (Symbol symT = symWhere; symT != null; symT = symT.parent) { if (symT is AggregateSymbol aggSym) { aggWhere = aggSym; break; } } if (aggWhere == null) { return ACCESSERROR.ACCESSERROR_NOACCESS; } // Should always have atsCheck for private and protected access check. // We currently don't need it since access doesn't respect instantiation. // We just use symWhere.parent as AggregateSymbol instead. AggregateSymbol aggCheck = symCheck.parent as AggregateSymbol; // First check for private access. for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg()) { if (agg == aggCheck) { return ACCESSERROR.ACCESSERROR_NOERROR; } } if (symCheck.GetAccess() == ACCESS.ACC_PRIVATE) { return ACCESSERROR.ACCESSERROR_NOACCESS; } // Handle the protected case - which is the only real complicated one. Debug.Assert(symCheck.GetAccess() == ACCESS.ACC_PROTECTED || symCheck.GetAccess() == ACCESS.ACC_INTERNALPROTECTED || symCheck.GetAccess() == ACCESS.ACC_INTERNAL_AND_PROTECTED); // Check if symCheck is in aggWhere or a base of aggWhere, // or in an outer agg of aggWhere or a base of an outer agg of aggWhere. AggregateType atsThru = null; if (typeThru != null && !symCheck.isStatic) { atsThru = typeThru.GetAts(); } // Look for aggCheck among the base classes of aggWhere and outer aggs. bool found = false; for (AggregateSymbol agg = aggWhere; agg != null; agg = agg.GetOuterAgg()) { Debug.Assert(agg != aggCheck); // We checked for this above. // Look for aggCheck among the base classes of agg. if (agg.FindBaseAgg(aggCheck)) { found = true; // aggCheck is a base class of agg. Check atsThru. // For non-static protected access to be legal, atsThru must be an instantiation of // agg or a CType derived from an instantiation of agg. In this case // all that matters is that agg is in the base AggregateSymbol chain of atsThru. The // actual AGGTYPESYMs involved don't matter. if (atsThru == null || atsThru.OwningAggregate.FindBaseAgg(agg)) { return ACCESSERROR.ACCESSERROR_NOERROR; } } } // the CType in which the method is being called has no relationship with the // CType on which the method is defined surely this is NOACCESS and not NOACCESSTHRU return found ? ACCESSERROR.ACCESSERROR_NOACCESSTHRU : ACCESSERROR.ACCESSERROR_NOACCESS; } public static bool CheckBogus(Symbol sym) => (sym as PropertySymbol)?.Bogus ?? false; public static RuntimeBinderException ReportAccessError(SymWithType swtBad, Symbol symWhere, CType typeQual) { Debug.Assert(!CheckAccess(swtBad.Sym, swtBad.GetType(), symWhere, typeQual) || !CheckTypeAccess(swtBad.GetType(), symWhere)); return CheckAccess2(swtBad.Sym, swtBad.GetType(), symWhere, typeQual) == ACCESSERROR.ACCESSERROR_NOACCESSTHRU ? ErrorHandling.Error(ErrorCode.ERR_BadProtectedAccess, swtBad, typeQual, symWhere) : ErrorHandling.Error(ErrorCode.ERR_BadAccess, swtBad); } public static bool CheckAccess(Symbol symCheck, AggregateType atsCheck, Symbol symWhere, CType typeThru) => CheckAccess2(symCheck, atsCheck, symWhere, typeThru) == ACCESSERROR.ACCESSERROR_NOERROR; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class CacheControlHeaderValueTest { [Fact] public void Properties_SetAndGetAllProperties_SetValueReturnedInGetter() { CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); // Bool properties cacheControl.NoCache = true; Assert.True(cacheControl.NoCache); cacheControl.NoStore = true; Assert.True(cacheControl.NoStore); cacheControl.MaxStale = true; Assert.True(cacheControl.MaxStale); cacheControl.NoTransform = true; Assert.True(cacheControl.NoTransform); cacheControl.OnlyIfCached = true; Assert.True(cacheControl.OnlyIfCached); cacheControl.Public = true; Assert.True(cacheControl.Public); cacheControl.Private = true; Assert.True(cacheControl.Private); cacheControl.MustRevalidate = true; Assert.True(cacheControl.MustRevalidate); cacheControl.ProxyRevalidate = true; Assert.True(cacheControl.ProxyRevalidate); // TimeSpan properties TimeSpan timeSpan = new TimeSpan(1, 2, 3); cacheControl.MaxAge = timeSpan; Assert.Equal(timeSpan, cacheControl.MaxAge); cacheControl.SharedMaxAge = timeSpan; Assert.Equal(timeSpan, cacheControl.SharedMaxAge); cacheControl.MaxStaleLimit = timeSpan; Assert.Equal(timeSpan, cacheControl.MaxStaleLimit); cacheControl.MinFresh = timeSpan; Assert.Equal(timeSpan, cacheControl.MinFresh); // String collection properties Assert.NotNull(cacheControl.NoCacheHeaders); Assert.Throws<ArgumentException>(() => { cacheControl.NoCacheHeaders.Add(null); }); Assert.Throws<FormatException>(() => { cacheControl.NoCacheHeaders.Add("invalid token"); }); cacheControl.NoCacheHeaders.Add("token"); Assert.Equal(1, cacheControl.NoCacheHeaders.Count); Assert.Equal("token", cacheControl.NoCacheHeaders.First()); Assert.NotNull(cacheControl.PrivateHeaders); Assert.Throws<ArgumentException>(() => { cacheControl.PrivateHeaders.Add(null); }); Assert.Throws<FormatException>(() => { cacheControl.PrivateHeaders.Add("invalid token"); }); cacheControl.PrivateHeaders.Add("token"); Assert.Equal(1, cacheControl.PrivateHeaders.Count); Assert.Equal("token", cacheControl.PrivateHeaders.First()); // NameValueHeaderValue collection property Assert.NotNull(cacheControl.Extensions); Assert.Throws<ArgumentNullException>(() => { cacheControl.Extensions.Add(null); }); cacheControl.Extensions.Add(new NameValueHeaderValue("name", "value")); Assert.Equal(1, cacheControl.Extensions.Count); Assert.Equal(new NameValueHeaderValue("name", "value"), cacheControl.Extensions.First()); } [Fact] public void ToString_UseRequestDirectiveValues_AllSerializedCorrectly() { CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); Assert.Equal("", cacheControl.ToString()); // Note that we allow all combinations of all properties even though the RFC specifies rules what value // can be used together. // Also for property pairs (bool property + collection property) like 'NoCache' and 'NoCacheHeaders' the // caller needs to set the bool property in order for the collection to be populated as string. // Cache Request Directive sample cacheControl.NoStore = true; Assert.Equal("no-store", cacheControl.ToString()); cacheControl.NoCache = true; Assert.Equal("no-store, no-cache", cacheControl.ToString()); cacheControl.MaxAge = new TimeSpan(0, 1, 10); Assert.Equal("no-store, no-cache, max-age=70", cacheControl.ToString()); cacheControl.MaxStale = true; Assert.Equal("no-store, no-cache, max-age=70, max-stale", cacheControl.ToString()); cacheControl.MaxStaleLimit = new TimeSpan(0, 2, 5); Assert.Equal("no-store, no-cache, max-age=70, max-stale=125", cacheControl.ToString()); cacheControl.MinFresh = new TimeSpan(0, 3, 0); Assert.Equal("no-store, no-cache, max-age=70, max-stale=125, min-fresh=180", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.NoTransform = true; Assert.Equal("no-transform", cacheControl.ToString()); cacheControl.OnlyIfCached = true; Assert.Equal("no-transform, only-if-cached", cacheControl.ToString()); cacheControl.Extensions.Add(new NameValueHeaderValue("custom")); cacheControl.Extensions.Add(new NameValueHeaderValue("customName", "customValue")); Assert.Equal("no-transform, only-if-cached, custom, customName=customValue", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.Extensions.Add(new NameValueHeaderValue("custom")); Assert.Equal("custom", cacheControl.ToString()); } [Fact] public void ToString_UseResponseDirectiveValues_AllSerializedCorrectly() { CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); Assert.Equal("", cacheControl.ToString()); cacheControl.NoCache = true; Assert.Equal("no-cache", cacheControl.ToString()); cacheControl.NoCacheHeaders.Add("token1"); Assert.Equal("no-cache=\"token1\"", cacheControl.ToString()); cacheControl.Public = true; Assert.Equal("public, no-cache=\"token1\"", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.Private = true; Assert.Equal("private", cacheControl.ToString()); cacheControl.PrivateHeaders.Add("token2"); cacheControl.PrivateHeaders.Add("token3"); Assert.Equal("private=\"token2, token3\"", cacheControl.ToString()); cacheControl.MustRevalidate = true; Assert.Equal("must-revalidate, private=\"token2, token3\"", cacheControl.ToString()); cacheControl.ProxyRevalidate = true; Assert.Equal("must-revalidate, proxy-revalidate, private=\"token2, token3\"", cacheControl.ToString()); } [Fact] public void GetHashCode_CompareValuesWithBoolFieldsSet_MatchExpectation() { // Verify that different bool fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[9]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].ProxyRevalidate = true; values[1].NoCache = true; values[2].NoStore = true; values[3].MaxStale = true; values[4].NoTransform = true; values[5].OnlyIfCached = true; values[6].Public = true; values[7].Private = true; values[8].MustRevalidate = true; // Only one bool field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareHashCodes(values[i], values[j], false); } } } // Validate that two instances with the same bool fields set are equal. values[0].NoCache = true; CompareHashCodes(values[0], values[1], false); values[1].ProxyRevalidate = true; CompareHashCodes(values[0], values[1], true); } [Fact] public void GetHashCode_CompareValuesWithTimeSpanFieldsSet_MatchExpectation() { // Verify that different timespan fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[4]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 1); values[2].MinFresh = new TimeSpan(0, 1, 1); values[3].SharedMaxAge = new TimeSpan(0, 1, 1); // Only one timespan field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareHashCodes(values[i], values[j], false); } } } values[0].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareHashCodes(values[0], values[1], false); values[1].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareHashCodes(values[0], values[1], true); } [Fact] public void GetHashCode_CompareCollectionFieldsSet_MatchExpectation() { CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue(); cacheControl1.NoCache = true; cacheControl1.NoCacheHeaders.Add("token2"); cacheControl2.NoCache = true; cacheControl2.NoCacheHeaders.Add("token1"); cacheControl2.NoCacheHeaders.Add("token2"); CompareHashCodes(cacheControl1, cacheControl2, false); cacheControl1.NoCacheHeaders.Add("token1"); CompareHashCodes(cacheControl1, cacheControl2, true); // Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders // have the same values, the hash code will be different. cacheControl3.Private = true; cacheControl3.PrivateHeaders.Add("token2"); CompareHashCodes(cacheControl1, cacheControl3, false); cacheControl4.Extensions.Add(new NameValueHeaderValue("custom")); CompareHashCodes(cacheControl1, cacheControl4, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV")); cacheControl5.Extensions.Add(new NameValueHeaderValue("custom")); CompareHashCodes(cacheControl4, cacheControl5, false); cacheControl4.Extensions.Add(new NameValueHeaderValue("customN", "customV")); CompareHashCodes(cacheControl4, cacheControl5, true); } [Fact] public void Equals_CompareValuesWithBoolFieldsSet_MatchExpectation() { // Verify that different bool fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[9]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].ProxyRevalidate = true; values[1].NoCache = true; values[2].NoStore = true; values[3].MaxStale = true; values[4].NoTransform = true; values[5].OnlyIfCached = true; values[6].Public = true; values[7].Private = true; values[8].MustRevalidate = true; // Only one bool field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareValues(values[i], values[j], false); } } } // Validate that two instances with the same bool fields set are equal. values[0].NoCache = true; CompareValues(values[0], values[1], false); values[1].ProxyRevalidate = true; CompareValues(values[0], values[1], true); } [Fact] public void Equals_CompareValuesWithTimeSpanFieldsSet_MatchExpectation() { // Verify that different timespan fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[4]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 1); values[2].MinFresh = new TimeSpan(0, 1, 1); values[3].SharedMaxAge = new TimeSpan(0, 1, 1); // Only one timespan field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareValues(values[i], values[j], false); } } } values[0].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareValues(values[0], values[1], false); values[1].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareValues(values[0], values[1], true); CacheControlHeaderValue value1 = new CacheControlHeaderValue(); value1.MaxStale = true; CacheControlHeaderValue value2 = new CacheControlHeaderValue(); value2.MaxStale = true; CompareValues(value1, value2, true); value2.MaxStaleLimit = new TimeSpan(1, 2, 3); CompareValues(value1, value2, false); } [Fact] public void Equals_CompareCollectionFieldsSet_MatchExpectation() { CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl6 = new CacheControlHeaderValue(); cacheControl1.NoCache = true; cacheControl1.NoCacheHeaders.Add("token2"); Assert.False(cacheControl1.Equals(null), "Compare with 'null'"); cacheControl2.NoCache = true; cacheControl2.NoCacheHeaders.Add("token1"); cacheControl2.NoCacheHeaders.Add("token2"); CompareValues(cacheControl1, cacheControl2, false); cacheControl1.NoCacheHeaders.Add("token1"); CompareValues(cacheControl1, cacheControl2, true); // Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders // have the same values, the hash code will be different. cacheControl3.Private = true; cacheControl3.PrivateHeaders.Add("token2"); CompareValues(cacheControl1, cacheControl3, false); cacheControl4.Private = true; cacheControl4.PrivateHeaders.Add("token3"); CompareValues(cacheControl3, cacheControl4, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("custom")); CompareValues(cacheControl1, cacheControl5, false); cacheControl6.Extensions.Add(new NameValueHeaderValue("customN", "customV")); cacheControl6.Extensions.Add(new NameValueHeaderValue("custom")); CompareValues(cacheControl5, cacheControl6, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV")); CompareValues(cacheControl5, cacheControl6, true); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { CacheControlHeaderValue source = new CacheControlHeaderValue(); source.Extensions.Add(new NameValueHeaderValue("custom")); source.Extensions.Add(new NameValueHeaderValue("customN", "customV")); source.MaxAge = new TimeSpan(1, 1, 1); source.MaxStale = true; source.MaxStaleLimit = new TimeSpan(1, 1, 2); source.MinFresh = new TimeSpan(1, 1, 3); source.MustRevalidate = true; source.NoCache = true; source.NoCacheHeaders.Add("token1"); source.NoStore = true; source.NoTransform = true; source.OnlyIfCached = true; source.Private = true; source.PrivateHeaders.Add("token2"); source.ProxyRevalidate = true; source.Public = true; source.SharedMaxAge = new TimeSpan(1, 1, 4); CacheControlHeaderValue clone = (CacheControlHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source, clone); } [Fact] public void GetCacheControlLength_DifferentValidScenariosAndNoExistingCacheControl_AllReturnNonZero() { CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoCache = true; CheckGetCacheControlLength("X , , no-cache ,,", 1, null, 16, expected); expected = new CacheControlHeaderValue(); expected.NoCache = true; expected.NoCacheHeaders.Add("token1"); expected.NoCacheHeaders.Add("token2"); CheckGetCacheControlLength("no-cache=\"token1, token2\"", 0, null, 25, expected); expected = new CacheControlHeaderValue(); expected.NoStore = true; expected.MaxAge = new TimeSpan(0, 0, 125); expected.MaxStale = true; CheckGetCacheControlLength("X no-store , max-age = 125, max-stale,", 1, null, 37, expected); expected = new CacheControlHeaderValue(); expected.MinFresh = new TimeSpan(0, 0, 123); expected.NoTransform = true; expected.OnlyIfCached = true; expected.Extensions.Add(new NameValueHeaderValue("custom")); CheckGetCacheControlLength("min-fresh=123, no-transform, only-if-cached, custom", 0, null, 51, expected); expected = new CacheControlHeaderValue(); expected.Public = true; expected.Private = true; expected.PrivateHeaders.Add("token1"); expected.MustRevalidate = true; expected.ProxyRevalidate = true; expected.Extensions.Add(new NameValueHeaderValue("c", "d")); expected.Extensions.Add(new NameValueHeaderValue("a", "b")); CheckGetCacheControlLength(",public, , private=\"token1\", must-revalidate, c=d, proxy-revalidate, a=b", 0, null, 72, expected); expected = new CacheControlHeaderValue(); expected.Private = true; expected.SharedMaxAge = new TimeSpan(0, 0, 1234567890); expected.MaxAge = new TimeSpan(0, 0, 987654321); CheckGetCacheControlLength("s-maxage=1234567890, private, max-age = 987654321,", 0, null, 50, expected); } [Fact] public void GetCacheControlLength_DifferentValidScenariosAndExistingCacheControl_AllReturnNonZero() { CacheControlHeaderValue storeValue = new CacheControlHeaderValue(); storeValue.NoStore = true; CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoCache = true; expected.NoStore = true; CheckGetCacheControlLength("X no-cache", 1, storeValue, 9, expected); storeValue = new CacheControlHeaderValue(); storeValue.Private = true; storeValue.PrivateHeaders.Add("token1"); storeValue.NoCache = true; expected.NoCacheHeaders.Add("token1"); expected.NoCacheHeaders.Clear(); // just make sure we have an assigned (empty) collection. expected = new CacheControlHeaderValue(); expected.Private = true; expected.PrivateHeaders.Add("token1"); expected.PrivateHeaders.Add("token2"); expected.NoCache = true; expected.NoCacheHeaders.Add("token1"); expected.NoCacheHeaders.Add("token2"); CheckGetCacheControlLength("private=\"token2\", no-cache=\"token1, , token2,\"", 0, storeValue, 46, expected); storeValue = new CacheControlHeaderValue(); storeValue.Extensions.Add(new NameValueHeaderValue("x", "y")); storeValue.NoTransform = true; storeValue.OnlyIfCached = true; expected = new CacheControlHeaderValue(); expected.Public = true; expected.Private = true; expected.PrivateHeaders.Add("token1"); expected.MustRevalidate = true; expected.ProxyRevalidate = true; expected.NoTransform = true; expected.OnlyIfCached = true; expected.Extensions.Add(new NameValueHeaderValue("a", "\"b\"")); expected.Extensions.Add(new NameValueHeaderValue("c", "d")); expected.Extensions.Add(new NameValueHeaderValue("x", "y")); // from store result CheckGetCacheControlLength(",public, , private=\"token1\", must-revalidate, c=d, proxy-revalidate, a=\"b\"", 0, storeValue, 74, expected); storeValue = new CacheControlHeaderValue(); storeValue.MaxStale = true; storeValue.MinFresh = new TimeSpan(1, 2, 3); expected = new CacheControlHeaderValue(); expected.MaxStale = true; expected.MaxStaleLimit = new TimeSpan(0, 0, 5); expected.MinFresh = new TimeSpan(0, 0, 10); // note that the last header value overwrites existing ones CheckGetCacheControlLength(" ,,max-stale=5,,min-fresh = 10,,", 0, storeValue, 33, expected); storeValue = new CacheControlHeaderValue(); storeValue.SharedMaxAge = new TimeSpan(1, 2, 3); storeValue.NoTransform = true; expected = new CacheControlHeaderValue(); expected.SharedMaxAge = new TimeSpan(1, 2, 3); expected.NoTransform = true; } [Fact] public void GetCacheControlLength_DifferentInvalidScenarios_AllReturnZero() { // Token-only values CheckInvalidCacheControlLength("no-store=15", 0); CheckInvalidCacheControlLength("no-store=", 0); CheckInvalidCacheControlLength("no-transform=a", 0); CheckInvalidCacheControlLength("no-transform=", 0); CheckInvalidCacheControlLength("only-if-cached=\"x\"", 0); CheckInvalidCacheControlLength("only-if-cached=", 0); CheckInvalidCacheControlLength("public=\"x\"", 0); CheckInvalidCacheControlLength("public=", 0); CheckInvalidCacheControlLength("must-revalidate=\"1\"", 0); CheckInvalidCacheControlLength("must-revalidate=", 0); CheckInvalidCacheControlLength("proxy-revalidate=x", 0); CheckInvalidCacheControlLength("proxy-revalidate=", 0); // Token with optional field-name list CheckInvalidCacheControlLength("no-cache=", 0); CheckInvalidCacheControlLength("no-cache=token", 0); CheckInvalidCacheControlLength("no-cache=\"token", 0); CheckInvalidCacheControlLength("no-cache=\"\"", 0); // at least one token expected as value CheckInvalidCacheControlLength("private=", 0); CheckInvalidCacheControlLength("private=token", 0); CheckInvalidCacheControlLength("private=\"token", 0); CheckInvalidCacheControlLength("private=\",\"", 0); // at least one token expected as value CheckInvalidCacheControlLength("private=\"=\"", 0); // Token with delta-seconds value CheckInvalidCacheControlLength("max-age", 0); CheckInvalidCacheControlLength("max-age=", 0); CheckInvalidCacheControlLength("max-age=a", 0); CheckInvalidCacheControlLength("max-age=\"1\"", 0); CheckInvalidCacheControlLength("max-age=1.5", 0); CheckInvalidCacheControlLength("max-stale=", 0); CheckInvalidCacheControlLength("max-stale=a", 0); CheckInvalidCacheControlLength("max-stale=\"1\"", 0); CheckInvalidCacheControlLength("max-stale=1.5", 0); CheckInvalidCacheControlLength("min-fresh", 0); CheckInvalidCacheControlLength("min-fresh=", 0); CheckInvalidCacheControlLength("min-fresh=a", 0); CheckInvalidCacheControlLength("min-fresh=\"1\"", 0); CheckInvalidCacheControlLength("min-fresh=1.5", 0); CheckInvalidCacheControlLength("s-maxage", 0); CheckInvalidCacheControlLength("s-maxage=", 0); CheckInvalidCacheControlLength("s-maxage=a", 0); CheckInvalidCacheControlLength("s-maxage=\"1\"", 0); CheckInvalidCacheControlLength("s-maxage=1.5", 0); // Invalid Extension values CheckInvalidCacheControlLength("custom=", 0); CheckInvalidCacheControlLength("custom value", 0); CheckInvalidCacheControlLength(null, 0); CheckInvalidCacheControlLength("", 0); CheckInvalidCacheControlLength("", 1); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { // Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue. CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoStore = true; expected.MinFresh = new TimeSpan(0, 2, 3); CheckValidParse(" , no-store, min-fresh=123", expected); expected = new CacheControlHeaderValue(); expected.MaxStale = true; expected.NoCache = true; expected.NoCacheHeaders.Add("t"); CheckValidParse("max-stale, no-cache=\"t\", ,,", expected); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("no-cache,=", 0); CheckInvalidParse("max-age=123x", 0); CheckInvalidParse("=no-cache", 0); CheckInvalidParse("no-cache no-store", 0); CheckInvalidParse("invalid =", 0); CheckInvalidParse("\u4F1A", 0); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { // Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue. CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoStore = true; expected.MinFresh = new TimeSpan(0, 2, 3); CheckValidTryParse(" , no-store, min-fresh=123", expected); expected = new CacheControlHeaderValue(); expected.MaxStale = true; expected.NoCache = true; expected.NoCacheHeaders.Add("t"); CheckValidTryParse("max-stale, no-cache=\"t\", ,,", expected); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("no-cache,=", 0); CheckInvalidTryParse("max-age=123x", 0); CheckInvalidTryParse("=no-cache", 0); CheckInvalidTryParse("no-cache no-store", 0); CheckInvalidTryParse("invalid =", 0); CheckInvalidTryParse("\u4F1A", 0); } #region Helper methods private void CompareHashCodes(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual) { if (areEqual) { Assert.Equal(x.GetHashCode(), y.GetHashCode()); } else { Assert.NotEqual(x.GetHashCode(), y.GetHashCode()); } } private void CompareValues(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual) { Assert.Equal(areEqual, x.Equals(y)); Assert.Equal(areEqual, y.Equals(x)); } private static void CheckGetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue, int expectedLength, CacheControlHeaderValue expectedResult) { CacheControlHeaderValue result = null; Assert.Equal(expectedLength, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, storeValue, out result)); if (storeValue == null) { Assert.Equal(expectedResult, result); } else { // If we provide a 'storeValue', then that instance will be updated and result will be 'null' Assert.Null(result); Assert.Equal(expectedResult, storeValue); } } private static void CheckInvalidCacheControlLength(string input, int startIndex) { CacheControlHeaderValue result = null; Assert.Equal(0, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, null, out result)); Assert.Null(result); } private void CheckValidParse(string input, CacheControlHeaderValue expectedResult) { CacheControlHeaderValue result = CacheControlHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input, int startIndex) { Assert.Throws<FormatException>(() => { CacheControlHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, CacheControlHeaderValue expectedResult) { CacheControlHeaderValue result = null; Assert.True(CacheControlHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input, int startIndex) { CacheControlHeaderValue result = null; Assert.False(CacheControlHeaderValue.TryParse(input, out result)); Assert.Null(result); } #endregion } }
using System; using System.Drawing; //using System.ComponentModel; using MonoTouch.ObjCRuntime; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace AFNetworking { public delegate void AFHttpRequestSuccessCallback(AFHTTPRequestOperation operation, NSObject responseObject); public delegate void AFHttpRequestFailureCallback(AFHTTPRequestOperation operation, NSError error); public delegate void AFImageRequestCallback(UIImage image); public delegate UIImage AFImageRequestImageProcessingCallback(UIImage image); public delegate void AFImageRequestDetailedCallback(NSUrlRequest request, NSHttpUrlResponse response, UIImage image); public delegate void AFImageRequestFailedCallback(NSUrlRequest request, NSHttpUrlResponse response, NSError error); public delegate void AFURLConnectionOperationProgressCallback (int bytes, long totalBytes, long totalBytesExpected); [BaseType (typeof (NSObject))] public partial interface AFHTTPClient { [Export ("baseURL")] NSUrl BaseURL { get; } [Export ("stringEncoding")] NSStringEncoding StringEncoding { get; set; } [Export ("parameterEncoding")] AFHTTPClientParameterEncoding ParameterEncoding { get; set; } [Export ("operationQueue")] NSOperationQueue OperationQueue { get; } [Static, Export ("clientWithBaseURL:")] AFHTTPClient ClientWithBaseURL (NSUrl url); [Export ("initWithBaseURL:")] NSObject Constructor (NSUrl url); [Export ("registerHTTPOperationClass:")] bool RegisterHTTPOperationClass (Class operationClass); [Export ("unregisterHTTPOperationClass:")] void UnregisterHTTPOperationClass (Class operationClass); [Export ("defaultValueForHeader:")] string DefaultValueForHeader (string header); [Export ("setDefaultHeader:value:")] void SetDefaultHeader (string header, string value); [Export ("setAuthorizationHeaderWithUsername:password:")] void SetAuthorizationHeaderWithUsername (string username, string password); [Export ("setAuthorizationHeaderWithToken:")] void SetAuthorizationHeaderWithToken (string token); [Export ("clearAuthorizationHeader")] void ClearAuthorizationHeader (); [Export ("setDefaultCredential:")] void SetDefaultCredential (NSUrlCredential credential); [Export ("requestWithMethod:path:parameters:")] NSMutableUrlRequest RequestWithMethod (string method, string path, [NullAllowed] NSDictionary parameters); /*[Export ("multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:")] NSMutableURLRequest MultipartFormRequestWithMethod (string method, string path, NSDictionary parameters, [unmapped: blockpointer: BlockPointer] block); [Export ("HTTPRequestOperationWithRequest:success:failure:")] AFHTTPRequestOperation HTTPRequestOperationWithRequest (NSURLRequest urlRequest, [unmapped: blockpointer: BlockPointer] success, [unmapped: blockpointer: BlockPointer] failure);*/ [Export ("enqueueHTTPRequestOperation:")] void EnqueueHTTPRequestOperation (AFHTTPRequestOperation operation); [Export ("cancelAllHTTPOperationsWithMethod:path:")] void CancelAllHTTPOperationsWithMethod (string method, string path); /*[Export ("enqueueBatchOfHTTPRequestOperationsWithRequests:progressBlock:completionBlock:")] void EnqueueBatchOfHTTPRequestOperationsWithRequests (NSArray urlRequests, [unmapped: blockpointer: BlockPointer] progressBlock, [unmapped: blockpointer: BlockPointer] completionBlock); [Export ("enqueueBatchOfHTTPRequestOperations:progressBlock:completionBlock:")] void EnqueueBatchOfHTTPRequestOperations (NSArray operations, [unmapped: blockpointer: BlockPointer] progressBlock, [unmapped: blockpointer: BlockPointer] completionBlock);*/ [Export ("getPath:parameters:success:failure:")] void GetPath (string path, [NullAllowed] NSDictionary parameters, Action<AFHTTPRequestOperation, NSObject> success, [NullAllowed] Action<AFHTTPRequestOperation, NSError> failure); [Export ("postPath:parameters:success:failure:")] void PostPath (string path, NSDictionary parameters, Action<AFHTTPRequestOperation, NSObject> success, [NullAllowed] Action<AFHTTPRequestOperation, NSError> failure); [Export ("putPath:parameters:success:failure:")] void PutPath (string path, NSDictionary parameters, Action<AFHTTPRequestOperation, NSObject> success, [NullAllowed] Action<AFHTTPRequestOperation, NSError> failure); [Export ("deletePath:parameters:success:failure:")] void DeletePath (string path, NSDictionary parameters, Action<AFHTTPRequestOperation, NSObject> success, [NullAllowed] Action<AFHTTPRequestOperation, NSError> failure); [Export ("patchPath:parameters:success:failure:")] void PatchPath (string path, NSDictionary parameters, Action<AFHTTPRequestOperation, NSObject> success, [NullAllowed] Action<AFHTTPRequestOperation, NSError> failure); /*[Field ("kAFUploadStream3GSuggestedPacketSize", "__Internal")] uint kAFUploadStream3GSuggestedPacketSize { get; }*/ [Field ("kAFUploadStream3GSuggestedDelay", "__Internal")] double kAFUploadStream3GSuggestedDelay { get; } } [Model] public partial interface AFMultipartFormData { [Export ("appendPartWithFileURL:name:error:")] bool AppendPartWithFileURL (NSUrl fileURL, string name, out NSError error); [Export ("appendPartWithFileURL:name:fileName:mimeType:error:")] bool AppendPartWithFileURL (NSUrl fileURL, string name, string fileName, string mimeType, out NSError error); [Export ("appendPartWithFileData:name:fileName:mimeType:")] void AppendPartWithFileData (NSData data, string name, string fileName, string mimeType); [Export ("appendPartWithFormData:name:")] void AppendPartWithFormData (NSData data, string name); [Export ("appendPartWithHeaders:body:")] void AppendPartWithHeaders (NSDictionary headers, NSData body); [Export ("throttleBandwidthWithPacketSize:delay:")] void ThrottleBandwidthWithPacketSize (uint numberOfBytes, double delay); } [BaseType (typeof (AFURLConnectionOperation))] public partial interface AFHTTPRequestOperation { [Export("initWithRequest:")] IntPtr Constructor(NSUrlRequest request); /*[Export ("response")] NSUrlResponse Response { get; }*/ [Export ("hasAcceptableStatusCode")] bool HasAcceptableStatusCode { get; } [Export ("hasAcceptableContentType")] bool HasAcceptableContentType { get; } [Export ("successCallbackQueue")] MonoTouch.CoreFoundation.DispatchQueue SuccessCallbackQueue { get; set; } [Export ("failureCallbackQueue")] MonoTouch.CoreFoundation.DispatchQueue FailureCallbackQueue { get; set; } [Static, Export ("acceptableStatusCodes")] NSIndexSet AcceptableStatusCodes (); [Static, Export ("addAcceptableStatusCodes:")] void AddAcceptableStatusCodes (NSIndexSet statusCodes); [Static, Export ("acceptableContentTypes")] NSSet AcceptableContentTypes (); [Static, Export ("addAcceptableContentTypes:")] void AddAcceptableContentTypes (NSSet contentTypes); [Static, Export ("canProcessRequest:")] bool CanProcessRequest (NSUrlRequest urlRequest); [Export ("setCompletionBlockWithSuccess:failure:")] void SetCompletionBlockWithSuccess(AFHttpRequestSuccessCallback success, AFHttpRequestFailureCallback failure); } [BaseType (typeof (AFHTTPRequestOperation))] public partial interface AFImageRequestOperation { [Export ("responseImage")] UIImage ResponseImage { get; } [Static, Export ("imageRequestOperationWithRequest:success:")] AFImageRequestOperation ImageRequestOperationWithRequest (NSUrlRequest urlRequest, AFImageRequestCallback success); [Static, Export ("imageRequestOperationWithRequest:imageProcessingBlock:success:failure:")] AFImageRequestOperation ImageRequestOperationWithRequest(NSUrlRequest urlRequest, AFImageRequestImageProcessingCallback imageProcessingBlock, AFImageRequestDetailedCallback success, AFImageRequestFailedCallback failed); } [BaseType (typeof (AFHTTPRequestOperation))] public partial interface AFJSONRequestOperation { [Export ("responseJSON")] NSObject ResponseJSON { get; } /*[Export ("JSONReadingOptions")] NSJSONReadingOptions JSONReadingOptions { get; set; }*/ /*[Static, Export ("JSONRequestOperationWithRequest:success:failure:")] instancetype JSONRequestOperationWithRequest (NSURLRequest urlRequest, [unmapped: blockpointer: BlockPointer] success, [unmapped: blockpointer: BlockPointer] failure);*/ } [BaseType (typeof (AFHTTPRequestOperation))] public partial interface AFPropertyListRequestOperation { [Export ("responsePropertyList")] NSObject ResponsePropertyList { get; } [Export ("propertyListReadOptions")] NSPropertyListReadOptions PropertyListReadOptions { get; set; } /*[Static, Export ("propertyListRequestOperationWithRequest:success:failure:")] instancetype PropertyListRequestOperationWithRequest (NSURLRequest urlRequest, [unmapped: blockpointer: BlockPointer] success, [unmapped: blockpointer: BlockPointer] failure);*/ } [BaseType (typeof (NSOperation))] public partial interface AFURLConnectionOperation { [Export ("runLoopModes")] NSSet RunLoopModes { get; set; } [Export ("request")] NSUrlRequest Request { get; } [Export ("response")] NSUrlResponse Response { get; } [Export ("error")] NSError Error { get; } [Export ("responseData")] NSData ResponseData { get; } [Export ("responseString")] string ResponseString { get; } [Export ("responseStringEncoding")] NSStringEncoding ResponseStringEncoding { get; } [Export ("shouldUseCredentialStorage")] bool ShouldUseCredentialStorage { get; set; } [Export ("credential")] NSUrlCredential Credential { get; set; } [Export ("inputStream")] NSInputStream InputStream { get; set; } [Export ("outputStream")] NSOutputStream OutputStream { get; set; } [Export ("userInfo")] NSDictionary UserInfo { get; set; } [Export ("initWithRequest:")] IntPtr Constructor (NSUrlRequest urlRequest); [Export ("pause")] void Pause (); [Export ("isPaused")] bool IsPaused (); [Export ("resume")] void Resume (); [Export ("setCompletionBlock:")] void SetCompletionBlock(Action block); [Export ("setUploadProgressBlock:")] void SetUploadProgressBlock (AFURLConnectionOperationProgressCallback block); [Export ("setDownloadProgressBlock:")] void SetDownloadProgressBlock (AFURLConnectionOperationProgressCallback block); /*[Export ("setAuthenticationAgainstProtectionSpaceBlock:")] void SetAuthenticationAgainstProtectionSpaceBlock ([unmapped: blockpointer: BlockPointer] block); [Export ("setAuthenticationChallengeBlock:")] void SetAuthenticationChallengeBlock ([unmapped: blockpointer: BlockPointer] block); [Export ("setRedirectResponseBlock:")] void SetRedirectResponseBlock ([unmapped: blockpointer: BlockPointer] block); [Export ("setCacheResponseBlock:")] void SetCacheResponseBlock ([unmapped: blockpointer: BlockPointer] block);*/ [Field ("AFNetworkingErrorDomain", "__Internal")] NSString AFNetworkingErrorDomain { get; } [Field ("AFNetworkingOperationFailingURLRequestErrorKey", "__Internal")] NSString AFNetworkingOperationFailingURLRequestErrorKey { get; } [Field ("AFNetworkingOperationFailingURLResponseErrorKey", "__Internal")] NSString AFNetworkingOperationFailingURLResponseErrorKey { get; } [Notification, Field ("AFNetworkingOperationDidStartNotification", "__Internal")] NSString AFNetworkingOperationDidStartNotification { get; } [Notification, Field ("AFNetworkingOperationDidFinishNotification", "__Internal")] NSString AFNetworkingOperationDidFinishNotification { get; } } [BaseType (typeof (AFHTTPRequestOperation))] public partial interface AFXMLRequestOperation { /*[Export ("responseXMLParser")] NSXMLParser ResponseXMLParser { get; } [Export ("responseXMLDocument")] NSXMLDocument ResponseXMLDocument { get; }*/ /*[Static, Export ("XMLParserRequestOperationWithRequest:success:failure:")] instancetype XMLParserRequestOperationWithRequest (NSURLRequest urlRequest, [unmapped: blockpointer: BlockPointer] success, [unmapped: blockpointer: BlockPointer] failure); [Static, Export ("XMLDocumentRequestOperationWithRequest:success:failure:")] instancetype XMLDocumentRequestOperationWithRequest (NSURLRequest urlRequest, [unmapped: blockpointer: BlockPointer] success, [unmapped: blockpointer: BlockPointer] failure);*/ } [BaseType (typeof (UIImageView))] [Category] interface AFNetworkingImageExtras { [Export ("setImageWithURL:")] void SetImageUrl (NSUrl url); [Export ("setImageWithURL:placeholderImage:")] void SetImageUrl(NSUrl url, UIImage placeholderImage); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { private static readonly UTF8Encoding s_utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { // Nop. } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { // Nop. } [CLSCompliant(false)] public static Process Start(string fileName, string userName, SecureString password, string domain) { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); } [CLSCompliant(false)] public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain) { throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported); } /// <summary>Stops the associated process immediately.</summary> public void Kill() { EnsureState(State.HaveId); if (Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL) != 0) { throw new Win32Exception(); // same exception as on Windows } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { // Nop. No additional state to reset. } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { if (_waitStateHolder != null) { _waitStateHolder.Dispose(); _waitStateHolder = null; } } /// <summary>Additional configuration when a process ID is set.</summary> partial void ConfigureAfterProcessIdSet() { // Make sure that we configure the wait state holder for this process object, which we can only do once we have a process ID. Debug.Assert(_haveProcessId, $"{nameof(ConfigureAfterProcessIdSet)} should only be called once a process ID is set"); GetWaitState(); // lazily initializes the wait state } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { bool exited = GetWaitState().WaitForExit(milliseconds); Debug.Assert(exited || milliseconds != Timeout.Infinite); if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams { if (_output != null) { _output.WaitUtilEOF(); } if (_error != null) { _error.WaitUtilEOF(); } } return exited; } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { ProcessModuleCollection pmc = Modules; return pmc.Count > 0 ? pmc[0] : null; } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { int? exitCode; _exited = GetWaitState().GetExited(out exitCode); if (_exited && exitCode != null) { _exitCode = exitCode.Value; } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetWaitState().ExitTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { return false; } //Nop set { } // Nop } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { // This mapping is relatively arbitrary. 0 is normal based on the man page, // and the other values above and below are simply distributed evenly. get { EnsureState(State.HaveId); int pri = 0; int errno = Interop.Sys.GetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, out pri); if (errno != 0) // Interop.Sys.GetPriority returns GetLastWin32Error() { throw new Win32Exception(errno); // match Windows exception } Debug.Assert(pri >= -20 && pri <= 20); return pri < -15 ? ProcessPriorityClass.RealTime : pri < -10 ? ProcessPriorityClass.High : pri < -5 ? ProcessPriorityClass.AboveNormal : pri == 0 ? ProcessPriorityClass.Normal : pri <= 10 ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Idle; } set { int pri = 0; // Normal switch (value) { case ProcessPriorityClass.RealTime: pri = -19; break; case ProcessPriorityClass.High: pri = -11; break; case ProcessPriorityClass.AboveNormal: pri = -6; break; case ProcessPriorityClass.BelowNormal: pri = 10; break; case ProcessPriorityClass.Idle: pri = 19; break; default: Debug.Assert(value == ProcessPriorityClass.Normal, "Input should have been validated by caller"); break; } int result = Interop.Sys.SetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, pri); if (result == -1) { throw new Win32Exception(); // match Windows exception } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return Interop.Sys.GetPid(); } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { if (_haveProcessHandle) { if (GetWaitState().HasExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } return _processHandle; } EnsureState(State.HaveId | State.IsLocal); return new SafeProcessHandle(_processId); } /// <summary> /// Starts the process using the supplied start info. /// With UseShellExecute option, we'll try the shell tools to launch it(e.g. "open fileName") /// </summary> /// <param name="startInfo">The start info with which to start the process.</param> private bool StartCore(ProcessStartInfo startInfo) { string filename; string[] argv; if (startInfo.UseShellExecute) { if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.CantRedirectStreams); } } int childPid, stdinFd, stdoutFd, stderrFd; string[] envp = CreateEnvp(startInfo); string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null; if (startInfo.UseShellExecute) { // use default program to open file/url filename = GetPathToOpenFile(); argv = ParseArgv(startInfo, filename); } else { filename = ResolvePath(startInfo.FileName); argv = ParseArgv(startInfo); if (Directory.Exists(filename)) { throw new Win32Exception(SR.DirectoryNotValidAsInput); } } if (string.IsNullOrEmpty(filename)) { throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno); } // Invoke the shim fork/execve routine. It will create pipes for all requested // redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr // descriptors, and execve to execute the requested process. The shim implementation // is used to fork/execve as executing managed code in a forked process is not safe (only // the calling thread will transfer, thread IDs aren't stable across the fork, etc.) Interop.Sys.ForkAndExecProcess( filename, argv, envp, cwd, startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError, out childPid, out stdinFd, out stdoutFd, out stderrFd); // Store the child's information into this Process object. Debug.Assert(childPid >= 0); SetProcessId(childPid); SetProcessHandle(new SafeProcessHandle(childPid)); // Configure the parent's ends of the redirection streams. // We use UTF8 encoding without BOM by-default(instead of Console encoding as on Windows) // as there is no good way to get this information from the native layer // and we do not want to take dependency on Console contract. if (startInfo.RedirectStandardInput) { Debug.Assert(stdinFd >= 0); _standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write), s_utf8NoBom, StreamBufferSize) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0); _standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), startInfo.StandardOutputEncoding ?? s_utf8NoBom, true, StreamBufferSize); } if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0); _standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read), startInfo.StandardErrorEncoding ?? s_utf8NoBom, true, StreamBufferSize); } return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Finalizable holder for the underlying shared wait state object.</summary> private ProcessWaitState.Holder _waitStateHolder; /// <summary>Size to use for redirect streams and stream readers/writers.</summary> private const int StreamBufferSize = 4096; /// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <param name="alternativePath">alternative resolved path to use as first argument</param> /// <returns>The argv array.</returns> private static string[] ParseArgv(ProcessStartInfo psi, string alternativePath = null) { string argv0 = psi.FileName; // when no alternative path exists, pass filename (instead of resolved path) as argv[0], to match what caller supplied if (string.IsNullOrEmpty(psi.Arguments) && string.IsNullOrEmpty(alternativePath)) { return new string[] { argv0 }; } var argvList = new List<string>(); if (!string.IsNullOrEmpty(alternativePath)) { argvList.Add(alternativePath); if (alternativePath.Contains("kfmclient")) { argvList.Add("openURL"); // kfmclient needs OpenURL } } argvList.Add(argv0); ParseArgumentsIntoList(psi.Arguments, argvList); return argvList.ToArray(); } /// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <returns>The envp array.</returns> private static string[] CreateEnvp(ProcessStartInfo psi) { var envp = new string[psi.Environment.Count]; int index = 0; foreach (var pair in psi.Environment) { envp[index++] = pair.Key + "=" + pair.Value; } return envp; } /// <summary>Resolves a path to the filename passed to ProcessStartInfo. </summary> /// <param name="filename">The filename.</param> /// <returns>The resolved path. It can return null in case of URLs.</returns> private static string ResolvePath(string filename) { // Follow the same resolution that Windows uses with CreateProcess: // 1. First try the exact path provided // 2. Then try the file relative to the executable directory // 3. Then try the file relative to the current directory // 4. then try the file in each of the directories specified in PATH // Windows does additional Windows-specific steps between 3 and 4, // and we ignore those here. // If the filename is a complete path, use it, regardless of whether it exists. if (Path.IsPathRooted(filename)) { // In this case, it doesn't matter whether the file exists or not; // it's what the caller asked for, so it's what they'll get return filename; } // Then check the executable's directory string path = GetExePath(); if (path != null) { try { path = Path.Combine(Path.GetDirectoryName(path), filename); if (File.Exists(path)) { return path; } } catch (ArgumentException) { } // ignore any errors in data that may come from the exe path } // Then check the current directory path = Path.Combine(Directory.GetCurrentDirectory(), filename); if (File.Exists(path)) { return path; } // Then check each directory listed in the PATH environment variables return FindProgramInPath(filename); } /// <summary> /// Gets the path to the program /// </summary> /// <param name="program"></param> /// <returns></returns> private static string FindProgramInPath(string program) { string path; string pathEnvVar = Environment.GetEnvironmentVariable("PATH"); if (pathEnvVar != null) { var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true); while (pathParser.MoveNext()) { string subPath = pathParser.ExtractCurrent(); path = Path.Combine(subPath, program); if (File.Exists(path)) { return path; } } } return null; } /// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary> /// <param name="ticks">The number of ticks.</param> /// <returns>The equivalent TimeSpan.</returns> internal static TimeSpan TicksToTimeSpan(double ticks) { // Look up the number of ticks per second in the system's configuration, // then use that to convert to a TimeSpan long ticksPerSecond = Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_CLK_TCK); if (ticksPerSecond <= 0) { throw new Win32Exception(); } return TimeSpan.FromSeconds(ticks / (double)ticksPerSecond); } /// <summary>Computes a time based on a number of ticks since boot.</summary> /// <param name="timespanAfterBoot">The timespan since boot.</param> /// <returns>The converted time.</returns> internal static DateTime BootTimeToDateTime(TimeSpan timespanAfterBoot) { // Use the uptime and the current time to determine the absolute boot time. This implementation is relying on the // implementation detail that Stopwatch.GetTimestamp() uses a value based on time since boot. DateTime bootTime = DateTime.UtcNow - TimeSpan.FromSeconds(Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency); // And use that to determine the absolute time for timespan. DateTime dt = bootTime + timespanAfterBoot; // The return value is expected to be in the local time zone. // It is converted here (rather than starting with DateTime.Now) to avoid DST issues. return dt.ToLocalTime(); } /// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="access">The access mode.</param> /// <returns>The opened stream.</returns> private static FileStream OpenStream(int fd, FileAccess access) { Debug.Assert(fd >= 0); return new FileStream( new SafeFileHandle((IntPtr)fd, ownsHandle: true), access, StreamBufferSize, isAsync: false); } /// <summary>Parses a command-line argument string into a list of arguments.</summary> /// <param name="arguments">The argument string.</param> /// <param name="results">The list into which the component arguments should be stored.</param> /// <remarks> /// This follows the rules outlined in "Parsing C++ Command-Line Arguments" at /// https://msdn.microsoft.com/en-us/library/17w5ykft.aspx. /// </remarks> private static void ParseArgumentsIntoList(string arguments, List<string> results) { // Iterate through all of the characters in the argument string. for (int i = 0; i < arguments.Length; i++) { while (i < arguments.Length && (arguments[i] == ' ' || arguments[i] == '\t')) i++; if (i == arguments.Length) break; results.Add(GetNextArgument(arguments, ref i)); } } private static string GetNextArgument(string arguments, ref int i) { var currentArgument = StringBuilderCache.Acquire(); bool inQuotes = false; while (i < arguments.Length) { // From the current position, iterate through contiguous backslashes. int backslashCount = 0; while (i < arguments.Length && arguments[i] == '\\') { i++; backslashCount++; } if (backslashCount > 0) { if (i >= arguments.Length || arguments[i] != '"') { // Backslashes not followed by a double quote: // they should all be treated as literal backslashes. currentArgument.Append('\\', backslashCount); } else { // Backslashes followed by a double quote: // - Output a literal slash for each complete pair of slashes // - If one remains, use it to make the subsequent quote a literal. currentArgument.Append('\\', backslashCount / 2); if (backslashCount % 2 != 0) { currentArgument.Append('"'); i++; } } continue; } char c = arguments[i]; // If this is a double quote, track whether we're inside of quotes or not. // Anything within quotes will be treated as a single argument, even if // it contains spaces. if (c == '"') { if (inQuotes && i < arguments.Length - 1 && arguments[i + 1] == '"') { currentArgument.Append('"'); i++; } else { inQuotes = !inQuotes; } i++; continue; } // If this is a space/tab and we're not in quotes, we're done with the current // argument, it should be added to the results and then reset for the next one. if ((c == ' ' || c == '\t') && !inQuotes) { break; } // Nothing special; add the character to the current argument. currentArgument.Append(c); i++; } return StringBuilderCache.GetStringAndRelease(currentArgument); } /// <summary>Gets the wait state for this Process object.</summary> private ProcessWaitState GetWaitState() { if (_waitStateHolder == null) { EnsureState(State.HaveId); _waitStateHolder = new ProcessWaitState.Holder(_processId); } return _waitStateHolder._state; } public IntPtr MainWindowHandle => IntPtr.Zero; private bool CloseMainWindowCore() => false; public string MainWindowTitle => string.Empty; public bool Responding => true; private bool WaitForInputIdleCore(int milliseconds) => throw new InvalidOperationException(SR.InputIdleUnkownError); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Dawn; using Lime.Protocol.Network; using Lime.Protocol.Security; namespace Lime.Protocol.Client { /// <summary> /// Helper class for building instances of <see cref="ClientChannel"/> and handling the establishment of the session for the channel. /// </summary> public sealed class EstablishedClientChannelBuilder : IEstablishedClientChannelBuilder { private readonly List<Func<IClientChannel, CancellationToken, Task>> _establishedHandlers; /// <summary> /// Initializes a new instance of the <see cref="EstablishedClientChannelBuilder"/> class. /// </summary> /// <param name="clientChannelBuilder">The client channel builder.</param> /// <exception cref="System.ArgumentNullException"> /// </exception> public EstablishedClientChannelBuilder(IClientChannelBuilder clientChannelBuilder) { ChannelBuilder = clientChannelBuilder ?? throw new ArgumentNullException(nameof(clientChannelBuilder)); _establishedHandlers = new List<Func<IClientChannel, CancellationToken, Task>>(); CompressionSelector = options => options.First(); EncryptionSelector = options => options.First(); Authenticator = (options, roundtrip) => new GuestAuthentication(); EstablishmentTimeout = TimeSpan.FromSeconds(30); Identity = new Identity(EnvelopeId.NewId(), clientChannelBuilder.ServerUri.Host); Instance = Environment.MachineName; } /// <summary> /// Gets the associated channel builder. /// </summary> public IClientChannelBuilder ChannelBuilder { get; } /// <summary> /// Gets the identity. /// </summary> public Identity Identity { get; private set; } /// <summary> /// Gets the instance. /// </summary> public string Instance { get; private set; } /// <summary> /// Gets the establishment timeout /// </summary> public TimeSpan EstablishmentTimeout { get; private set; } /// <summary> /// Gets the compression selector. /// </summary> public Func<SessionCompression[], SessionCompression> CompressionSelector { get; private set; } /// <summary> /// Gets the encryption selector. /// </summary> public Func<SessionEncryption[], SessionEncryption> EncryptionSelector { get; private set; } /// <summary> /// Gets the authenticator. /// </summary> public Func<AuthenticationScheme[], Authentication, Authentication> Authenticator { get; private set; } /// <summary> /// Gets the established handlers. /// </summary> public IEnumerable<Func<IClientChannel, CancellationToken, Task>> EstablishedHandlers => _establishedHandlers.AsReadOnly(); /// <summary> /// Sets the timeout to Build and establish a new session /// </summary> /// <param name="timeout">The timeout</param> /// <returns></returns> public IEstablishedClientChannelBuilder WithEstablishmentTimeout(TimeSpan timeout) { EstablishmentTimeout = timeout; return this; } /// <summary> /// Sets the compression option to be used in the session establishment. /// </summary> /// <param name="compression">The compression.</param> /// <returns></returns> public IEstablishedClientChannelBuilder WithCompression(SessionCompression compression) { return WithCompression(options => compression); } /// <summary> /// Sets the compression selector to be used in the session establishment. /// </summary> /// <param name="compressionSelector">The compression selector.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithCompression(Func<SessionCompression[], SessionCompression> compressionSelector) { Guard.Argument(compressionSelector, nameof(compressionSelector)).NotNull(); CompressionSelector = compressionSelector; return this; } /// <summary> /// Sets the encryption option to be used in the session establishment. /// </summary> /// <param name="encryption">The encryption.</param> /// <returns></returns> public IEstablishedClientChannelBuilder WithEncryption(SessionEncryption encryption) { return WithEncryption(options => encryption); } /// <summary> /// Sets the encryption selector to be used in the session establishment. /// </summary> /// <param name="encryptionSelector">The encryption selector.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithEncryption(Func<SessionEncryption[], SessionEncryption> encryptionSelector) { Guard.Argument(encryptionSelector, nameof(encryptionSelector)).NotNull(); EncryptionSelector = encryptionSelector; return this; } /// <summary> /// Sets the authentication password to be used in the session establishment. /// </summary> /// <param name="password">The authentication password, in plain text.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithPlainAuthentication(string password) { Guard.Argument(password, nameof(password)).NotNull(); var authentication = new PlainAuthentication(); authentication.SetToBase64Password(password); return WithAuthentication(authentication); } /// <summary> /// Sets the authentication key to be used in the session establishment. /// </summary> /// <param name="key">The authentication key.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithKeyAuthentication(string key) { Guard.Argument(key, nameof(key)).NotNull(); var authentication = new KeyAuthentication(); authentication.SetToBase64Key(key); return WithAuthentication(authentication); } public IEstablishedClientChannelBuilder WithTransportAuthentication(DomainRole domainRole) { var authentication = new TransportAuthentication(); authentication.DomainRole = domainRole; return WithAuthentication(authentication); } public IEstablishedClientChannelBuilder WithExternalAuthentication(string token, string issuer) { Guard.Argument(token, nameof(token)).NotNull(); var authentication = new ExternalAuthentication { Token = token, Issuer = issuer }; return WithAuthentication(authentication); } /// <summary> /// Sets the authentication to be used in the session establishment. /// </summary> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithAuthentication<TAuthentication>() where TAuthentication : Authentication, new() { return WithAuthentication((schemes, roundtrip) => new TAuthentication()); } /// <summary> /// Sets the authentication to be used in the session establishment. /// </summary> /// <param name="authentication">The authentication.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithAuthentication(Authentication authentication) { Guard.Argument(authentication, nameof(authentication)).NotNull(); return WithAuthentication((schemes, roundtrip) => authentication); } /// <summary> /// Sets the authentication to be used in the session establishment. /// </summary> /// <param name="authenticator">The authenticator.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithAuthentication(Func<AuthenticationScheme[], Authentication, Authentication> authenticator) { Guard.Argument(authenticator, nameof(authenticator)).NotNull(); Authenticator = authenticator; return this; } /// <summary> /// Sets the identity to be used in the session establishment. /// </summary> /// <param name="identity">The identity to be used.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithIdentity(Identity identity) { Guard.Argument(identity, nameof(identity)).NotNull(); Identity = identity; return this; } /// <summary> /// Sets the instance name to be used in the session establishment. /// </summary> /// <param name="instance">The instance to be used.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder WithInstance(string instance) { Guard.Argument(instance, nameof(instance)).NotNull(); Instance = instance; return this; } /// <summary> /// Adds a handler to be executed after the channel is built and established. /// </summary> /// <param name="establishedHandler">The handler to be executed.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public IEstablishedClientChannelBuilder AddEstablishedHandler(Func<IClientChannel, CancellationToken, Task> establishedHandler) { Guard.Argument(establishedHandler, nameof(establishedHandler)).NotNull(); _establishedHandlers.Add(establishedHandler); return this; } /// <summary> /// Creates a copy of the current builder instance. /// </summary> /// <returns></returns> public IEstablishedClientChannelBuilder Copy() { return (IEstablishedClientChannelBuilder)MemberwiseClone(); } /// <summary> /// Builds a <see cref="ClientChannel"/> instance and establish the session using the builder options. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public async Task<IClientChannel> BuildAndEstablishAsync(CancellationToken cancellationToken) { var clientChannel = await ChannelBuilder .BuildAsync(cancellationToken) .ConfigureAwait(false); try { Session session; using (var cancellationTokenSource = new CancellationTokenSource(EstablishmentTimeout)) { using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) { session = await clientChannel.EstablishSessionAsync( CompressionSelector, EncryptionSelector, Identity, Authenticator, Instance, linkedCts.Token) .ConfigureAwait(false); } } if (session.State != SessionState.Established) { var reason = session.Reason ?? new Reason() { Code = ReasonCodes.GENERAL_ERROR, Description = "Could not establish the session for an unknown reason" }; throw new LimeException(reason); } foreach (var handler in _establishedHandlers.ToList()) { cancellationToken.ThrowIfCancellationRequested(); await handler(clientChannel, cancellationToken).ConfigureAwait(false); } } catch { clientChannel.DisposeIfDisposable(); throw; } return clientChannel; } internal EstablishedClientChannelBuilder ShallowCopy() { return (EstablishedClientChannelBuilder)MemberwiseClone(); } } }
// 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.Drawing; using System.Globalization; using System.Linq; using Xunit; namespace System.ComponentModel.TypeConverterTests { public class SizeConverterTests : StringTypeConverterTestBase<Size> { protected override TypeConverter Converter { get; } = new SizeConverter(); protected override bool StandardValuesSupported { get; } = false; protected override bool StandardValuesExclusive { get; } = false; protected override Size Default => new Size(1, 1); protected override bool CreateInstanceSupported { get; } = true; protected override bool IsGetPropertiesSupported { get; } = true; protected override IEnumerable<Tuple<Size, Dictionary<string, object>>> CreateInstancePairs { get { yield return Tuple.Create(new Size(10, 20), new Dictionary<string, object> { ["Width"] = 10, ["Height"] = 20, }); yield return Tuple.Create(new Size(-2, 3), new Dictionary<string, object> { ["Width"] = -2, ["Height"] = 3, }); } } [Theory] [InlineData(typeof(string))] public void CanConvertFromTrue(Type type) { CanConvertFrom(type); } [Theory] [InlineData(typeof(Rectangle))] [InlineData(typeof(RectangleF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(Color))] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(object))] [InlineData(typeof(int))] public void CanConvertFromFalse(Type type) { CannotConvertFrom(type); } [Theory] [InlineData(typeof(string))] public void CanConvertToTrue(Type type) { CanConvertTo(type); } [Theory] [InlineData(typeof(Rectangle))] [InlineData(typeof(RectangleF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(Color))] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(object))] [InlineData(typeof(int))] public void CanConvertToFalse(Type type) { CannotConvertTo(type); } public static IEnumerable<object[]> SizeData => new[] { new object[] {0, 0}, new object[] {1, 1}, new object[] {-1, 1}, new object[] {1, -1}, new object[] {-1, -1}, new object[] {int.MaxValue, int.MaxValue}, new object[] {int.MinValue, int.MaxValue}, new object[] {int.MaxValue, int.MinValue}, new object[] {int.MinValue, int.MinValue}, }; [Theory] [MemberData(nameof(SizeData))] public void ConvertFrom(int width, int height) { TestConvertFromString(new Size(width, height), $"{width}, {height}"); } [Theory] [InlineData("1")] [InlineData("1, 1, 1")] public void ConvertFrom_ArgumentException(string value) { ConvertFromThrowsArgumentExceptionForString(value); } [Fact] public void ConvertFrom_Invalid() { ConvertFromThrowsFormatInnerExceptionForString("*1, 1"); } public static IEnumerable<object[]> ConvertFrom_NotSupportedData => new[] { new object[] {new Point(1, 1)}, new object[] {new PointF(1, 1)}, new object[] {new Size(1, 1)}, new object[] {new SizeF(1, 1)}, new object[] {0x10}, }; [Theory] [MemberData(nameof(ConvertFrom_NotSupportedData))] public void ConvertFrom_NotSupported(object value) { ConvertFromThrowsNotSupportedFor(value); } [Theory] [MemberData(nameof(SizeData))] public void ConvertTo(int width, int height) { TestConvertToString(new Size(width, height), $"{width}, {height}"); } [Theory] [InlineData(typeof(Size))] [InlineData(typeof(SizeF))] [InlineData(typeof(Point))] [InlineData(typeof(PointF))] [InlineData(typeof(int))] public void ConvertTo_NotSupportedException(Type type) { ConvertToThrowsNotSupportedForType(type); } [Fact] public void ConvertTo_NullCulture() { string listSep = CultureInfo.CurrentCulture.TextInfo.ListSeparator; Assert.Equal($"1{listSep} 1", Converter.ConvertTo(null, null, new Size(1, 1), typeof(string))); } [Fact] public void CreateInstance_CaseSensitive() { Assert.Throws<ArgumentException>(() => { Converter.CreateInstance(null, new Dictionary<string, object> { ["width"] = 1, ["Height"] = 1, }); }); } [Fact] public void GetProperties() { var pt = new Size(1, 1); var props = Converter.GetProperties(new Size(1, 1)); Assert.Equal(3, props.Count); Assert.Equal(1, props["Width"].GetValue(pt)); Assert.Equal(1, props["Height"].GetValue(pt)); Assert.Equal(false, props["IsEmpty"].GetValue(pt)); props = Converter.GetProperties(null, new Size(1, 1)); Assert.Equal(3, props.Count); Assert.Equal(1, props["Width"].GetValue(pt)); Assert.Equal(1, props["Height"].GetValue(pt)); Assert.Equal(false, props["IsEmpty"].GetValue(pt)); props = Converter.GetProperties(null, new Size(1, 1), null); Assert.Equal(3, props.Count); Assert.Equal(1, props["Width"].GetValue(pt)); Assert.Equal(1, props["Height"].GetValue(pt)); Assert.Equal(false, props["IsEmpty"].GetValue(pt)); props = Converter.GetProperties(null, new Size(1, 1), typeof(Size).GetCustomAttributes(true).OfType<Attribute>().ToArray()); Assert.Equal(3, props.Count); Assert.Equal(1, props["Width"].GetValue(pt)); Assert.Equal(1, props["Height"].GetValue(pt)); Assert.Equal(false, props["IsEmpty"].GetValue(pt)); } [Theory] [MemberData(nameof(SizeData))] public void ConvertFromInvariantString(int width, int height) { var point = (Size)Converter.ConvertFromInvariantString($"{width}, {height}"); Assert.Equal(width, point.Width); Assert.Equal(height, point.Height); } [Fact] public void ConvertFromInvariantString_ArgumentException() { ConvertFromInvariantStringThrowsArgumentException("1"); } [Fact] public void ConvertFromInvariantString_FormatException() { ConvertFromInvariantStringThrowsFormatInnerException("hello"); } [Theory] [MemberData(nameof(SizeData))] public void ConvertFromString(int width, int height) { var point = (Size)Converter.ConvertFromString(string.Format("{0}{2} {1}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator)); Assert.Equal(width, point.Width); Assert.Equal(height, point.Height); } [Fact] public void ConvertFromString_ArgumentException() { ConvertFromStringThrowsArgumentException("1"); } [Fact] public void ConvertFromString_FormatException() { ConvertFromStringThrowsFormatInnerException("hello"); } [Theory] [MemberData(nameof(SizeData))] public void ConvertToInvariantString(int width, int height) { var str = Converter.ConvertToInvariantString(new Size(width, height)); Assert.Equal($"{width}, {height}", str); } [Theory] [MemberData(nameof(SizeData))] public void ConvertToString(int width, int height) { var str = Converter.ConvertToString(new Size(width, height)); Assert.Equal(string.Format("{0}{2} {1}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the ConConsultaMedicamento class. /// </summary> [Serializable] public partial class ConConsultaMedicamentoCollection : ActiveList<ConConsultaMedicamento, ConConsultaMedicamentoCollection> { public ConConsultaMedicamentoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ConConsultaMedicamentoCollection</returns> public ConConsultaMedicamentoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { ConConsultaMedicamento o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the CON_ConsultaMedicamento table. /// </summary> [Serializable] public partial class ConConsultaMedicamento : ActiveRecord<ConConsultaMedicamento>, IActiveRecord { #region .ctors and Default Settings public ConConsultaMedicamento() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public ConConsultaMedicamento(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public ConConsultaMedicamento(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public ConConsultaMedicamento(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("CON_ConsultaMedicamento", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdConsultaMedicamento = new TableSchema.TableColumn(schema); colvarIdConsultaMedicamento.ColumnName = "idConsultaMedicamento"; colvarIdConsultaMedicamento.DataType = DbType.Int32; colvarIdConsultaMedicamento.MaxLength = 0; colvarIdConsultaMedicamento.AutoIncrement = true; colvarIdConsultaMedicamento.IsNullable = false; colvarIdConsultaMedicamento.IsPrimaryKey = true; colvarIdConsultaMedicamento.IsForeignKey = false; colvarIdConsultaMedicamento.IsReadOnly = false; colvarIdConsultaMedicamento.DefaultSetting = @""; colvarIdConsultaMedicamento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdConsultaMedicamento); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = true; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; colvarIdEfector.DefaultSetting = @""; colvarIdEfector.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEfector); TableSchema.TableColumn colvarIdConsulta = new TableSchema.TableColumn(schema); colvarIdConsulta.ColumnName = "idConsulta"; colvarIdConsulta.DataType = DbType.Int32; colvarIdConsulta.MaxLength = 0; colvarIdConsulta.AutoIncrement = false; colvarIdConsulta.IsNullable = true; colvarIdConsulta.IsPrimaryKey = false; colvarIdConsulta.IsForeignKey = true; colvarIdConsulta.IsReadOnly = false; colvarIdConsulta.DefaultSetting = @""; colvarIdConsulta.ForeignKeyTableName = "CON_Consulta"; schema.Columns.Add(colvarIdConsulta); TableSchema.TableColumn colvarIdMedicamento = new TableSchema.TableColumn(schema); colvarIdMedicamento.ColumnName = "idMedicamento"; colvarIdMedicamento.DataType = DbType.Int32; colvarIdMedicamento.MaxLength = 0; colvarIdMedicamento.AutoIncrement = false; colvarIdMedicamento.IsNullable = true; colvarIdMedicamento.IsPrimaryKey = false; colvarIdMedicamento.IsForeignKey = false; colvarIdMedicamento.IsReadOnly = false; colvarIdMedicamento.DefaultSetting = @""; colvarIdMedicamento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMedicamento); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("CON_ConsultaMedicamento",schema); } } #endregion #region Props [XmlAttribute("IdConsultaMedicamento")] [Bindable(true)] public int IdConsultaMedicamento { get { return GetColumnValue<int>(Columns.IdConsultaMedicamento); } set { SetColumnValue(Columns.IdConsultaMedicamento, value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int? IdEfector { get { return GetColumnValue<int?>(Columns.IdEfector); } set { SetColumnValue(Columns.IdEfector, value); } } [XmlAttribute("IdConsulta")] [Bindable(true)] public int? IdConsulta { get { return GetColumnValue<int?>(Columns.IdConsulta); } set { SetColumnValue(Columns.IdConsulta, value); } } [XmlAttribute("IdMedicamento")] [Bindable(true)] public int? IdMedicamento { get { return GetColumnValue<int?>(Columns.IdMedicamento); } set { SetColumnValue(Columns.IdMedicamento, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a ConConsultum ActiveRecord object related to this ConConsultaMedicamento /// /// </summary> public DalSic.ConConsultum ConConsultum { get { return DalSic.ConConsultum.FetchByID(this.IdConsulta); } set { SetColumnValue("idConsulta", value.IdConsulta); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int? varIdEfector,int? varIdConsulta,int? varIdMedicamento) { ConConsultaMedicamento item = new ConConsultaMedicamento(); item.IdEfector = varIdEfector; item.IdConsulta = varIdConsulta; item.IdMedicamento = varIdMedicamento; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdConsultaMedicamento,int? varIdEfector,int? varIdConsulta,int? varIdMedicamento) { ConConsultaMedicamento item = new ConConsultaMedicamento(); item.IdConsultaMedicamento = varIdConsultaMedicamento; item.IdEfector = varIdEfector; item.IdConsulta = varIdConsulta; item.IdMedicamento = varIdMedicamento; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdConsultaMedicamentoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEfectorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdConsultaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdMedicamentoColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string IdConsultaMedicamento = @"idConsultaMedicamento"; public static string IdEfector = @"idEfector"; public static string IdConsulta = @"idConsulta"; public static string IdMedicamento = @"idMedicamento"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using Glipho.OAuth.Providers.WebApiSample.Areas.HelpPage.Models; namespace Glipho.OAuth.Providers.WebApiSample.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 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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; using System.IO; namespace SoftLogik.Miscellaneous { public enum GridLines { None, Horizontal, Vertical, Both } public class TableTextWriter : TextWriter { #region Private inner types private struct Cell { string _text; public Cell(string text) { _text = text; } public string Text { get { return _text ?? string.Empty; } } } private class Column { private int _maximumWidth; public int MaximumWidth { get { return _maximumWidth; } } public Column(int maximumWidth) { _maximumWidth = maximumWidth; } } private struct Row { private List<Cell> _cells; public Row(List<Cell> cells) { _cells = cells; } public List<Cell> Cells { get { return _cells; } } } #endregion private TextWriter _writer; private List<Row> _rows; private Row? _currentRow; private int _columnSpacing; private bool _border; private GridLines _gridLines; public GridLines GridLines { get { return _gridLines; } set { _gridLines = value; } } public bool Border { get { return _border; } set { _border = value; } } public int ColumnSpacing { get { return _columnSpacing; } set { _columnSpacing = value; } } public TableTextWriter(TextWriter writer) { _writer = writer; _columnSpacing = 1; } private void EnsureCurrentLine() { if (_rows == null) _rows = new List<Row>(); if (_currentRow == null) { _currentRow = new Row(new List<Cell>()); _rows.Add(_currentRow.Value); } } private void WriteSpacing() { _writer.Write(new string(' ', _columnSpacing)); } private int CalculateColumnSpacing() { if (_gridLines == GridLines.Vertical || _gridLines == GridLines.Both) return (_columnSpacing * 2) + 1; else return _columnSpacing; } public override void Flush() { if (_rows == null) return; List<Column> columns = CalculateCellColumns(); int columnsTotalWidth = CalculateTotalColumnCellWidth(columns); int columnsTotalSpacing = CalculateTotalColumnSpacingWidth(columns); int totalInnerWidth = columnsTotalWidth + columnsTotalSpacing + (_columnSpacing * 2); if (_border) { _writer.Write(@"/"); _writer.Write(new string('-', totalInnerWidth)); _writer.Write(@"\"); _writer.WriteLine(); } for (int rowIndex = 0; rowIndex < _rows.Count; rowIndex++) { Row row = _rows[rowIndex]; if (_border) { _writer.Write("|"); WriteSpacing(); } for (int i = 0; i < columns.Count; i++) { Column column = columns[i]; Cell? cell = (i < row.Cells.Count) ? new Cell?(row.Cells[i]) : null; InternalWrite(cell, columns[i]); WriteSpacing(); if (i + 1 < columns.Count && (_gridLines == GridLines.Vertical || _gridLines == GridLines.Both)) { _writer.Write("|"); WriteSpacing(); } } if (_border) _writer.Write("|"); _writer.WriteLine(); if (rowIndex + 1 < _rows.Count) { if (_gridLines == GridLines.Horizontal || _gridLines == GridLines.Both) { if (_border) _writer.Write("|"); _writer.Write(new string('-', totalInnerWidth)); if (_border) _writer.Write("|"); _writer.WriteLine(); } } } if (_border) { _writer.Write(@"\"); _writer.Write(new string('-', totalInnerWidth)); _writer.Write(@"/"); _writer.WriteLine(); } _rows = null; _writer.Flush(); } private int CalculateTotalColumnCellWidth(List<Column> columns) { int totalWidth = 0; foreach (Column column in columns) { totalWidth += column.MaximumWidth; } return totalWidth; } private List<Column> CalculateCellColumns() { SortedDictionary<int, int> cellIndexMaximumWidths = new SortedDictionary<int, int>(Comparer<int>.Default); for (int rowIndex = 0; rowIndex < _rows.Count; rowIndex++) { Row row = _rows[rowIndex]; for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++) { Cell cell = row.Cells[cellIndex]; int maximumWidth; cellIndexMaximumWidths.TryGetValue(cellIndex, out maximumWidth); cellIndexMaximumWidths[cellIndex] = Math.Max(cell.Text.Length, maximumWidth); } } List<Column> columns = new List<Column>(); foreach (int columnIndex in cellIndexMaximumWidths.Keys) { columns.Add(new Column(cellIndexMaximumWidths[columnIndex])); } return columns; } private int CalculateTotalColumnSpacingWidth(List<Column> columns) { return (columns.Count - 1) * CalculateColumnSpacing(); } private void InternalWrite(Cell? cell, Column column) { string text = (cell != null) ? cell.Value.Text : string.Empty; _writer.Write(text); for (int i = text.Length; i < column.MaximumWidth; i++) { _writer.Write(' '); } } private void AddCell(string text) { EnsureCurrentLine(); _currentRow.Value.Cells.Add(new Cell(text)); } #region TextWriter overriden members protected override void Dispose(bool disposing) { if (disposing) Flush(); base.Dispose(disposing); } public override Encoding Encoding { get { return _writer.Encoding; } } public override void Write(object value) { if (value == null) Write(string.Empty); base.Write(value); } public override void Write(string value) { AddCell(value); } public override void Write(char[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException("buffer", "Buffer cannot be null."); if (index < 0) throw new ArgumentOutOfRangeException("index", "Non-negative number required."); if (count < 0) throw new ArgumentOutOfRangeException("index", "Non-negative number required."); if (buffer.Length - index < count) throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."); Write(new string(buffer, index, count)); } public override void Write(char value) { Write(value.ToString()); } public override void WriteLine() { if (_currentRow == null) EnsureCurrentLine(); _currentRow = null; } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.ComponentModel.Design; using System.IO; using System.Linq; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Notification; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.SolutionExplorer; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using VSLangProj140; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export] internal class AnalyzersCommandHandler : IAnalyzersCommandHandler, IVsUpdateSolutionEvents { private readonly AnalyzerItemsTracker _tracker; private readonly AnalyzerReferenceManager _analyzerReferenceManager; private readonly IServiceProvider _serviceProvider; private ContextMenuController _analyzerFolderContextMenuController; private ContextMenuController _analyzerContextMenuController; private ContextMenuController _diagnosticContextMenuController; // Analyzers folder context menu items private MenuCommand _addMenuItem; private MenuCommand _openRuleSetMenuItem; // Analyzer context menu items private MenuCommand _removeMenuItem; // Diagnostic context menu items private MenuCommand _setSeverityDefaultMenuItem; private MenuCommand _setSeverityErrorMenuItem; private MenuCommand _setSeverityWarningMenuItem; private MenuCommand _setSeverityInfoMenuItem; private MenuCommand _setSeverityHiddenMenuItem; private MenuCommand _setSeverityNoneMenuItem; private MenuCommand _openHelpLinkMenuItem; // Other menu items private MenuCommand _projectAddMenuItem; private MenuCommand _projectContextAddMenuItem; private MenuCommand _referencesContextAddMenuItem; private MenuCommand _setActiveRuleSetMenuItem; private Workspace _workspace; private bool _allowProjectSystemOperations = true; [ImportingConstructor] public AnalyzersCommandHandler( AnalyzerItemsTracker tracker, AnalyzerReferenceManager analyzerReferenceManager, [Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider) { _tracker = tracker; _analyzerReferenceManager = analyzerReferenceManager; _serviceProvider = serviceProvider; } /// <summary> /// Hook up the context menu handlers. /// </summary> public void Initialize(IMenuCommandService menuCommandService) { if (menuCommandService != null) { // Analyzers folder context menu items _addMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.AddAnalyzer, AddAnalyzerHandler); _openRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenRuleSet, OpenRuleSetHandler); // Analyzer context menu items _removeMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.RemoveAnalyzer, RemoveAnalyzerHandler); // Diagnostic context menu items _setSeverityDefaultMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityDefault, SetSeverityHandler); _setSeverityErrorMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityError, SetSeverityHandler); _setSeverityWarningMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityWarning, SetSeverityHandler); _setSeverityInfoMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityInfo, SetSeverityHandler); _setSeverityHiddenMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityHidden, SetSeverityHandler); _setSeverityNoneMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityNone, SetSeverityHandler); _openHelpLinkMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenDiagnosticHelpLink, OpenDiagnosticHelpLinkHandler); // Other menu items _projectAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectAddAnalyzer, AddAnalyzerHandler); _projectContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectContextAddAnalyzer, AddAnalyzerHandler); _referencesContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ReferencesContextAddAnalyzer, AddAnalyzerHandler); _setActiveRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetActiveRuleSet, SetActiveRuleSetHandler); UpdateOtherMenuItemsVisibility(); if (_tracker != null) { _tracker.SelectedHierarchyItemChanged += SelectedHierarchyItemChangedHandler; } var buildManager = (IVsSolutionBuildManager)_serviceProvider.GetService(typeof(SVsSolutionBuildManager)); uint cookie; buildManager.AdviseUpdateSolutionEvents(this, out cookie); } } public IContextMenuController AnalyzerFolderContextMenuController { get { if (_analyzerFolderContextMenuController == null) { _analyzerFolderContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerFolderContextMenu, ShouldShowAnalyzerFolderContextMenu, UpdateAnalyzerFolderContextMenu); } return _analyzerFolderContextMenuController; } } private bool ShouldShowAnalyzerFolderContextMenu(IEnumerable<object> items) { return items.Count() == 1; } private void UpdateAnalyzerFolderContextMenu() { if (_addMenuItem != null) { _addMenuItem.Visible = SelectedProjectSupportsAnalyzers(); _addMenuItem.Enabled = _allowProjectSystemOperations; } } public IContextMenuController AnalyzerContextMenuController { get { if (_analyzerContextMenuController == null) { _analyzerContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerContextMenu, ShouldShowAnalyzerContextMenu, UpdateAnalyzerContextMenu); } return _analyzerContextMenuController; } } private bool ShouldShowAnalyzerContextMenu(IEnumerable<object> items) { return items.All(item => item is AnalyzerItem); } private void UpdateAnalyzerContextMenu() { _removeMenuItem.Enabled = _allowProjectSystemOperations; } public IContextMenuController DiagnosticContextMenuController { get { if (_diagnosticContextMenuController == null) { _diagnosticContextMenuController = new ContextMenuController( ID.RoslynCommands.DiagnosticContextMenu, ShouldShowDiagnosticContextMenu, UpdateDiagnosticContextMenu); } return _diagnosticContextMenuController; } } private bool ShouldShowDiagnosticContextMenu(IEnumerable<object> items) { return items.All(item => item is DiagnosticItem); } private void UpdateDiagnosticContextMenu() { UpdateSeverityMenuItemsChecked(); UpdateSeverityMenuItemsEnabled(); UpdateOpenHelpLinkMenuItemVisibility(); } private MenuCommand AddCommandHandler(IMenuCommandService menuCommandService, int roslynCommand, EventHandler handler) { var commandID = new CommandID(Guids.RoslynGroupId, roslynCommand); var menuCommand = new MenuCommand(handler, commandID); menuCommandService.AddCommand(menuCommand); return menuCommand; } private void SelectedHierarchyItemChangedHandler(object sender, EventArgs e) { UpdateOtherMenuItemsVisibility(); } private void UpdateOtherMenuItemsVisibility() { bool selectedProjectSupportsAnalyzers = SelectedProjectSupportsAnalyzers(); _projectAddMenuItem.Visible = selectedProjectSupportsAnalyzers; _projectContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedItemId == VSConstants.VSITEMID_ROOT; _referencesContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers; string itemName; _setActiveRuleSetMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedHierarchy.TryGetItemName(_tracker.SelectedItemId, out itemName) && Path.GetExtension(itemName).Equals(".ruleset", StringComparison.OrdinalIgnoreCase); } private void UpdateOtherMenuItemsEnabled() { _projectAddMenuItem.Enabled = _allowProjectSystemOperations; _projectContextAddMenuItem.Enabled = _allowProjectSystemOperations; _referencesContextAddMenuItem.Enabled = _allowProjectSystemOperations; _removeMenuItem.Enabled = _allowProjectSystemOperations; } private void UpdateOpenHelpLinkMenuItemVisibility() { _openHelpLinkMenuItem.Visible = _tracker.SelectedDiagnosticItems.Length == 1 && _tracker.SelectedDiagnosticItems[0].GetHelpLink() != null; } private void UpdateSeverityMenuItemsChecked() { _setSeverityDefaultMenuItem.Checked = false; _setSeverityErrorMenuItem.Checked = false; _setSeverityWarningMenuItem.Checked = false; _setSeverityInfoMenuItem.Checked = false; _setSeverityHiddenMenuItem.Checked = false; _setSeverityNoneMenuItem.Checked = false; var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } HashSet<ReportDiagnostic> selectedItemSeverities = new HashSet<ReportDiagnostic>(); var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.AnalyzerItem.AnalyzersFolder.ProjectId); foreach (var group in groups) { var project = (AbstractProject)workspace.GetHostProject(group.Key); IRuleSetFile ruleSet = project.RuleSetFile; if (ruleSet != null) { var specificOptions = ruleSet.GetSpecificDiagnosticOptions(); foreach (var diagnosticItem in group) { ReportDiagnostic ruleSetSeverity; if (specificOptions.TryGetValue(diagnosticItem.Descriptor.Id, out ruleSetSeverity)) { selectedItemSeverities.Add(ruleSetSeverity); } else { // The rule has no setting. selectedItemSeverities.Add(ReportDiagnostic.Default); } } } } if (selectedItemSeverities.Count != 1) { return; } switch (selectedItemSeverities.Single()) { case ReportDiagnostic.Default: _setSeverityDefaultMenuItem.Checked = true; break; case ReportDiagnostic.Error: _setSeverityErrorMenuItem.Checked = true; break; case ReportDiagnostic.Warn: _setSeverityWarningMenuItem.Checked = true; break; case ReportDiagnostic.Info: _setSeverityInfoMenuItem.Checked = true; break; case ReportDiagnostic.Hidden: _setSeverityHiddenMenuItem.Checked = true; break; case ReportDiagnostic.Suppress: _setSeverityNoneMenuItem.Checked = true; break; default: break; } } private bool AnyDiagnosticsWithSeverity(ReportDiagnostic severity) { return _tracker.SelectedDiagnosticItems.Any(item => item.EffectiveSeverity == severity); } private void UpdateSeverityMenuItemsEnabled() { bool configurable = !_tracker.SelectedDiagnosticItems.Any(item => item.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable)); _setSeverityDefaultMenuItem.Enabled = configurable; _setSeverityErrorMenuItem.Enabled = configurable; _setSeverityWarningMenuItem.Enabled = configurable; _setSeverityInfoMenuItem.Enabled = configurable; _setSeverityHiddenMenuItem.Enabled = configurable; _setSeverityNoneMenuItem.Enabled = configurable; } private bool SelectedProjectSupportsAnalyzers() { EnvDTE.Project project; return _tracker != null && _tracker.SelectedHierarchy != null && _tracker.SelectedHierarchy.TryGetProject(out project) && project.Object is VSProject3; } /// <summary> /// Handler for "Add Analyzer..." context menu on Analyzers folder node. /// </summary> internal void AddAnalyzerHandler(object sender, EventArgs args) { if (_analyzerReferenceManager != null) { _analyzerReferenceManager.ShowDialog(); } } /// <summary> /// Handler for "Remove" context menu on individual Analyzer items. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void RemoveAnalyzerHandler(object sender, EventArgs args) { foreach (var item in _tracker.SelectedAnalyzerItems) { item.Remove(); } } internal void OpenRuleSetHandler(object sender, EventArgs args) { if (_tracker.SelectedFolder != null && _serviceProvider != null) { var workspace = _tracker.SelectedFolder.Workspace as VisualStudioWorkspaceImpl; var projectId = _tracker.SelectedFolder.ProjectId; if (workspace != null) { var project = (AbstractProject)workspace.GetHostProject(projectId); if (project == null) { SendUnableToOpenRuleSetNotification(workspace, string.Format(SolutionExplorerShim.Could_not_find_project_0, projectId)); return; } if (project.RuleSetFile == null) { SendUnableToOpenRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); return; } try { EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE)); dte.ItemOperations.OpenFile(project.RuleSetFile.FilePath); } catch (Exception e) { SendUnableToOpenRuleSetNotification(workspace, e.Message); } } } } private void SetSeverityHandler(object sender, EventArgs args) { var selectedItem = (MenuCommand)sender; ReportDiagnostic? selectedAction = MapSelectedItemToReportDiagnostic(selectedItem); if (!selectedAction.HasValue) { return; } var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } foreach (var selectedDiagnostic in _tracker.SelectedDiagnosticItems) { var projectId = selectedDiagnostic.AnalyzerItem.AnalyzersFolder.ProjectId; var project = (AbstractProject)workspace.GetHostProject(projectId); if (project == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.Could_not_find_project_0, projectId)); continue; } var pathToRuleSet = project.RuleSetFile?.FilePath; if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.No_rule_set_file_is_specified_or_the_file_does_not_exist); continue; } try { EnvDTE.Project envDteProject; project.Hierarchy.TryGetProject(out envDteProject); if (SdkUiUtilities.IsBuiltInRuleSet(pathToRuleSet, _serviceProvider)) { pathToRuleSet = CreateCopyOfRuleSetForProject(pathToRuleSet, envDteProject); if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.Could_not_create_a_rule_set_for_project_0, envDteProject.Name)); continue; } var fileInfo = new FileInfo(pathToRuleSet); fileInfo.IsReadOnly = false; } var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var waitIndicator = componentModel.GetService<IWaitIndicator>(); waitIndicator.Wait( title: SolutionExplorerShim.Rule_Set, message: string.Format(SolutionExplorerShim.Checking_out_0_for_editing, Path.GetFileName(pathToRuleSet)), allowCancel: false, action: c => { if (envDteProject.DTE.SourceControl.IsItemUnderSCC(pathToRuleSet)) { envDteProject.DTE.SourceControl.CheckOutItem(pathToRuleSet); } }); selectedDiagnostic.SetSeverity(selectedAction.Value, pathToRuleSet); } catch (Exception e) { SendUnableToUpdateRuleSetNotification(workspace, e.Message); } } } private void OpenDiagnosticHelpLinkHandler(object sender, EventArgs e) { if (_tracker.SelectedDiagnosticItems.Length != 1) { return; } var uri = _tracker.SelectedDiagnosticItems[0].GetHelpLink(); if (uri != null) { BrowserHelper.StartBrowser(uri); } } private void SetActiveRuleSetHandler(object sender, EventArgs e) { EnvDTE.Project project; string ruleSetFileFullPath; if (_tracker.SelectedHierarchy.TryGetProject(out project) && _tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out ruleSetFileFullPath)) { string projectDirectoryFullPath = Path.GetDirectoryName(project.FullName); string ruleSetFileRelativePath = FilePathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath); UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath); } } private string CreateCopyOfRuleSetForProject(string pathToRuleSet, EnvDTE.Project envDteProject) { string fileName = GetNewRuleSetFileNameForProject(envDteProject); string projectDirectory = Path.GetDirectoryName(envDteProject.FullName); string fullFilePath = Path.Combine(projectDirectory, fileName); File.Copy(pathToRuleSet, fullFilePath); UpdateProjectConfigurationsToUseRuleSetFile(envDteProject, fileName); envDteProject.ProjectItems.AddFromFile(fullFilePath); return fullFilePath; } private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName) { foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager) { EnvDTE.Properties properties = config.Properties; try { EnvDTE.Property codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet"); if (codeAnalysisRuleSetFileProperty != null) { codeAnalysisRuleSetFileProperty.Value = fileName; } } catch (ArgumentException) { // Unfortunately the properties collection sometimes throws an ArgumentException // instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet. // Ignore it and move on. } } } private string GetNewRuleSetFileNameForProject(EnvDTE.Project envDteProject) { string projectName = envDteProject.Name; HashSet<string> projectItemNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (ProjectItem item in envDteProject.ProjectItems) { projectItemNames.Add(item.Name); } string ruleSetName = projectName + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } for (int i = 1; i < int.MaxValue; i++) { ruleSetName = projectName + i + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } } return null; } private static ReportDiagnostic? MapSelectedItemToReportDiagnostic(MenuCommand selectedItem) { ReportDiagnostic? selectedAction = null; if (selectedItem.CommandID.Guid == Guids.RoslynGroupId) { switch (selectedItem.CommandID.ID) { case ID.RoslynCommands.SetSeverityDefault: selectedAction = ReportDiagnostic.Default; break; case ID.RoslynCommands.SetSeverityError: selectedAction = ReportDiagnostic.Error; break; case ID.RoslynCommands.SetSeverityWarning: selectedAction = ReportDiagnostic.Warn; break; case ID.RoslynCommands.SetSeverityInfo: selectedAction = ReportDiagnostic.Info; break; case ID.RoslynCommands.SetSeverityHidden: selectedAction = ReportDiagnostic.Hidden; break; case ID.RoslynCommands.SetSeverityNone: selectedAction = ReportDiagnostic.Suppress; break; default: selectedAction = null; break; } } return selectedAction; } private void SendUnableToOpenRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.The_rule_set_file_could_not_be_opened, message); } private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.The_rule_set_file_could_not_be_updated, message); } private void SendErrorNotification(Workspace workspace, string message1, string message2) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification(message1 + Environment.NewLine + Environment.NewLine + message2, severity: NotificationSeverity.Error); } int IVsUpdateSolutionEvents.UpdateSolution_Begin(ref int pfCancelUpdate) { _allowProjectSystemOperations = false; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_StartUpdate(ref int pfCancelUpdate) { return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Cancel() { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy) { return VSConstants.S_OK; } private Workspace TryGetWorkspace() { if (_workspace == null) { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var provider = componentModel.DefaultExportProvider.GetExportedValueOrDefault<ISolutionExplorerWorkspaceProvider>(); if (provider != null) { _workspace = provider.GetWorkspace(); } } return _workspace; } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet * The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangBulgarianModel.cpp * and adjusted to language specific support. */ namespace UtfUnknown.Core.Models.SingleByte.Bulgarian; internal class Iso_8859_5_BulgarianModel : BulgarianModel { // CTR: Control characters that usually does not exist in any text // RET: Carriage/Return // SYM: symbol(punctuation) that does not belong to word // NUM: 0 - 9 // // Character Mapping Table: // this table is modified base on win1251BulgarianCharToOrderMap, so // only number <64 is sure valid private static byte[] CHAR_TO_ORDER_MAP = { CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, RET, CTR, CTR, RET, CTR, CTR, /* 0X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 1X */ SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* 2X */ NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, SYM, SYM, SYM, SYM, SYM, SYM, /* 3X */ SYM, 77, 90, 99, 100, 72, 109, 107, 101, 79, 185, 81, 102, 76, 94, 82, /* 4X */ 110, 186, 108, 91, 74, 119, 84, 96, 111, 187, 115, SYM, SYM, SYM, SYM, SYM, /* 5X */ SYM, 65, 69, 70, 66, 63, 68, 112, 103, 92, 194, 104, 95, 86, 87, 71, /* 6X */ 116, 195, 85, 93, 97, 113, 196, 197, 198, 199, 200, SYM, SYM, SYM, SYM, SYM, /* 7X */ 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, /* 8X */ 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, /* 9X */ 81, 226, 227, 228, 229, 230, 105, 231, 232, 233, 234, 235, 236, 45, 237, 238, /* AX */ 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, /* BX */ 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61, 239, 67, 240, 60, 56, /* CX */ 1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, /* DX */ 7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52, 241, 42, 16, /* EX */ 62, 242, 243, 244, 58, 245, 98, 246, 247, 248, 249, 250, 251, 91, NUM, SYM /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ public Iso_8859_5_BulgarianModel() : base( CHAR_TO_ORDER_MAP, CodepageName.ISO_8859_5) { } }
/* Copyright (c) 2006-2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ #region Using directives #define USE_TRACING using System; using System.Xml; using System.IO; using System.Globalization; using System.Collections; using Google.GData.Extensions; using System.Collections.Generic; #endregion /// <summary> /// Contains AtomBase, the base class for all Atom-related objects. /// AtomBase holds the two common properties (xml:lang and xml:base). /// </summary> namespace Google.GData.Client { /// <summary> /// Helper object to walk the tree for the dirty flag. /// </summary> public class BaseIsDirty : IBaseWalkerAction { /// <summary>Walker action. Just gets a property.</summary> /// <param name="atom">object to set the property on</param> /// <returns>the value of the dirty flag</returns> public bool Go(AtomBase atom) { Tracing.Assert(atom != null, "atom should not be null"); if (atom == null) { throw new ArgumentNullException("atom"); } return atom.Dirty; } } /// <summary> /// Helper object to walk the tree for the dirty flag. /// </summary> public class BaseMarkDirty : IBaseWalkerAction { /// <summary>Holds if set/unset to dirty.</summary> private bool flag; /// <summary>Constructor.</summary> /// <param name="flag">indicates the value to pass </param> internal BaseMarkDirty(bool flag) { this.flag = flag; } /// <summary>Walker action. Just sets a property.</summary> /// <param name="atom">object to set the property on </param> /// <returns> always false, indicating to walk the whole tree</returns> public bool Go(AtomBase atom) { Tracing.Assert(atom != null, "atom should not be null"); if (atom == null) { throw new ArgumentNullException("atom"); } atom.Dirty = this.flag; return false; } } /// <summary>Helper to walk the tree and set the versioninformation</summary> internal class ChangeVersion : IBaseWalkerAction { private VersionInformation v; /// <summary>Constructor.</summary> /// <param name="v">the versioninformation to pass </param> internal ChangeVersion(IVersionAware v) { this.v = new VersionInformation(v); } /// <summary>Walker action. Just sets a property.</summary> /// <param name="atom">object to set the property on </param> /// <returns> always false, indicating to walk the whole tree</returns> public bool Go(AtomBase atom) { Tracing.Assert(atom != null, "atom should not be null"); if (atom == null) { throw new ArgumentNullException("atom"); } atom.SetVersionInfo(v); return false; } } /// <summary>Helper class, mainly used to walk the tree for the dirty flag.</summary> public class BaseIsPersistable : IBaseWalkerAction { /// <summary>Walker action. Just gets a property.</summary> /// <param name="atom">object to set the property on </param> /// <returns>returns the value of the ShouldBePersisted() of the object</returns> public bool Go(AtomBase atom) { Tracing.Assert(atom != null, "atom should not be null"); if (atom == null) { throw new ArgumentNullException("atom"); } bool f = atom.ShouldBePersisted(); return f; } } /// <summary> /// AtomBase object representation. /// </summary> public abstract class AtomBase : IExtensionContainer, IVersionAware { /// <summary>holds the base Uri</summary> private AtomUri uriBase; /// <summary>implied base, get's pushed down</summary> private AtomUri uriImpliedBase; /// <summary>holds the xml:lang element</summary> private string atomLanguageTag; /// <summary>extension element collection</summary> private ExtensionList extensionsList; /// <summary> extension element factories </summary> private ExtensionList extensionFactories; /// <summary>a boolean indicating that recalc is allowed to happen implicitly now</summary> private bool fAllowRecalc; /// <summary>holds a flag indicating if the thing should be send to the server</summary> private bool fIsDirty; /// <summary>sets the element and all subelemts dirty flag</summary> /// <param name="fFlag">indicates the property value to set</param> /// <returns> </returns> internal void MarkElementDirty(bool fFlag) { this.WalkTree(new BaseMarkDirty(fFlag)); } /// <summary> /// checks if the element or one subelement are persistable /// </summary> public bool IsPersistable() { return this.WalkTree(new BaseIsPersistable()); } /// <summary>returns if the element or one subelement is dirty</summary> public bool IsDirty() { return WalkTree(new BaseIsDirty()); } /// <summary>The dirty property - indicates if exactly this element is dirty</summary> /// <returns>returns true or false</returns> public bool Dirty { get { return this.fIsDirty; } set { this.fIsDirty = value; } } /// <summary>property that holds the implied base URI</summary> /// <returns> the implied base URI as an AtomUri</returns> protected AtomUri ImpliedBase { get { return this.uriImpliedBase; } set { this.uriImpliedBase = value; } } /// <summary>Returns the XML name as string used for the element when persisting.</summary> public abstract string XmlName { get; } /// <summary> /// Read only accessor for AbsoluteUri. This is pushed down /// whenever a base changes. /// </summary> public string GetAbsoluteUri(string part) { return Utilities.CalculateUri(this.Base, this.ImpliedBase, part); } /// <summary>This starts the calculation, to push down the base /// URI changes.</summary> /// <param name="uriValue">the baseuri calculated so far</param> internal virtual void BaseUriChanged(AtomUri uriValue) { // if this is ever getting called explicitly (parsing), we turn on recalc this.fAllowRecalc = true; this.uriImpliedBase = uriValue; } #region accessors /// <summary>calculates or sets the base uri of an element</summary> /// <returns>an AtomUri for the Base URI when get is called</returns> public AtomUri Base { get { return this.uriBase; } set { this.Dirty = true; this.uriBase = value; if (this.fAllowRecalc) { BaseUriChanged(value); } } } /// <summary>returns and sets the xml:lang value</summary> /// <returns> </returns> public string Language { get { return this.atomLanguageTag; } set { this.Dirty = true; this.atomLanguageTag = value; } } /// <summary> /// adding an extension factory for extension elements /// </summary> /// <param name="factory">The factory</param> public void AddExtension(IExtensionElementFactory factory) { Tracing.Assert(factory != null, "factory should not be null"); if (factory == null) { throw new ArgumentNullException("factory"); } this.ExtensionFactories.Add(factory); } /// <summary> /// removing an extension factory for extension elements /// </summary> /// <param name="factory">The factory</param> public void RemoveExtension(IExtensionElementFactory factory) { Tracing.Assert(factory != null, "factory should not be null"); if (factory == null) { throw new ArgumentNullException("factory"); } this.ExtensionFactories.Remove(factory.XmlNameSpace, factory.XmlName); } /// <summary> /// read only accessor for the Extension Factories /// </summary> public ExtensionList ExtensionFactories { get { if (this.extensionFactories == null) { this.extensionFactories = new ExtensionList(this); } return this.extensionFactories; } } /// <summary>Calls the action on this object and all children.</summary> /// <param name="action">an IBaseWalkerAction interface to call </param> /// <returns>true or false, pending outcome of the passed in action</returns> public virtual bool WalkTree(IBaseWalkerAction action) { Tracing.Assert(action != null, "action should not be null"); if (action == null) { throw new ArgumentNullException("action"); } return action.Go(this); } /// <summary>read only accessor for the ExtensionsElements Collections</summary> /// <returns> an ExtensionList of ExtensionElements</returns> public ExtensionList ExtensionElements { get { if (this.extensionsList == null) { this.extensionsList = new ExtensionList(this); } return this.extensionsList; } } /// <summary> /// Finds a specific ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, the first one where /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>Object</returns> public IExtensionElementFactory FindExtension(string localName, string ns) { return Utilities.FindExtension(this.ExtensionElements, localName, ns); } /// <summary> /// Creates an extension for a given name and namespace by walking the /// extension factories list and calling CreateInstance for the right one /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>Object</returns> public IExtensionElementFactory CreateExtension(string localName, string ns) { IExtensionElementFactory ele = null; IExtensionElementFactory f = FindExtensionFactory(localName, ns); if (f != null) { ele = f.CreateInstance(null, null); } return ele; } /// <summary> /// Finds the extension factory for a given name/namespace /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>Object</returns> public IExtensionElementFactory FindExtensionFactory(string localName, string ns) { foreach (IExtensionElementFactory f in this.ExtensionFactories) { if (String.Compare(ns, f.XmlNameSpace, true, CultureInfo.InvariantCulture) == 0) { if (String.Compare(localName, f.XmlName) == 0) { return f; } } } return null; } /// <summary> /// Finds all ExtensionElement based on local name /// and namespace. If namespace is NULL, all where /// the localname matches is found. If there are extensionelements that do /// not implement ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <returns>Object</returns> public ExtensionList FindExtensions(string localName, string ns) { return FindExtensions(localName, ns, new ExtensionList(this)); } /// <summary> /// Finds all ExtensionElement based on local name /// and namespace. If namespace is NULL, all where /// the localname matches is found. If there are extensionelements that do /// not implement ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to find</param> /// <param name="arr">the array to fill</param> /// <returns>none</returns> public ExtensionList FindExtensions(string localName, string ns, ExtensionList arr) { return Utilities.FindExtensions(this.ExtensionElements, localName, ns, arr); } /// <summary> /// Finds all ExtensionElement based on local name /// and amespace. If namespace is NULL, all where /// the localname matches is found. If there are extensionelements that do /// not implement ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the element to findt</param> /// <returns>none</returns> public List<T> FindExtensions<T>(string localName, string ns) where T : IExtensionElementFactory { return Utilities.FindExtensions<T>(this.ExtensionElements, localName, ns); } /// <summary> /// Deletes all Extensions from the Extension list that match /// a localName and a Namespace. /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <returns>int - the number of deleted extensions</returns> public int DeleteExtensions(string localName, string ns) { // Find them first ExtensionList arr = FindExtensions(localName, ns); foreach (IExtensionElementFactory ob in arr) { this.ExtensionElements.Remove(ob); } return arr.Count; } /// <summary> /// all extension elements that match a namespace/localname /// given will be removed and replaced with the new ones. /// the input array can contain several different /// namespace/localname combinations /// if the passed list is NULL or empty, this will just result /// in additions /// </summary> /// <param name="newList">a list of xmlnodes or IExtensionElementFactory objects</param> /// <returns>int - the number of deleted extensions</returns> public int ReplaceExtensions(ExtensionList newList) { int count = 0; // get rid of all of the old ones matching the specs if (newList != null) { foreach (Object ob in newList) { string localName = null; string ns = null; XmlNode node = ob as XmlNode; if (node != null) { localName = node.LocalName; ns = node.NamespaceURI; } else { IExtensionElementFactory ele = ob as IExtensionElementFactory; if (ele != null) { localName = ele.XmlName; ns = ele.XmlNameSpace; } } if (localName != null) { count += DeleteExtensions(localName, ns); } } // now add the new ones foreach (IExtensionElementFactory ob in newList) { this.ExtensionElements.Add(ob); } } return count; } /// <summary> /// all extension elements that match a namespace/localname /// given will be removed and the new one will be inserted /// </summary> /// <param name="localName">the local name to find</param> /// <param name="ns">the namespace to match, if null, ns is ignored</param> /// <param name="obj">the new element to put in</param> public void ReplaceExtension (string localName, string ns, IExtensionElementFactory obj) { DeleteExtensions(localName, ns); this.ExtensionElements.Add(obj); } /// <summary> /// this is the subclassing method for AtomBase derived /// classes to overload what childelements should be created /// needed to create CustomLink type objects, like WebContentLink etc /// </summary> /// <param name="reader">The XmlReader that tells us what we are working with</param> /// <param name="parser">the parser is primarily used for nametable comparisons</param> /// <returns>AtomBase</returns> public virtual AtomBase CreateAtomSubElement(XmlReader reader, AtomFeedParser parser) { if (reader == null) { throw new ArgumentNullException("reader"); } if (parser == null) { throw new ArgumentNullException("parser"); } Object localname = reader.LocalName; if (localname.Equals(parser.Nametable.Id)) { return new AtomId(); } else if (localname.Equals(parser.Nametable.Link)) { return new AtomLink(); } else if (localname.Equals(parser.Nametable.Icon)) { return new AtomIcon(); } else if (localname.Equals(parser.Nametable.Logo)) { return new AtomLogo(); } else if (localname.Equals(parser.Nametable.Author)) { return new AtomPerson(AtomPersonType.Author); } else if (localname.Equals(parser.Nametable.Contributor)) { return new AtomPerson(AtomPersonType.Contributor); } else if (localname.Equals(parser.Nametable.Title)) { return new AtomTextConstruct(AtomTextConstructElementType.Title); } else if (localname.Equals(parser.Nametable.Subtitle)) { return new AtomTextConstruct(AtomTextConstructElementType.Subtitle); } else if (localname.Equals(parser.Nametable.Rights)) { return new AtomTextConstruct(AtomTextConstructElementType.Rights); } else if (localname.Equals(parser.Nametable.Summary)) { return new AtomTextConstruct(AtomTextConstructElementType.Summary); } else if (localname.Equals(parser.Nametable.Generator)) { return new AtomGenerator(); } else if (localname.Equals(parser.Nametable.Category)) { return new AtomCategory(); } throw new NotImplementedException("AtomBase CreateChild should NEVER be called for: " + reader.LocalName); } /// <summary>Saves the object as XML.</summary> /// <param name="stream">stream to save to</param> /// <returns>how many bytes written</returns> public void SaveToXml(Stream stream) { Tracing.Assert(stream != null, "stream should not be null"); if (stream == null) { throw new ArgumentNullException("stream"); } XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); SaveToXml(writer); writer.Flush(); } /// <summary>saves the object as XML</summary> /// <param name="writer">the xmlwriter to save to</param> public void SaveToXml(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } if (IsPersistable()) { WriteElementStart(writer, this.XmlName); SaveXmlAttributes(writer); SaveInnerXml(writer); writer.WriteEndElement(); } this.MarkElementDirty(false); } /// <summary>protected virtual int SaveXmlAttributes(XmlWriter writer)</summary> /// <param name="writer">the XmlWriter to save to</param> protected virtual void SaveXmlAttributes(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } // this will save the base and language attributes, if we have them if (Utilities.IsPersistable(this.uriBase)) { //Lookup the prefix and then write the ISBN attribute. writer.WriteAttributeString("xml", "base", BaseNameTable.NSXml, this.Base.ToString()); } if (Utilities.IsPersistable(this.atomLanguageTag)) { writer.WriteAttributeString("xml", "lang", BaseNameTable.NSXml, this.Language); } ISupportsEtag se = this as ISupportsEtag; if (se != null && se.Etag != null) { writer.WriteAttributeString(BaseNameTable.gDataPrefix, BaseNameTable.XmlEtagAttribute, BaseNameTable.gNamespace, se.Etag); } // first go over all attributes foreach (IExtensionElementFactory ele in this.ExtensionElements) { XmlExtension x = ele as XmlExtension; // what we need to do here is: // go over all the attributes. look at all attributes that are namespace related // if the attribute is another default atomnamespace declaration, change it to some rnd prefix if (x != null) { if (x.Node.NodeType == XmlNodeType.Attribute) { ele.Save(writer); } } } AddOtherNamespaces(writer); // now just the non attributes foreach (IExtensionElementFactory ele in this.ExtensionElements) { XmlExtension x = ele as XmlExtension; if (x != null) { if (x.Node.NodeType == XmlNodeType.Attribute) { // skip the guy continue; } } ele.Save(writer); } } /// <summary>checks if this is a namespace /// decl that we already added</summary> /// <param name="node">XmlNode to check</param> /// <returns>true if this node should be skipped </returns> protected virtual bool SkipNode(XmlNode node) { if (node.NodeType == XmlNodeType.Attribute && (String.Compare(node.Name, "xmlns") == 0) && (String.Compare(node.Value, BaseNameTable.NSAtom) == 0)) return true; return false; } private bool IsAtomDefaultNamespace(XmlWriter writer) { string prefix = writer.LookupPrefix(BaseNameTable.NSAtom); if (prefix == null) { // if it is not defined, we need to make a choice // go over all attributes foreach (IExtensionElementFactory ele in this.ExtensionElements) { XmlExtension x = ele as XmlExtension; // what we need to do here is: // go over all the attributes. look at all attributes that are namespace related // if the attribute is another default atomnamespace declaration, change it to some rnd prefix if (x != null) { if (x.Node.NodeType == XmlNodeType.Attribute && (String.Compare(x.Node.Name, "xmlns") == 0) && (String.Compare(x.Node.Value, BaseNameTable.NSAtom) != 0)) return false; } } return true; } if (prefix.Length > 0) { return false; } return true; } /// <summary>protected WriteElementStart(XmlWriter writer)</summary> /// <param name="writer"> the xmlwriter to use</param> /// <param name="elementName"> the elementToPersist to use</param> protected void WriteElementStart(XmlWriter writer, string elementName) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } if (!IsAtomDefaultNamespace(writer)) { writer.WriteStartElement("atom", elementName, BaseNameTable.NSAtom); } else { writer.WriteStartElement(elementName); } } /// <summary>empty base implementation</summary> /// <param name="writer">the xmlwriter, where we want to add default namespaces to</param> protected virtual void AddOtherNamespaces(XmlWriter writer) { Utilities.EnsureAtomNamespace(writer); } /// <summary>Writes out a LOCAL datetime in ISO 8601 format. /// </summary> /// <param name="writer"> the xmlwriter to use</param> /// <param name="elementName"> the elementToPersist to use</param> /// <param name="dateTime"> the localDateTime to convert and persist</param> protected void WriteLocalDateTimeElement(XmlWriter writer, string elementName, DateTime dateTime) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } Tracing.Assert(elementName != null, "elementName should not be null"); if (elementName == null) { throw new ArgumentNullException("elementName"); } Tracing.Assert(elementName.Length > 0, "elementName should be longer than null"); // only save out if valid if (elementName.Length > 0 && Utilities.IsPersistable(dateTime)) { string strOutput = Utilities.LocalDateTimeInUTC(dateTime); WriteElementStart(writer, elementName); writer.WriteString(strOutput); writer.WriteEndElement(); } } /// <summary>empty base implementation</summary> /// <param name="writer">the xmlwriter to save to</param> protected virtual void SaveInnerXml(XmlWriter writer) { } /// <summary>helper method to encapsulate a string encoding, uses HTML encoding now</summary> /// <param name="writer">the xml writer to write to</param> /// <param name="content">the string to encode</param> static protected void WriteEncodedString(XmlWriter writer, string content) { if (writer == null) { throw new System.ArgumentNullException("writer", "No valid xmlWriter"); } if (Utilities.IsPersistable(content)) { string encoded = Utilities.EncodeString(content); writer.WriteString(encoded); } } /// <summary>helper method to encapsulate a string encoding, uses HTML encoding now</summary> /// <param name="writer">the xml writer to write to</param> /// <param name="content">the string to encode</param> static protected void WriteEncodedString(XmlWriter writer, AtomUri content) { if (writer == null) { throw new System.ArgumentNullException("writer", "No valid xmlWriter"); } if (Utilities.IsPersistable(content)) { string encoded = Utilities.EncodeString(content.ToString()); writer.WriteString(encoded); } } /// <summary>helper method to encapsulate encoding, uses HTML encoding now</summary> /// <param name="writer">the xml writer to write to</param> /// <param name="attributeName">the attribute the write</param> /// <param name="content">the atomUri to encode</param> static protected void WriteEncodedAttributeString(XmlWriter writer, string attributeName, AtomUri content) { if (writer == null) { throw new System.ArgumentNullException("writer", "No valid xmlWriter"); } if (attributeName == null) { throw new System.ArgumentNullException("attributeName", "No valid attributename"); } if (Utilities.IsPersistable(content)) { string encoded = Utilities.EncodeString(content.ToString()); writer.WriteAttributeString(attributeName, encoded); } } /// <summary>helper method to encapsulate encoding, uses HTML encoding now</summary> /// <param name="writer">the xml writer to write to</param> /// <param name="attributeName">the attribute the write</param> /// <param name="content">the string to encode</param> static protected void WriteEncodedAttributeString(XmlWriter writer, string attributeName, string content) { if (writer == null) { throw new ArgumentNullException("writer"); } if (Utilities.IsPersistable(content)) { string encoded = Utilities.EncodeString(content); writer.WriteAttributeString(attributeName, encoded); } } /// <summary>helper method to encapsulate encoding, uses HTML encoding now</summary> /// <param name="writer">the xml writer to write to</param> /// <param name="elementName">the attribute the write</param> /// <param name="content">the string to encode</param> static protected void WriteEncodedElementString(XmlWriter writer, string elementName, string content) { if (writer == null) { throw new ArgumentNullException("writer"); } if (Utilities.IsPersistable(content)) { string encoded = Utilities.EncodeString(content); writer.WriteElementString(elementName, BaseNameTable.NSAtom, encoded); } } /// <summary>helper method to encapsulate encoding, uses HTML encoding now</summary> /// <param name="writer">the xml writer to write to</param> /// <param name="elementName">the attribute the write</param> /// <param name="content">the string to encode</param> static protected void WriteEncodedElementString(XmlWriter writer, string elementName, AtomUri content) { if (writer == null) { throw new ArgumentNullException("writer"); } if (Utilities.IsPersistable(content)) { string encoded = Utilities.EncodeString(content.ToString()); writer.WriteElementString(elementName, BaseNameTable.NSAtom, encoded); } } /// <summary> /// this potential overloaded method gets called when the version information /// of an object is changed. It handles setting the versioninformation on /// all children and the factories. /// </summary> /// <returns></returns> protected virtual void OnVersionInfoChanged() { WalkTree(new ChangeVersion(this)); } /// <summary> /// this gets called out of a notification chain. It sets /// this objects version info and the extension lists. We do not /// use the property accessor to avoid the notification loop /// </summary> /// <param name="obj"></param> internal void SetVersionInfo(IVersionAware obj) { this.versionInfo = new VersionInformation(obj); this.versionInfo.ImprintVersion(this.ExtensionElements); this.versionInfo.ImprintVersion(this.ExtensionFactories); } /// <summary>Method to check whether object should be saved. /// This doesn't check whether the object is dirty; it only /// checks whether the XML content is worth saving. /// </summary> public virtual bool ShouldBePersisted() { if (Utilities.IsPersistable(this.uriBase) || Utilities.IsPersistable(this.atomLanguageTag)) { return true; } if (this.extensionsList != null && this.extensionsList.Count > 0 && this.extensionsList[0] != null) { return true; } return false; } #endregion private VersionInformation versionInfo = new VersionInformation(); /// <summary> /// returns the major protocol version number this element /// is working against. /// </summary> /// <returns></returns> public int ProtocolMajor { get { return this.versionInfo.ProtocolMajor; } set { this.versionInfo.ProtocolMajor = value; OnVersionInfoChanged(); } } /// <summary> /// returns the minor protocol version number this element /// is working against. /// </summary> /// <returns></returns> public int ProtocolMinor { get { return this.versionInfo.ProtocolMinor; } set { this.versionInfo.ProtocolMinor = value; OnVersionInfoChanged(); } } } }
// <copyright file="ComplexTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using NUnit.Framework; namespace MathNet.Numerics.UnitTests.ComplexTests { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// Complex extension methods tests. /// </summary> [TestFixture] public class ComplexExtensionTest { /// <summary> /// Can compute exponential. /// </summary> /// <param name="real">Real part.</param> /// <param name="imag">Imaginary part.</param> /// <param name="expectedReal">Expected real part.</param> /// <param name="expectedImag">Expected imaginary part.</param> [TestCase(0.0, 0.0, 1.0, 0.0)] [TestCase(0.0, 1.0, 0.54030230586813977, 0.8414709848078965)] [TestCase(-1.0, 1.0, 0.19876611034641295, 0.30955987565311222)] [TestCase(-111.1, 111.1, -2.3259065941590448e-49, -5.1181940185795617e-49)] public void CanComputeExponential(double real, double imag, double expectedReal, double expectedImag) { var value = new Complex(real, imag); var expected = new Complex(expectedReal, expectedImag); AssertHelpers.AlmostEqualRelative(expected, value.Exp(), 15); } /// <summary> /// Can compute natural logarithm. /// </summary> /// <param name="real">Real part.</param> /// <param name="imag">Imaginary part.</param> /// <param name="expectedReal">Expected real part.</param> /// <param name="expectedImag">Expected imaginary part.</param> [TestCase(0.0, 0.0, double.NegativeInfinity, 0.0)] [TestCase(0.0, 1.0, 0.0, 1.5707963267948966)] [TestCase(-1.0, 1.0, 0.34657359027997264, 2.3561944901923448)] [TestCase(-111.1, 111.1, 5.0570042869255571, 2.3561944901923448)] [TestCase(111.1, -111.1, 5.0570042869255571, -0.78539816339744828)] public void CanComputeNaturalLogarithm(double real, double imag, double expectedReal, double expectedImag) { var value = new Complex(real, imag); var expected = new Complex(expectedReal, expectedImag); AssertHelpers.AlmostEqualRelative(expected, value.Ln(), 14); } /// <summary> /// Can compute power. /// </summary> [Test] public void CanComputePower() { var a = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); var b = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(9.99998047207974718744e-1, -1.76553541154378695012e-6), a.Power(b), 14); a = new Complex(0.0, 1.19209289550780998537e-7); b = new Complex(0.0, -1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(1.00000018725172576491, 1.90048076369011843105e-6), a.Power(b), 14); a = new Complex(0.0, -1.19209289550780998537e-7); b = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(-2.56488189382693049636e-1, -2.17823120666116144959), a.Power(b), 14); a = new Complex(0.0, 0.5); b = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(2.06287223508090495171, 7.45007062179724087859e-1), a.Power(b), 14); a = new Complex(0.0, -0.5); b = new Complex(0.0, 1.0); AssertHelpers.AlmostEqualRelative(new Complex(3.70040633557002510874, -3.07370876701949232239), a.Power(b), 14); a = new Complex(0.0, 2.0); b = new Complex(0.0, -2.0); AssertHelpers.AlmostEqualRelative(new Complex(4.24532146387429353891, -2.27479427903521192648e1), a.Power(b), 14); a = new Complex(0.0, -8.388608e6); b = new Complex(1.19209289550780998537e-7, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(1.00000190048219620166, -1.87253870018168043834e-7), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(0.0, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(1.0, 0.0), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(1.0, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(0.0, 0.0), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(-1.0, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(double.PositiveInfinity, 0.0), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(-1.0, 1.0); AssertHelpers.AlmostEqualRelative(new Complex(double.PositiveInfinity, double.PositiveInfinity), a.Power(b), 14); a = new Complex(0.0, 0.0); b = new Complex(0.0, 1.0); Assert.That(a.Power(b).IsNaN()); } /// <summary> /// Can compute root. /// </summary> [Test] public void CanComputeRoot() { var a = new Complex(0.0, -1.19209289550780998537e-7); var b = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.038550761943650161, 0.019526430428319544), a.Root(b), 13); a = new Complex(0.0, 0.5); b = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.007927894711475968, -0.042480480425152213), a.Root(b), 13); a = new Complex(0.0, -0.5); b = new Complex(0.0, 1.0); AssertHelpers.AlmostEqualRelative(new Complex(0.15990905692806806, 0.13282699942462053), a.Root(b), 13); a = new Complex(0.0, 2.0); b = new Complex(0.0, -2.0); AssertHelpers.AlmostEqualRelative(new Complex(0.42882900629436788, 0.15487175246424678), a.Root(b), 13); //a = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); //b = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); //AssertHelpers.AlmostEqual(new Complex(0.0, 0.0), a.Root(b), 15); a = new Complex(0.0, -8.388608e6); b = new Complex(1.19209289550780998537e-7, 0.0); AssertHelpers.AlmostEqualRelative(new Complex(double.PositiveInfinity, double.NegativeInfinity), a.Root(b), 14); } /// <summary> /// Can compute square. /// </summary> [Test] public void CanComputeSquare() { var complex = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(0, 2.8421709430403888e-14), complex.Square(), 15); complex = new Complex(0.0, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(-1.4210854715201944e-14, 0.0), complex.Square(), 15); complex = new Complex(0.0, -1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(-1.4210854715201944e-14, 0.0), complex.Square(), 15); complex = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(-0.25, 0.0), complex.Square(), 15); complex = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(-0.25, 0.0), complex.Square(), 15); complex = new Complex(0.0, -8.388608e6); AssertHelpers.AlmostEqualRelative(new Complex(-70368744177664.0, 0.0), complex.Square(), 15); } /// <summary> /// Can compute square root. /// </summary> [Test] public void CanComputeSquareRoot() { var complex = new Complex(1.19209289550780998537e-7, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(0.00037933934912842666, 0.00015712750315077684), complex.SquareRoot(), 14); complex = new Complex(0.0, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(0.00024414062499999973, 0.00024414062499999976), complex.SquareRoot(), 14); complex = new Complex(0.0, -1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative( new Complex(0.00024414062499999973, -0.00024414062499999976), complex.SquareRoot(), 14); complex = new Complex(0.0, 0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.5, 0.5), complex.SquareRoot(), 14); complex = new Complex(0.0, -0.5); AssertHelpers.AlmostEqualRelative(new Complex(0.5, -0.5), complex.SquareRoot(), 14); complex = new Complex(0.0, -8.388608e6); AssertHelpers.AlmostEqualRelative(new Complex(2048.0, -2048.0), complex.SquareRoot(), 14); complex = new Complex(8.388608e6, 1.19209289550780998537e-7); AssertHelpers.AlmostEqualRelative(new Complex(2896.3093757400989, 2.0579515874459933e-11), complex.SquareRoot(), 14); complex = new Complex(0.0, 0.0); AssertHelpers.AlmostEqualRelative(Complex.Zero, complex.SquareRoot(), 14); } /// <summary> /// Can determine if imaginary is unit. /// </summary> [Test] public void CanDetermineIfImaginaryUnit() { var complex = new Complex(0, 1); Assert.IsTrue(complex.IsImaginaryOne(), "Imaginary unit"); } /// <summary> /// Can determine if a complex is infinity. /// </summary> [Test] public void CanDetermineIfInfinity() { var complex = new Complex(double.PositiveInfinity, 1); Assert.IsTrue(complex.IsInfinity(), "Real part is infinity."); complex = new Complex(1, double.NegativeInfinity); Assert.IsTrue(complex.IsInfinity(), "Imaginary part is infinity."); complex = new Complex(double.NegativeInfinity, double.PositiveInfinity); Assert.IsTrue(complex.IsInfinity(), "Both parts are infinity."); } /// <summary> /// Can determine if a complex is not a number. /// </summary> [Test] public void CanDetermineIfNaN() { var complex = new Complex(double.NaN, 1); Assert.IsTrue(complex.IsNaN(), "Real part is NaN."); complex = new Complex(1, double.NaN); Assert.IsTrue(complex.IsNaN(), "Imaginary part is NaN."); complex = new Complex(double.NaN, double.NaN); Assert.IsTrue(complex.IsNaN(), "Both parts are NaN."); } /// <summary> /// Can determine Complex number with a value of one. /// </summary> [Test] public void CanDetermineIfOneValueComplexNumber() { var complex = new Complex(1, 0); Assert.IsTrue(complex.IsOne(), "Complex number with a value of one."); } /// <summary> /// Can determine if a complex is a real non-negative number. /// </summary> [Test] public void CanDetermineIfRealNonNegativeNumber() { var complex = new Complex(1, 0); Assert.IsTrue(complex.IsReal(), "Is a real non-negative number."); } /// <summary> /// Can determine if a complex is a real number. /// </summary> [Test] public void CanDetermineIfRealNumber() { var complex = new Complex(-1, 0); Assert.IsTrue(complex.IsReal(), "Is a real number."); } /// <summary> /// Can determine if a complex is a zero number. /// </summary> [Test] public void CanDetermineIfZeroValueComplexNumber() { var complex = new Complex(0, 0); Assert.IsTrue(complex.IsZero(), "Zero complex number."); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable { internal partial class CSharpIntroduceVariableService { protected override Task<Document> IntroduceLocalAsync( SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, bool isConstant, CancellationToken cancellationToken) { var options = document.Project.Solution.Workspace.Options; var newLocalNameToken = (SyntaxToken)GenerateUniqueLocalName(document, expression, isConstant, cancellationToken); var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken); var modifiers = isConstant ? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword)) : default(SyntaxTokenList); var declarationStatement = SyntaxFactory.LocalDeclarationStatement( modifiers, SyntaxFactory.VariableDeclaration( this.GetTypeSyntax(document, expression, isConstant, options, cancellationToken), SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator( newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()), null, SyntaxFactory.EqualsValueClause(expression.WithoutTrailingTrivia().WithoutLeadingTrivia()))))); var anonymousMethodParameters = GetAnonymousMethodParameters(document, expression, cancellationToken); var lambdas = anonymousMethodParameters.SelectMany(p => p.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).AsEnumerable()) .Where(n => n is ParenthesizedLambdaExpressionSyntax || n is SimpleLambdaExpressionSyntax) .ToSet(); var parentLambda = GetParentLambda(expression, lambdas); if (parentLambda != null) { return Task.FromResult(IntroduceLocalDeclarationIntoLambda( document, expression, newLocalName, declarationStatement, parentLambda, allOccurrences, cancellationToken)); } else { return IntroduceLocalDeclarationIntoBlockAsync( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } } private Document IntroduceLocalDeclarationIntoLambda( SemanticDocument document, ExpressionSyntax expression, IdentifierNameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, SyntaxNode oldLambda, bool allOccurrences, CancellationToken cancellationToken) { var oldBody = oldLambda is ParenthesizedLambdaExpressionSyntax ? (ExpressionSyntax)((ParenthesizedLambdaExpressionSyntax)oldLambda).Body : (ExpressionSyntax)((SimpleLambdaExpressionSyntax)oldLambda).Body; var rewrittenBody = Rewrite( document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken); var delegateType = document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType as INamedTypeSymbol; var newBody = delegateType != null && delegateType.DelegateInvokeMethod != null && delegateType.DelegateInvokeMethod.ReturnsVoid ? SyntaxFactory.Block(declarationStatement) : SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody)); newBody = newBody.WithAdditionalAnnotations(Formatter.Annotation); var newLambda = oldLambda is ParenthesizedLambdaExpressionSyntax ? ((ParenthesizedLambdaExpressionSyntax)oldLambda).WithBody(newBody) : (SyntaxNode)((SimpleLambdaExpressionSyntax)oldLambda).WithBody(newBody); var newRoot = document.Root.ReplaceNode(oldLambda, newLambda); return document.Document.WithSyntaxRoot(newRoot); } private SyntaxNode GetParentLambda(ExpressionSyntax expression, ISet<SyntaxNode> lambdas) { var current = expression; while (current != null) { if (lambdas.Contains(current.Parent)) { return current.Parent; } current = current.Parent as ExpressionSyntax; } return null; } private TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, bool isConstant, OptionSet options, CancellationToken cancellationToken) { var typeSymbol = GetTypeSymbol(document, expression, cancellationToken); if (typeSymbol.ContainsAnonymousType()) { return SyntaxFactory.IdentifierName("var"); } if (!isConstant && options.GetOption(CSharpCodeStyleOptions.UseVarWhenDeclaringLocals) && CanUseVar(typeSymbol)) { return SyntaxFactory.IdentifierName("var"); } return typeSymbol.GenerateTypeSyntax(); } private bool CanUseVar(ITypeSymbol typeSymbol) { return typeSymbol.TypeKind != TypeKind.Delegate && !typeSymbol.IsErrorType(); } private static async Task<Tuple<SemanticDocument, ISet<ExpressionSyntax>>> ComplexifyParentingStatements( SemanticDocument semanticDocument, ISet<ExpressionSyntax> matches, CancellationToken cancellationToken) { // First, track the matches so that we can get back to them later. var newRoot = semanticDocument.Root.TrackNodes(matches); var newDocument = semanticDocument.Document.WithSyntaxRoot(newRoot); var newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); var newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); // Next, expand the topmost parenting expression of each match, being careful // not to expand the matches themselves. var topMostExpressions = newMatches .Select(m => m.AncestorsAndSelf().OfType<ExpressionSyntax>().Last()) .Distinct(); newRoot = await newSemanticDocument.Root .ReplaceNodesAsync( topMostExpressions, computeReplacementAsync: async (oldNode, newNode, ct) => { return await Simplifier .ExpandAsync( oldNode, newSemanticDocument.Document, expandInsideNode: node => { var expression = node as ExpressionSyntax; return expression == null || !newMatches.Contains(expression); }, cancellationToken: ct) .ConfigureAwait(false); }, cancellationToken: cancellationToken) .ConfigureAwait(false); newDocument = newSemanticDocument.Document.WithSyntaxRoot(newRoot); newSemanticDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); newMatches = newSemanticDocument.Root.GetCurrentNodes(matches.AsEnumerable()).ToSet(); return Tuple.Create(newSemanticDocument, newMatches); } private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync( SemanticDocument document, ExpressionSyntax expression, NameSyntax newLocalName, LocalDeclarationStatementSyntax declarationStatement, bool allOccurrences, CancellationToken cancellationToken) { declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation); var oldOutermostBlock = expression.GetAncestorsOrThis<BlockSyntax>().LastOrDefault(); var matches = FindMatches(document, expression, document, oldOutermostBlock, allOccurrences, cancellationToken); Debug.Assert(matches.Contains(expression)); var complexified = await ComplexifyParentingStatements(document, matches, cancellationToken).ConfigureAwait(false); document = complexified.Item1; matches = complexified.Item2; // Our original expression should have been one of the matches, which were tracked as part // of complexification, so we can retrieve the latest version of the expression here. expression = document.Root.GetCurrentNodes(expression).First(); var innermostStatements = new HashSet<StatementSyntax>( matches.Select(expr => expr.GetAncestorOrThis<StatementSyntax>())); if (innermostStatements.Count == 1) { // If there was only one match, or all the matches came from the same // statement, then we want to place the declaration right above that // statement. Note: we special case this because the statement we are going // to go above might not be in a block and we may have to generate it return IntroduceLocalForSingleOccurrenceIntoBlock( document, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken); } var oldInnerMostCommonBlock = matches.FindInnermostCommonBlock(); var allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => expr.GetAncestorsOrThis<StatementSyntax>())); var firstStatementAffectedInBlock = oldInnerMostCommonBlock.Statements.First(allAffectedStatements.Contains); var firstStatementAffectedIndex = oldInnerMostCommonBlock.Statements.IndexOf(firstStatementAffectedInBlock); var newInnerMostBlock = Rewrite( document, expression, newLocalName, document, oldInnerMostCommonBlock, allOccurrences, cancellationToken); var statements = new List<StatementSyntax>(); statements.AddRange(newInnerMostBlock.Statements.Take(firstStatementAffectedIndex)); statements.Add(declarationStatement); statements.AddRange(newInnerMostBlock.Statements.Skip(firstStatementAffectedIndex)); var finalInnerMostBlock = newInnerMostBlock.WithStatements( SyntaxFactory.List<StatementSyntax>(statements)); var newRoot = document.Root.ReplaceNode(oldInnerMostCommonBlock, finalInnerMostBlock); return document.Document.WithSyntaxRoot(newRoot); } private Document IntroduceLocalForSingleOccurrenceIntoBlock( SemanticDocument document, ExpressionSyntax expression, NameSyntax localName, LocalDeclarationStatementSyntax localDeclaration, bool allOccurrences, CancellationToken cancellationToken) { var oldStatement = expression.GetAncestorOrThis<StatementSyntax>(); var newStatement = Rewrite( document, expression, localName, document, oldStatement, allOccurrences, cancellationToken); if (oldStatement.IsParentKind(SyntaxKind.Block)) { var oldBlock = oldStatement.Parent as BlockSyntax; var statementIndex = oldBlock.Statements.IndexOf(oldStatement); var newBlock = oldBlock.WithStatements(CreateNewStatementList( oldBlock.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldBlock, newBlock); return document.Document.WithSyntaxRoot(newRoot); } else if (oldStatement.IsParentKind(SyntaxKind.SwitchSection)) { var oldSwitchSection = oldStatement.Parent as SwitchSectionSyntax; var statementIndex = oldSwitchSection.Statements.IndexOf(oldStatement); var newSwitchSection = oldSwitchSection.WithStatements(CreateNewStatementList( oldSwitchSection.Statements, localDeclaration, newStatement, statementIndex)); var newRoot = document.Root.ReplaceNode(oldSwitchSection, newSwitchSection); return document.Document.WithSyntaxRoot(newRoot); } else { // we need to introduce a block to put the original statement, along with // the statement we're generating var newBlock = SyntaxFactory.Block(localDeclaration, newStatement).WithAdditionalAnnotations(Formatter.Annotation); var newRoot = document.Root.ReplaceNode(oldStatement, newBlock); return document.Document.WithSyntaxRoot(newRoot); } } private static SyntaxList<StatementSyntax> CreateNewStatementList( SyntaxList<StatementSyntax> oldStatements, LocalDeclarationStatementSyntax localDeclaration, StatementSyntax newStatement, int statementIndex) { return oldStatements.Take(statementIndex) .Concat(localDeclaration.WithLeadingTrivia(oldStatements.Skip(statementIndex).First().GetLeadingTrivia())) .Concat(newStatement.WithoutLeadingTrivia()) .Concat(oldStatements.Skip(statementIndex + 1)) .ToSyntaxList(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System { internal static class IriHelper { // // Checks if provided non surrogate char lies in iri range // internal static bool CheckIriUnicodeRange(char unicode, bool isQuery) { return ((unicode >= '\u00A0' && unicode <= '\uD7FF') || (unicode >= '\uF900' && unicode <= '\uFDCF') || (unicode >= '\uFDF0' && unicode <= '\uFFEF') || (isQuery && unicode >= '\uE000' && unicode <= '\uF8FF')); } // // Check if highSurr and lowSurr are a surrogate pair then // it checks if the combined char is in the range // Takes in isQuery because because iri restrictions for query are different // internal static bool CheckIriUnicodeRange(char highSurr, char lowSurr, ref bool surrogatePair, bool isQuery) { bool inRange = false; surrogatePair = false; Debug.Assert(char.IsHighSurrogate(highSurr)); if (char.IsSurrogatePair(highSurr, lowSurr)) { surrogatePair = true; char[] chars = new char[2] { highSurr, lowSurr }; string surrPair = new string(chars); if (((string.CompareOrdinal(surrPair, "\U00010000") >= 0) && (string.CompareOrdinal(surrPair, "\U0001FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00020000") >= 0) && (string.CompareOrdinal(surrPair, "\U0002FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00030000") >= 0) && (string.CompareOrdinal(surrPair, "\U0003FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00040000") >= 0) && (string.CompareOrdinal(surrPair, "\U0004FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00050000") >= 0) && (string.CompareOrdinal(surrPair, "\U0005FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00060000") >= 0) && (string.CompareOrdinal(surrPair, "\U0006FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00070000") >= 0) && (string.CompareOrdinal(surrPair, "\U0007FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00080000") >= 0) && (string.CompareOrdinal(surrPair, "\U0008FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00090000") >= 0) && (string.CompareOrdinal(surrPair, "\U0009FFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000A0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000AFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000B0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000BFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000C0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000CFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000D0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000DFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U000E1000") >= 0) && (string.CompareOrdinal(surrPair, "\U000EFFFD") <= 0)) || (isQuery && (((string.CompareOrdinal(surrPair, "\U000F0000") >= 0) && (string.CompareOrdinal(surrPair, "\U000FFFFD") <= 0)) || ((string.CompareOrdinal(surrPair, "\U00100000") >= 0) && (string.CompareOrdinal(surrPair, "\U0010FFFD") <= 0))))) { inRange = true; } } return inRange; } // // Check reserved chars according to rfc 3987 in a sepecific component // internal static bool CheckIsReserved(char ch, UriComponents component) { if ((component != UriComponents.Scheme) && (component != UriComponents.UserInfo) && (component != UriComponents.Host) && (component != UriComponents.Port) && (component != UriComponents.Path) && (component != UriComponents.Query) && (component != UriComponents.Fragment) ) { return (component == (UriComponents)0) ? Uri.IsGenDelim(ch) : false; } else { switch (component) { // Reserved chars according to rfc 3987 case UriComponents.UserInfo: if (ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@') return true; break; case UriComponents.Host: if (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@') return true; break; case UriComponents.Path: if (ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']') return true; break; case UriComponents.Query: if (ch == '#' || ch == '[' || ch == ']') return true; break; case UriComponents.Fragment: if (ch == '#' || ch == '[' || ch == ']') return true; break; default: break; } return false; } } // // IRI normalization for strings containing characters that are not allowed or // escaped characters that should be unescaped in the context of the specified Uri component. // internal static unsafe string EscapeUnescapeIri(char* pInput, int start, int end, UriComponents component) { char[] dest = new char[end - start]; byte[] bytes = null; // Pin the array to do pointer accesses GCHandle destHandle = GCHandle.Alloc(dest, GCHandleType.Pinned); char* pDest = (char*)destHandle.AddrOfPinnedObject(); const int percentEncodingLen = 3; // Escaped UTF-8 will take 3 chars: %AB. const int bufferCapacityIncrease = 30 * percentEncodingLen; int bufferRemaining = 0; int next = start; int destOffset = 0; char ch; bool escape = false; bool surrogatePair = false; for (; next < end; ++next) { escape = false; surrogatePair = false; if ((ch = pInput[next]) == '%') { if (next + 2 < end) { ch = UriHelper.EscapedAscii(pInput[next + 1], pInput[next + 2]); // Do not unescape a reserved char if (ch == Uri.c_DummyChar || ch == '%' || CheckIsReserved(ch, component) || UriHelper.IsNotSafeForUnescape(ch)) { // keep as is Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next++]; Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next++]; Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; continue; } else if (ch <= '\x7F') { Debug.Assert(ch < 0xFF, "Expecting ASCII character."); Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); //ASCII pDest[destOffset++] = ch; next += 2; continue; } else { // possibly utf8 encoded sequence of unicode // check if safe to unescape according to Iri rules Debug.Assert(ch < 0xFF, "Expecting ASCII character."); int startSeq = next; int byteCount = 1; // lazy initialization of max size, will reuse the array for next sequences if ((object)bytes == null) bytes = new byte[end - next]; bytes[0] = (byte)ch; next += 3; while (next < end) { // Check on exit criterion if ((ch = pInput[next]) != '%' || next + 2 >= end) break; // already made sure we have 3 characters in str ch = UriHelper.EscapedAscii(pInput[next + 1], pInput[next + 2]); //invalid hex sequence ? if (ch == Uri.c_DummyChar) break; // character is not part of a UTF-8 sequence ? else if (ch < '\x80') break; else { //a UTF-8 sequence bytes[byteCount++] = (byte)ch; next += 3; } Debug.Assert(ch < 0xFF, "Expecting ASCII character."); } next--; // for loop will increment // Using encoder with no replacement fall-back will skip all invalid UTF-8 sequences. Encoding noFallbackCharUTF8 = Encoding.GetEncoding( Encoding.UTF8.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback("")); char[] unescapedChars = new char[bytes.Length]; int charCount = noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0); if (charCount != 0) { // If invalid sequences were present in the original escaped string, we need to // copy the escaped versions of those sequences. // Decoded Unicode values will be kept only when they are allowed by the URI/IRI RFC // rules. UriHelper.MatchUTF8Sequence(pDest, dest, ref destOffset, unescapedChars, charCount, bytes, byteCount, component == UriComponents.Query, true); } else { // copy escaped sequence as is for (int i = startSeq; i <= next; ++i) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[i]; } } } } else { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } } else if (ch > '\x7f') { // unicode char ch2; if ((char.IsHighSurrogate(ch)) && (next + 1 < end)) { ch2 = pInput[next + 1]; escape = !CheckIriUnicodeRange(ch, ch2, ref surrogatePair, component == UriComponents.Query); if (!escape) { // copy the two chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next++]; Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } } else { if (CheckIriUnicodeRange(ch, component == UriComponents.Query)) { if (!Uri.IsBidiControlCharacter(ch)) { // copy it Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } } else { // escape it escape = true; } } } else { // just copy the character Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = pInput[next]; } if (escape) { const int maxNumberOfBytesEncoded = 4; if (bufferRemaining < maxNumberOfBytesEncoded * percentEncodingLen) { int newBufferLength = 0; checked { // may need more memory since we didn't anticipate escaping newBufferLength = dest.Length + bufferCapacityIncrease; bufferRemaining += bufferCapacityIncrease; } char[] newDest = new char[newBufferLength]; fixed (char* pNewDest = newDest) { Buffer.MemoryCopy((byte*)pDest, (byte*)pNewDest, newBufferLength, destOffset * sizeof(char)); } if (destHandle.IsAllocated) { destHandle.Free(); } dest = newDest; // re-pin new dest[] array destHandle = GCHandle.Alloc(dest, GCHandleType.Pinned); pDest = (char*)destHandle.AddrOfPinnedObject(); } byte[] encodedBytes = new byte[maxNumberOfBytesEncoded]; fixed (byte* pEncodedBytes = encodedBytes) { int encodedBytesCount = Encoding.UTF8.GetBytes(pInput + next, surrogatePair ? 2 : 1, pEncodedBytes, maxNumberOfBytesEncoded); Debug.Assert(encodedBytesCount <= maxNumberOfBytesEncoded, "UTF8 encoder should not exceed specified byteCount"); bufferRemaining -= encodedBytesCount * percentEncodingLen; for (int count = 0; count < encodedBytesCount; ++count) { UriHelper.EscapeAsciiChar((char)encodedBytes[count], dest, ref destOffset); } } } } if (destHandle.IsAllocated) destHandle.Free(); Debug.Assert(destOffset <= dest.Length, "Destination length met or exceeded destination offset."); return new string(dest, 0, destOffset); } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections; using Spring.Messaging.Ems.Common; using TIBCO.EMS; using Common.Logging; using Spring.Collections; using Spring.Util; using Queue=TIBCO.EMS.Queue; namespace Spring.Messaging.Ems.Connections { /// <summary> /// Wrapper for Session that caches producers and registers itself as available /// to the session cache when being closed. Generally used for testing purposes or /// if need to get at the wrapped Session object via the TargetSession property (for /// vendor specific methods). /// </summary> /// <author>Juergen Hoeller</author> /// <author>Mark Pollack</author> public class CachedSession : IDecoratorSession { #region Logging Definition private static readonly ILog LOG = LogManager.GetLogger(typeof(CachedSession)); #endregion private ISession target; private LinkedList sessionList; private int sessionCacheSize; private IDictionary cachedProducers = new Hashtable(); private IDictionary cachedConsumers = new Hashtable(); private bool shouldCacheProducers; private bool shouldCacheConsumers; private bool transactionOpen = false; private CachingConnectionFactory ccf; /// <summary> /// Initializes a new instance of the <see cref="CachedSession"/> class. /// </summary> /// <param name="targetSession">The target session.</param> /// <param name="sessionList">The session list.</param> /// <param name="ccf">The CachingConnectionFactory.</param> public CachedSession(ISession targetSession, LinkedList sessionList, CachingConnectionFactory ccf) { target = targetSession; this.sessionList = sessionList; this.sessionCacheSize = ccf.SessionCacheSize; shouldCacheProducers = ccf.CacheProducers; shouldCacheConsumers = ccf.CacheConsumers; this.ccf = ccf; } /// <summary> /// Gets the target, for testing purposes. /// </summary> /// <value>The target.</value> public ISession TargetSession { get { return target; } } /// <summary> /// Creates the producer, potentially returning a cached instance. /// </summary> /// <param name="destination">The destination.</param> /// <returns>A message producer.</returns> public IMessageProducer CreateProducer(Destination destination) { if (shouldCacheProducers) { IMessageProducer producer = (IMessageProducer)cachedProducers[destination]; if (producer != null) { #region Logging if (LOG.IsDebugEnabled) { LOG.Debug("Found cached MessageProducer for destination [" + destination + "]"); } #endregion } else { producer = target.CreateProducer(destination); #region Logging if (LOG.IsDebugEnabled) { LOG.Debug("Creating cached MessageProducer for destination [" + destination + "]"); } #endregion cachedProducers.Add(destination, producer); } this.transactionOpen = true; return new CachedMessageProducer(producer); } else { return target.CreateProducer(destination); } } /// <summary> /// If have not yet reached session cache size, cache the session, otherwise /// dispose of all cached message producers and close the session. /// </summary> public void Close() { if (ccf.IsActive) { //don't pass the call to the underlying target. lock (sessionList) { if (sessionList.Count < sessionCacheSize) { LogicalClose(); // Remain open in the session list. return; } } } // If we get here, we're supposed to shut down. PhysicalClose(); } private void LogicalClose() { // Preserve rollback-on-close semantics. if (this.transactionOpen && this.target.Transacted) { this.transactionOpen = false; this.target.Rollback(); } // Physically close durable subscribers at time of Session close call. IList ToRemove = new ArrayList(); foreach (DictionaryEntry dictionaryEntry in cachedConsumers) { ConsumerCacheKey key = (ConsumerCacheKey) dictionaryEntry.Key; if (key.Subscription != null) { ((IMessageConsumer) dictionaryEntry.Value).Close(); ToRemove.Add(key); } } foreach (ConsumerCacheKey key in ToRemove) { cachedConsumers.Remove(key); } // Allow for multiple close calls... if (!sessionList.Contains(this)) { #region Logging if (LOG.IsDebugEnabled) { LOG.Debug("Returning cached Session: " + target); } #endregion sessionList.Add(this); //add to end of linked list. } } private void PhysicalClose() { if (LOG.IsDebugEnabled) { LOG.Debug("Closing cached Session: " + this.target); } // Explicitly close all MessageProducers and MessageConsumers that // this Session happens to cache... try { foreach (DictionaryEntry entry in cachedProducers) { ((IMessageProducer)entry.Value).Close(); } foreach (DictionaryEntry entry in cachedConsumers) { ((IMessageConsumer)entry.Value).Close(); } } finally { // Now actually close the Session. target.Close(); } } /// <summary> /// Creates the consumer, potentially returning a cached instance. /// </summary> /// <param name="destination">The destination.</param> /// <returns>A message consumer</returns> public IMessageConsumer CreateConsumer(Destination destination) { return CreateConsumer(destination, null, false, null); } /// <summary> /// Creates the consumer, potentially returning a cached instance. /// </summary> /// <param name="destination">The destination.</param> /// <param name="selector">The selector.</param> /// <returns>A message consumer</returns> public IMessageConsumer CreateConsumer(Destination destination, string selector) { return CreateConsumer(destination, selector, false, null); } /// <summary> /// Creates the consumer, potentially returning a cached instance. /// </summary> /// <param name="destination">The destination.</param> /// <param name="selector">The selector.</param> /// <param name="noLocal">if set to <c>true</c> [no local].</param> /// <returns>A message consumer.</returns> public IMessageConsumer CreateConsumer(Destination destination, string selector, bool noLocal) { return CreateConsumer(destination, selector, noLocal, null); } /// <summary> /// Creates the durable consumer, potentially returning a cached instance. /// </summary> /// <param name="destination">The destination.</param> /// <param name="subscription">The name of the durable subscription.</param> /// <param name="selector">The selector.</param> /// <param name="noLocal">if set to <c>true</c> [no local].</param> /// <returns>A message consumer</returns> public ITopicSubscriber CreateDurableSubscriber(Topic destination, string subscription, string selector, bool noLocal) { this.transactionOpen = true; if (shouldCacheConsumers) { return (ITopicSubscriber)GetCachedConsumer(destination, selector, noLocal, subscription); } else { return target.CreateDurableSubscriber(destination, subscription, selector, noLocal); } } /// <summary> /// Creates the durable consumer, potentially returning a cached instance. /// </summary> /// <param name="destination">The destination.</param> /// <param name="subscription">The name of the durable subscription.</param> /// <returns>A message consumer</returns> public ITopicSubscriber CreateDurableSubscriber(Topic destination, string subscription) { return CreateDurableSubscriber(destination, subscription, null, false); } /// <summary> /// Creates the consumer. /// </summary> /// <param name="destination">The destination.</param> /// <param name="selector">The selector.</param> /// <param name="noLocal">if set to <c>true</c> [no local].</param> /// <param name="subscription">The subscription.</param> /// <returns></returns> protected IMessageConsumer CreateConsumer(Destination destination, string selector, bool noLocal, string subscription) { this.transactionOpen = true; if (shouldCacheConsumers) { return GetCachedConsumer(destination, selector, noLocal, subscription); } else { return target.CreateConsumer(destination, selector, noLocal); } } private IMessageConsumer GetCachedConsumer(Destination destination, string selector, bool noLocal, string subscription) { object cacheKey = new ConsumerCacheKey(destination, selector, noLocal, null); IMessageConsumer consumer = (IMessageConsumer)cachedConsumers[cacheKey]; if (consumer != null) { if (LOG.IsDebugEnabled) { LOG.Debug("Found cached EMS MessageConsumer for destination [" + destination + "]: " + consumer); } } else { if (destination is Topic) { consumer = (subscription != null ? target.CreateDurableSubscriber((Topic)destination, subscription, selector, noLocal) : target.CreateConsumer(destination, selector, noLocal)); } else { consumer = target.CreateConsumer(destination, selector); } if (LOG.IsDebugEnabled) { LOG.Debug("Creating cached EMS MessageConsumer for destination [" + destination + "]: " + consumer); } cachedConsumers[cacheKey] = consumer; } return new CachedMessageConsumer(consumer); } #region Pass through implementations /// <summary> /// Gets the queue. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public TIBCO.EMS.Queue CreateQueue(string name) { this.transactionOpen = true; return target.CreateQueue(name); } /// <summary> /// Gets the topic. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public Topic CreateTopic(string name) { this.transactionOpen = true; return target.CreateTopic(name); } /// <summary> /// Creates the temporary queue. /// </summary> /// <returns></returns> public TemporaryQueue CreateTemporaryQueue() { this.transactionOpen = true; return target.CreateTemporaryQueue(); } /// <summary> /// Creates the temporary topic. /// </summary> /// <returns></returns> public TemporaryTopic CreateTemporaryTopic() { this.transactionOpen = true; return target.CreateTemporaryTopic(); } /// <summary> /// Creates the message. /// </summary> /// <returns></returns> public Message CreateMessage() { this.transactionOpen = true; return target.CreateMessage(); } /// <summary> /// Creates the text message. /// </summary> /// <returns></returns> public TextMessage CreateTextMessage() { this.transactionOpen = true; return target.CreateTextMessage(); } /// <summary> /// Creates the text message. /// </summary> /// <param name="text">The text.</param> /// <returns></returns> public TextMessage CreateTextMessage(string text) { this.transactionOpen = true; return target.CreateTextMessage(text); } /// <summary> /// Creates the map message. /// </summary> /// <returns></returns> public MapMessage CreateMapMessage() { this.transactionOpen = true; return target.CreateMapMessage(); } /// <summary> /// Creates the bytes message. /// </summary> /// <returns></returns> public BytesMessage CreateBytesMessage() { this.transactionOpen = true; return target.CreateBytesMessage(); } /// <summary> /// Creates the object message. /// </summary> /// <returns></returns> public ObjectMessage CreateObjectMessage() { this.transactionOpen = true; return target.CreateObjectMessage(); } /// <summary> /// Creates the object message. /// </summary> /// <param name="body">The body.</param> /// <returns></returns> public ObjectMessage CreateObjectMessage(object body) { this.transactionOpen = true; return target.CreateObjectMessage(body); } /// <summary> /// Creates the stream message. /// </summary> /// <returns></returns> public StreamMessage CreateStreamMessage() { this.transactionOpen = true; return target.CreateStreamMessage(); } /// <summary> /// Commits this instance. /// </summary> public void Commit() { this.transactionOpen = false; target.Commit(); } /// <summary> /// Rollbacks this instance. /// </summary> public void Rollback() { this.transactionOpen = false; target.Rollback(); } public QueueBrowser CreateBrowser(Queue queue) { this.transactionOpen = true; return target.CreateBrowser(queue); } public QueueBrowser CreateBrowser(Queue queue, string messageSelector) { this.transactionOpen = true; return target.CreateBrowser(queue, messageSelector); } public void Recover() { this.transactionOpen = true; target.Recover(); } public void Run() { this.transactionOpen = true; target.Run(); } public void Unsubscribe(string name) { this.transactionOpen = true; target.Unsubscribe(name); } /// <summary> /// Gets a value indicating whether this <see cref="CachedSession"/> is transacted. /// </summary> /// <value><c>true</c> if transacted; otherwise, <c>false</c>.</value> public bool Transacted { get { this.transactionOpen = true; return target.Transacted; } } /// <summary> /// Gets the acknowledgement mode. /// </summary> /// <value>The acknowledgement mode.</value> public SessionMode SessionAcknowledgeMode { get { this.transactionOpen = true; return target.SessionAcknowledgeMode; } } public long SessID { get { this.transactionOpen = true; return target.SessID; } } public Session NativeSession { get { this.transactionOpen = true; return target.NativeSession; } } public int AcknowledgeMode { get { this.transactionOpen = true; return target.AcknowledgeMode; } } public Connection Connection { get { this.transactionOpen = true; return target.Connection; } } public bool IsClosed { get { this.transactionOpen = true; return target.IsClosed; } } public bool IsTransacted { get { this.transactionOpen = true; return target.IsTransacted; } } public IMessageListener MessageListener { get { this.transactionOpen = true; return target.MessageListener; } set { this.transactionOpen = true; target.MessageListener = value; } } #endregion /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return "Cached EMS Session: " + this.target; } } internal class ConsumerCacheKey { private Destination destination; private string selector; private bool noLocal; private string subscription; public ConsumerCacheKey(Destination destination, string selector, bool noLocal, string subscription) { this.destination = destination; this.selector = selector; this.noLocal = noLocal; this.subscription = subscription; } public string Subscription { get { return subscription; } } protected bool Equals(ConsumerCacheKey consumerCacheKey) { if (consumerCacheKey == null) return false; if (!Equals(destination, consumerCacheKey.destination)) return false; if (!ObjectUtils.NullSafeEquals(selector, consumerCacheKey.selector)) return false; if (!Equals(noLocal, consumerCacheKey.noLocal)) return false; if (!ObjectUtils.NullSafeEquals(subscription, consumerCacheKey.subscription)) return false; return true; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; return Equals(obj as ConsumerCacheKey); } public override int GetHashCode() { return destination.GetHashCode(); } } }
#region Description /* # A Pool manager for Unity3D Author: Karakonstantioglou Spiros, "SaturnTheIcy" (kronos.ice.dev@gmail.com) This is a simple GameObjects pool manager for [Unity3D](http://www.unity3d.com/), it's only spawn, despawn GameObjects and create or delete pool. Usage : - First you must create your pool with PoolCreator with parametre your prefab(GameObject) and optional parameter a size(int). The pool is automaticly prepare for you 2 copy of the GameObject if you don't provide size(int). PoolManager.PoolCreator(prefab); or PoolManager.PoolCreator(prefab, 10); - To take a prefab(GameObject) from the pool use Spawn with parameter your prefab(GameObject) and optionals parameter are position(Vector3) and rotation(Quaternion). PoolManager.Spawn(prefab); or PoolManager.Spawn(prefab, Vector3.one); or PoolManager.Spawn(prefab, Vector3.one, Quaternion.identity); - To return a obj(GameObject) to the pool use Despawn with parametre your object(GameObject) PoolManager.Despawn(obj); - To delete your pool and all GameObject inside the pool use DisposePool with parameter your prefab(GameObject). PoolManager.DisposePool(prefab); */ #region TODO #endregion TODO #region IDEAS // * Check if move the lock the pool to the wrapper is better solution // * Add Spawn Despawn with timer? and able to stop it. #endregion IDEAS #endregion Description using System; using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; public static class PoolManager { private const int POOL_SIZE = 2; // Our pool keeper we use Dictionary with key GameObject // for easier search and value the pool that GameObject // represent static private Dictionary<GameObject,Pool> pools; /// <summary> /// Return a GameObject from the pool. /// If Pool not exist is create one. /// </summary> /// <param name="obj">GameObject</param> /// <param name="position">Default Vector3.zero</param> /// <param name="rotation">Default Quaternion.identity</param> /// <returns></returns> static public GameObject Spawn(GameObject obj, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion)) { if(obj == null) throw new ArgumentNullException("Spawn GameObject"); CreatePool(obj); // not sure if is correct ways to do return pools[obj].Spawn(position, rotation); } /// <summary> /// Store the GameObject to pool, if pool of the /// same obj exist else destroy the GameObject. /// </summary> /// <param name="obj"></param> static public void Despawn(GameObject obj) { if(obj == null) throw new ArgumentNullException("Despawn GameObject"); // Get from the PoolObject componet the prefab GameObject compPrefab = obj.GetComponent<PoolObject>().prefab; if(compPrefab == null) { // If we don't have a pool of this GameObject, destoyed GameObject.Destroy(obj); return; } pools[compPrefab].Despawn(obj); } /// <summary> /// Destroy the pool of this GameObject /// </summary> /// <param name="obj"></param> static public void DisposePool(GameObject obj) { if(obj == null) throw new ArgumentNullException("DisposePool GameObject"); // Delete all GameObjects pools[obj].DisposeAll(obj); // Remove the pool pools.Remove(obj); } /// <summary> /// Create pool base on this GameObject with size /// </summary> /// <param name="prefab"></param> /// <param name="size"></param> static public void CreatePool(GameObject prefab, int size = POOL_SIZE, ePoolType type = default(ePoolType)) { if(prefab == null) throw new ArgumentNullException("GameObject"); if(pools == null) { // Create dictionary of our pools pools = new Dictionary<GameObject, Pool>(); } if(pools.ContainsKey(prefab) == false) { // Add entry to dictionary with key the GameObject prefab // and create new pool for that GameObject with size and // type of pool pools.Add(prefab, new Pool(prefab, size, type)); } } #region Internal Objects private class Pool { // If the pool is ready to be disposed aka empty of all GameObjects. private bool isDisposed; // The GameObject to clone. private GameObject prefab; // The parent object for easier hierachy manage. private Transform poolParent; private ePoolType type; // A "list" like store used to keep none active GameObject. We use Interface for versatility. private IObjectStore<GameObject> thePool { get; set; } // Total cloned of objects this pool manage, we do not know if some of // the objects are already destroyed manualy and we dont care. Used for // names only. private int size; // Current size of the pool public int Count { get { return thePool.Count; } } // Pool constructor public Pool(GameObject prefab, int capacity = POOL_SIZE, ePoolType type = default(ePoolType)) { if(capacity <= 0) throw new ArgumentOutOfRangeException("size", capacity, "Argument 'size' must be greater than zero."); if(prefab == null) throw new ArgumentNullException("GameObject prefab"); this.prefab = prefab; this.size = 0; isDisposed = false; this.type = type; // Create new obj to add all our GameObjects // result, a better Hierarchy control. poolParent = new GameObject().transform; poolParent.name = "pool_" + prefab.name; thePool = CreateItemPool<GameObject>(capacity); PopulatePool(capacity); } /// <summary> /// Get a GameObject from the pool or /// generate new one if empty /// </summary> /// <param name="position"></param> /// <param name="rotation"></param> /// <returns>GameObject</returns> public GameObject Spawn(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion)) { GameObject obj; if(thePool.Count <= 0) { // Create new clone of prefab GameObject obj = CreateObjectClone(prefab); } else { // Get the GameObject from our pool // locked the pool so no other request happen simutanusly lock(thePool) { obj = thePool.Acquire(); } } // set position and rotation obj.transform.position = position; obj.transform.rotation = rotation; // Enable the GameObject to call the OnEnable() obj.SetActive(true); return obj; } /// <summary> /// Disable and store the GameObject /// </summary> /// <param name="obj">GameObject</param> public void Despawn(GameObject obj) { obj.SetActive(false); // locked the pool so no other request happen simutanusly lock(thePool) { thePool.Store(obj); } } /// <summary> /// Remove all GameObjects from the pool /// and destroy them. /// </summary> /// <param name="obj">GameObject</param> public void DisposeAll(GameObject obj) { if(isDisposed == true) { return; } if(obj != null) { // locked the pool so no other request happen simutanusly lock(thePool) { GameObject disposable; while(thePool.Count > 0) { disposable = thePool.Acquire(); Object.Destroy(disposable); } } isDisposed = true; } } /// <summary> /// Generate GameObjects and store them /// </summary> /// <param name="capacity"></param> private void PopulatePool(int capacity = POOL_SIZE) { GameObject obj; for(int i = 0; i < capacity; i++) { obj = CreateObjectClone(prefab); Despawn(obj); } } /// <summary> /// Generate one GameObject /// </summary> /// <param name="prefab"></param> /// <returns>GameObject</returns> private GameObject CreateObjectClone(GameObject prefab) { GameObject clone; // Generate clone of the prefab clone = (GameObject)GameObject.Instantiate(prefab); // And set paret GameObject for easy manage on hierachy clone.transform.SetParent(poolParent); // Change the name clone.name = prefab.name + "_" + size; // Add our custome componets clone.AddComponent<PoolObject>().prefab = prefab; size++; return clone; } /// <summary> /// Create new pool /// </summary> /// <typeparam name="T"></typeparam> /// <param name="capacity"></param> /// <returns></returns> private IObjectStore<T> CreateItemPool<T>(int capacity) { if(this.type == ePoolType.Queue) return new QueuePool<T>(capacity); return new StackPool<T>(capacity); } } //End class pool #region Unity Component private class PoolObject : MonoBehaviour { // We do not want to expose the pool it self // so we use the prefab public GameObject prefab; } #endregion #region Collection Wrappers interface IObjectStore<T> { T Acquire(); void Store(T item); int Count { get; } } //Wrapp C# Stack generic class class StackPool<T> : Stack<T>, IObjectStore<T> { public StackPool(int capacity) : base(capacity) { } /// <summary> /// Get the first item on pool and returned /// </summary> /// <returns>GameObject</returns> public T Acquire() { return Pop(); } /// <summary> /// Store the object on stack /// </summary> /// <param name="obj"></param> public void Store(T obj) { Push(obj); } } //Wrapp C# Queue generic class class QueuePool<T> : Queue<T>, IObjectStore<T> { public QueuePool(int capacity) : base(capacity) { } /// <summary> /// Get the first item on pool and returned /// </summary> /// <returns>GameObject</returns> public T Acquire() { return Dequeue(); } /// <summary> /// Store the object on stack /// </summary> /// <param name="obj"></param> public void Store(T item) { Enqueue(item); } } #endregion Collection Wrappers #endregion Internal Objects } #region enumarator public enum ePoolType { Stack = 0, Queue = 1 } #endregion enumarator
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A bar or pub. /// </summary> public class BarOrPub_Core : TypeCore, IFoodEstablishment { public BarOrPub_Core() { this._TypeId = 33; this._Id = "BarOrPub"; this._Schema_Org_Url = "http://schema.org/BarOrPub"; string label = ""; GetLabel(out label, "BarOrPub", typeof(BarOrPub_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,106}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{106}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167,1,139,205}; } /// <summary> /// Either <code>Yes/No</code>, or a URL at which reservations can be made. /// </summary> private AcceptsReservations_Core acceptsReservations; public AcceptsReservations_Core AcceptsReservations { get { return acceptsReservations; } set { acceptsReservations = value; SetPropertyInstance(acceptsReservations); } } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// Either the actual menu or a URL of the menu. /// </summary> private Menu_Core menu; public Menu_Core Menu { get { return menu; } set { menu = value; SetPropertyInstance(menu); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The cuisine of the restaurant. /// </summary> private ServesCuisine_Core servesCuisine; public ServesCuisine_Core ServesCuisine { get { return servesCuisine; } set { servesCuisine = value; SetPropertyInstance(servesCuisine); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** ** Purpose: List for exceptions. ** ** ===========================================================*/ using System.Diagnostics.Contracts; namespace System.Collections { /// This is a simple implementation of IDictionary using a singly linked list. This /// will be smaller and faster than a Hashtable if the number of elements is 10 or less. /// This should not be used if performance is important for large numbers of elements. [Serializable] internal class ListDictionaryInternal: IDictionary { DictionaryNode head; int version; int count; [NonSerialized] private Object _syncRoot; public ListDictionaryInternal() { } public Object this[Object key] { get { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); DictionaryNode node = head; while (node != null) { if ( node.key.Equals(key) ) { return node.value; } node = node.next; } return null; } set { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); #if FEATURE_SERIALIZATION if (!key.GetType().IsSerializable) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key"); if( (value != null) && (!value.GetType().IsSerializable ) ) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value"); #endif version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if( node.key.Equals(key) ) { break; } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } } public int Count { get { return count; } } public ICollection Keys { get { return new NodeKeyValueCollection(this, true); } } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return false; } } public bool IsSynchronized { get { return false; } } public Object SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } public ICollection Values { get { return new NodeKeyValueCollection(this, false); } } public void Add(Object key, Object value) { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); #if FEATURE_SERIALIZATION if (!key.GetType().IsSerializable) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key" ); if( (value != null) && (!value.GetType().IsSerializable) ) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value"); #endif version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", node.key, key)); } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } public void Clear() { count = 0; head = null; version++; } public bool Contains(Object key) { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { if (node.key.Equals(key)) { return true; } } return false; } public void CopyTo(Array array, int index) { if (array==null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( array.Length - index < this.Count ) throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), "index"); Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(this); } public void Remove(Object key) { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { break; } last = node; } if (node == null) { return; } if (node == head) { head = node.next; } else { last.next = node.next; } count--; } private class NodeEnumerator : IDictionaryEnumerator { ListDictionaryInternal list; DictionaryNode current; int version; bool start; public NodeEnumerator(ListDictionaryInternal list) { this.list = list; version = list.version; start = true; current = null; } public Object Current { get { return Entry; } } public DictionaryEntry Entry { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return new DictionaryEntry(current.key, current.value); } } public Object Key { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return current.key; } } public Object Value { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } if (start) { current = list.head; start = false; } else { if( current != null ) { current = current.next; } } return (current != null); } public void Reset() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } start = true; current = null; } } private class NodeKeyValueCollection : ICollection { ListDictionaryInternal list; bool isKeys; public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; } void ICollection.CopyTo(Array array, int index) { if (array==null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (array.Length - index < list.Count) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Index"), "index"); for (DictionaryNode node = list.head; node != null; node = node.next) { array.SetValue(isKeys ? node.key : node.value, index); index++; } } int ICollection.Count { get { int count = 0; for (DictionaryNode node = list.head; node != null; node = node.next) { count++; } return count; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return list.SyncRoot; } } IEnumerator IEnumerable.GetEnumerator() { return new NodeKeyValueEnumerator(list, isKeys); } private class NodeKeyValueEnumerator: IEnumerator { ListDictionaryInternal list; DictionaryNode current; int version; bool isKeys; bool start; public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; this.version = list.version; this.start = true; this.current = null; } public Object Current { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return isKeys ? current.key : current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } if (start) { current = list.head; start = false; } else { if( current != null) { current = current.next; } } return (current != null); } public void Reset() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } start = true; current = null; } } } [Serializable] private class DictionaryNode { public Object key; public Object value; public DictionaryNode next; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDateTimeRfc1123 { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class Datetimerfc1123Extensions { /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetNull(this IDatetimerfc1123 operations) { return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetNullAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetInvalid(this IDatetimerfc1123 operations) { return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetInvalidAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetOverflow(this IDatetimerfc1123 operations) { return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetOverflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetOverflowAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetUnderflow(this IDatetimerfc1123 operations) { return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUnderflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetUnderflowAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMaxDateTime(this IDatetimerfc1123 operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutUtcMaxDateTimeAsync( this IDatetimerfc1123 operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max datetime value fri, 31 dec 9999 23:59:59 gmt /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetUtcLowercaseMaxDateTime(this IDatetimerfc1123 operations) { return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value fri, 31 dec 9999 23:59:59 gmt /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetUtcLowercaseMaxDateTimeAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetUtcUppercaseMaxDateTime(this IDatetimerfc1123 operations) { return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetUtcUppercaseMaxDateTimeAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMinDateTime(this IDatetimerfc1123 operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetimerfc1123)s).PutUtcMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutUtcMinDateTimeAsync( this IDatetimerfc1123 operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetUtcMinDateTime(this IDatetimerfc1123 operations) { return Task.Factory.StartNew(s => ((IDatetimerfc1123)s).GetUtcMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetUtcMinDateTimeAsync( this IDatetimerfc1123 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
/* * Copyright (c) 2012 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJson; // // public class MiniJsonTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public static class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) { return null; } return Parser.Parse(json); } sealed class Parser : IDisposable { const string WHITE_SPACE = " \t\n\r"; const string WORD_BREAK = " \t\n\r{}[],:\""; enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; StringReader json; Parser(string jsonString) { json = new StringReader(jsonString); } public static object Parse(string jsonString) { using (var instance = new Parser(jsonString)) { return instance.ParseValue(); } } public void Dispose() { json.Dispose(); json = null; } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); // ditch opening brace json.Read(); // { while (true) { switch (NextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : if (NextToken != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table[name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); // ditch opening bracket json.Read(); // [ var parsing = true; while (parsing) { TOKEN nextToken = NextToken; switch (nextToken) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.SQUARED_CLOSE: parsing = false; break; default: object value = ParseByToken(nextToken); array.Add(value); break; } } return array; } object ParseValue() { TOKEN nextToken = NextToken; return ParseByToken(nextToken); } object ParseByToken(TOKEN token) { switch (token) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool parsing = true; while (parsing) { if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': parsing = false; break; case '\\': if (json.Peek() == -1) { parsing = false; break; } c = NextChar; switch (c) { case '"': case '\\': case '/': s.Append(c); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': var hex = new StringBuilder(); for (int i=0; i< 4; i++) { hex.Append(NextChar); } s.Append((char) Convert.ToInt32(hex.ToString(), 16)); break; } break; default: s.Append(c); break; } } return s.ToString(); } object ParseNumber() { string number = NextWord; if (number.IndexOf('.') == -1) { long parsedInt; Int64.TryParse(number, out parsedInt); return parsedInt; } double parsedDouble; Double.TryParse(number, out parsedDouble); return parsedDouble; } void EatWhitespace() { while (WHITE_SPACE.IndexOf(PeekChar) != -1) { json.Read(); if (json.Peek() == -1) { break; } } } char PeekChar { get { return Convert.ToChar(json.Peek()); } } char NextChar { get { return Convert.ToChar(json.Read()); } } string NextWord { get { StringBuilder word = new StringBuilder(); while (WORD_BREAK.IndexOf(PeekChar) == -1) { word.Append(NextChar); if (json.Peek() == -1) { break; } } return word.ToString(); } } TOKEN NextToken { get { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } char c = PeekChar; switch (c) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } string word = NextWord; switch (word) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { return Serializer.Serialize(obj); } sealed class Serializer { StringBuilder builder; Serializer() { builder = new StringBuilder(); } public static string Serialize(object obj) { var instance = new Serializer(); instance.SerializeValue(obj); return instance.builder.ToString(); } void SerializeValue(object value) { IList asList; IDictionary asDict; string asStr; if (value == null) { builder.Append("null"); } else if ((asStr = value as string) != null) { SerializeString(asStr); } else if (value is bool) { builder.Append(value.ToString().ToLower()); } else if ((asList = value as IList) != null) { SerializeArray(asList); } else if ((asDict = value as IDictionary) != null) { SerializeObject(asDict); } else if (value is char) { SerializeString(value.ToString()); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { switch (c) { case '"': builder.Append("\\\""); break; case '\\': builder.Append("\\\\"); break; case '\b': builder.Append("\\b"); break; case '\f': builder.Append("\\f"); break; case '\n': builder.Append("\\n"); break; case '\r': builder.Append("\\r"); break; case '\t': builder.Append("\\t"); break; default: int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } break; } } builder.Append('\"'); } void SerializeOther(object value) { if (value is float || value is int || value is uint || value is long || value is double || value is sbyte || value is byte || value is short || value is ushort || value is ulong || value is decimal) { builder.Append(value.ToString()); } else { SerializeString(value.ToString()); } } } } #region Extension methods public static class MiniJsonExtensions { public static string toJson( this Dictionary<string,object> obj ) { return Json.Serialize( obj ); } public static List<object> listFromJson( this string json ) { return (List<object>) Json.Deserialize( json ); } public static Dictionary<string,object> dictionaryFromJson( this string json ) { return (Dictionary<string,object>) Json.Deserialize( json ); } } #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.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; #pragma warning disable CA1823 // analyzer incorrectly flags fixed buffer length const (https://github.com/dotnet/roslyn-analyzers/issues/2724) internal static partial class Interop { internal static partial class Process { private const ulong SecondsToNanoseconds = 1000000000; // Constants from sys/syslimits.h private const int PATH_MAX = 1024; // Constants from sys/user.h private const int TDNAMLEN = 16; private const int WMESGLEN = 8; private const int LOGNAMELEN = 17; private const int LOCKNAMELEN = 8; private const int COMMLEN = 19; private const int KI_EMULNAMELEN = 16; private const int LOGINCLASSLEN = 17; private const int KI_NGROUPS = 16; private const int KI_NSPARE_INT = 4; private const int KI_NSPARE_LONG = 12; private const int KI_NSPARE_PTR = 6; // Constants from sys/_sigset.h private const int _SIG_WORDS = 4; // Constants from sys/sysctl.h private const int CTL_KERN = 1; private const int KERN_PROC = 14; private const int KERN_PROC_PATHNAME = 12; private const int KERN_PROC_PROC = 8; private const int KERN_PROC_ALL = 0; private const int KERN_PROC_PID = 1; private const int KERN_PROC_INC_THREAD = 16; // Constants from proc_info.h private const int MAXTHREADNAMESIZE = 64; private const int PROC_PIDTASKALLINFO = 2; private const int PROC_PIDTHREADINFO = 5; private const int PROC_PIDLISTTHREADS = 6; private const int PROC_PIDPATHINFO_MAXSIZE = 4 * PATH_MAX; internal struct proc_stats { internal long startTime; /* time_t */ internal int nice; internal ulong userTime; /* in ticks */ internal ulong systemTime; /* in ticks */ } // From sys/_sigset.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct sigset_t { private fixed int bits[4]; } [StructLayout(LayoutKind.Sequential)] internal struct uid_t { public uint id; } [StructLayout(LayoutKind.Sequential)] internal struct gid_t { public uint id; } [StructLayout(LayoutKind.Sequential)] public struct timeval { public IntPtr tv_sec; public IntPtr tv_usec; } [StructLayout(LayoutKind.Sequential)] private struct vnode { public long tv_sec; public long tv_usec; } // sys/resource.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct rusage { public timeval ru_utime; /* user time used */ public timeval ru_stime; /* system time used */ public long ru_maxrss; /* max resident set size */ private long ru_ixrss; /* integral shared memory size */ private long ru_idrss; /* integral unshared data " */ private long ru_isrss; /* integral unshared stack " */ private long ru_minflt; /* page reclaims */ private long ru_majflt; /* page faults */ private long ru_nswap; /* swaps */ private long ru_inblock; /* block input operations */ private long ru_oublock; /* block output operations */ private long ru_msgsnd; /* messages sent */ private long ru_msgrcv; /* messages received */ private long ru_nsignals; /* signals received */ private long ru_nvcsw; /* voluntary context switches */ private long ru_nivcsw; /* involuntary " */ } // From sys/user.h [StructLayout(LayoutKind.Sequential)] public unsafe struct kinfo_proc { public int ki_structsize; /* size of this structure */ private int ki_layout; /* reserved: layout identifier */ private void* ki_args; /* address of command arguments */ private void* ki_paddr; /* address of proc */ private void* ki_addr; /* kernel virtual addr of u-area */ private vnode* ki_tracep; /* pointer to trace file */ private vnode* ki_textvp; /* pointer to executable file */ private void* ki_fd; /* pointer to open file info */ private void* ki_vmspace; /* pointer to kernel vmspace struct */ private void* ki_wchan; /* sleep address */ public int ki_pid; /* Process identifier */ public int ki_ppid; /* parent process id */ private int ki_pgid; /* process group id */ private int ki_tpgid; /* tty process group id */ public int ki_sid; /* Process session ID */ public int ki_tsid; /* Terminal session ID */ private short ki_jobc; /* job control counter */ private short ki_spare_short1; /* unused (just here for alignment) */ private int ki_tdev; /* controlling tty dev */ private sigset_t ki_siglist; /* Signals arrived but not delivered */ private sigset_t ki_sigmask; /* Current signal mask */ private sigset_t ki_sigignore; /* Signals being ignored */ private sigset_t ki_sigcatch; /* Signals being caught by user */ public uid_t ki_uid; /* effective user id */ private uid_t ki_ruid; /* Real user id */ private uid_t ki_svuid; /* Saved effective user id */ private gid_t ki_rgid; /* Real group id */ private gid_t ki_svgid; /* Saved effective group id */ private short ki_ngroups; /* number of groups */ private short ki_spare_short2; /* unused (just here for alignment) */ private fixed uint ki_groups[KI_NGROUPS]; /* groups */ public ulong ki_size; /* virtual size */ public long ki_rssize; /* current resident set size in pages */ private long ki_swrss; /* resident set size before last swap */ private long ki_tsize; /* text size (pages) XXX */ private long ki_dsize; /* data size (pages) XXX */ private long ki_ssize; /* stack size (pages) */ private ushort ki_xstat; /* Exit status for wait & stop signal */ private ushort ki_acflag; /* Accounting flags */ private uint ki_pctcpu; /* %cpu for process during ki_swtime */ private uint ki_estcpu; /* Time averaged value of ki_cpticks */ private uint ki_slptime; /* Time since last blocked */ private uint ki_swtime; /* Time swapped in or out */ private uint ki_cow; /* number of copy-on-write faults */ private ulong ki_runtime; /* Real time in microsec */ public timeval ki_start; /* starting time */ private timeval ki_childtime; /* time used by process children */ private long ki_flag; /* P_* flags */ private long ki_kiflag; /* KI_* flags (below) */ private int ki_traceflag; /* Kernel trace points */ private byte ki_stat; /* S* process status */ public byte ki_nice; /* Process "nice" value */ private byte ki_lock; /* Process lock (prevent swap) count */ private byte ki_rqindex; /* Run queue index */ private byte ki_oncpu_old; /* Which cpu we are on (legacy) */ private byte ki_lastcpu_old; /* Last cpu we were on (legacy) */ public fixed byte ki_tdname[TDNAMLEN+1]; /* thread name */ private fixed byte ki_wmesg[WMESGLEN+1]; /* wchan message */ private fixed byte ki_login[LOGNAMELEN+1]; /* setlogin name */ private fixed byte ki_lockname[LOCKNAMELEN+1]; /* lock name */ public fixed byte ki_comm[COMMLEN+1]; /* command name */ private fixed byte ki_emul[KI_EMULNAMELEN+1]; /* emulation name */ private fixed byte ki_loginclass[LOGINCLASSLEN+1]; /* login class */ private fixed byte ki_sparestrings[50]; /* spare string space */ private fixed int ki_spareints[KI_NSPARE_INT]; /* spare room for growth */ private int ki_oncpu; /* Which cpu we are on */ private int ki_lastcpu; /* Last cpu we were on */ private int ki_tracer; /* Pid of tracing process */ private int ki_flag2; /* P2_* flags */ private int ki_fibnum; /* Default FIB number */ private uint ki_cr_flags; /* Credential flags */ private int ki_jid; /* Process jail ID */ public int ki_numthreads; /* XXXKSE number of threads in total */ public int ki_tid; /* XXXKSE thread id */ private fixed byte ki_pri[4]; /* process priority */ public rusage ki_rusage; /* process rusage statistics */ /* XXX - most fields in ki_rusage_ch are not (yet) filled in */ private rusage ki_rusage_ch; /* rusage of children processes */ private void* ki_pcb; /* kernel virtual addr of pcb */ private void* ki_kstack; /* kernel virtual addr of stack */ private void* ki_udata; /* User convenience pointer */ public void* ki_tdaddr; /* address of thread */ private fixed long ki_spareptrs[KI_NSPARE_PTR]; /* spare room for growth */ private fixed long ki_sparelongs[KI_NSPARE_LONG]; /* spare room for growth */ private long ki_sflag; /* PS_* flags */ private long ki_tdflags; /* XXXKSE kthread flag */ } /// <summary> /// Queries the OS for the list of all running processes and returns the PID for each /// </summary> /// <returns>Returns a list of PIDs corresponding to all running processes</returns> internal static unsafe int[] ListAllPids() { int numProcesses = 0; int[] pids; kinfo_proc * entries = null; int idx; try { entries = GetProcInfo(0, false, out numProcesses); if (entries == null || numProcesses <= 0) { throw new Win32Exception(SR.CantGetAllPids); } var list = new ReadOnlySpan<kinfo_proc>(entries, numProcesses); pids = new int[numProcesses]; idx = 0; // walk through process list and skip kernel threads for (int i = 0; i < list.Length; i++) { if (list[i].ki_ppid == 0) { // skip kernel threads numProcesses-=1; } else { pids[idx] = list[i].ki_pid; idx += 1; } } // Remove extra elements Array.Resize<int>(ref pids, numProcesses); } finally { Marshal.FreeHGlobal((IntPtr)entries); } return pids; } /// <summary> /// Gets executable name for process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> public static unsafe string GetProcPath(int pid) { Span<int> sysctlName = stackalloc int[4]; byte* pBuffer = null; int bytesLength = 0; sysctlName[0] = CTL_KERN; sysctlName[1] = KERN_PROC; sysctlName[2] = KERN_PROC_PATHNAME; sysctlName[3] = pid; int ret = Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength); if (ret != 0 ) { return null; } return System.Text.Encoding.UTF8.GetString(pBuffer, (int)bytesLength-1); } /// <summary> /// Gets information about process or thread(s) /// </summary> /// <param name="pid">The PID of the process. If PID is 0, this will return all processes</param> public static unsafe kinfo_proc* GetProcInfo(int pid, bool threads, out int count) { Span<int> sysctlName = stackalloc int[4]; int bytesLength = 0; byte* pBuffer = null; kinfo_proc* kinfo = null; int ret; count = -1; if (pid == 0) { // get all processes sysctlName[3] = 0; sysctlName[2] = KERN_PROC_PROC; } else { // get specific process, possibly with threads sysctlName[3] = pid; sysctlName[2] = KERN_PROC_PID | (threads ? KERN_PROC_INC_THREAD : 0); } sysctlName[1] = KERN_PROC; sysctlName[0] = CTL_KERN; try { ret = Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength); if (ret != 0 ) { throw new ArgumentOutOfRangeException(nameof(pid)); } kinfo = (kinfo_proc*)pBuffer; if (kinfo->ki_structsize != sizeof(kinfo_proc)) { // failed consistency check throw new ArgumentOutOfRangeException(nameof(pid)); } count = (int)bytesLength / sizeof(kinfo_proc); } catch { Marshal.FreeHGlobal((IntPtr)pBuffer); throw; } return kinfo; } /// <summary> /// Gets the process information for a given process /// </summary> /// <param name="pid">The PID (process ID) of the process</param> /// <returns> /// Returns a valid ProcessInfo struct for valid processes that the caller /// has permission to access; otherwise, returns null /// </returns> public static unsafe ProcessInfo GetProcessInfoById(int pid) { kinfo_proc* kinfo = null; int count; ProcessInfo info; // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException(nameof(pid)); } try { kinfo = GetProcInfo(pid, true, out count); if (kinfo == null || count < 1) { throw new ArgumentOutOfRangeException(nameof(pid)); } var process = new ReadOnlySpan<kinfo_proc>(kinfo, count); // Get the process information for the specified pid info = new ProcessInfo(); info.ProcessName = Marshal.PtrToStringAnsi((IntPtr)kinfo->ki_comm); info.BasePriority = kinfo->ki_nice; info.VirtualBytes = (long)kinfo->ki_size; info.WorkingSet = kinfo->ki_rssize; info.SessionId = kinfo->ki_sid; for (int i = 0; i < process.Length; i++) { var ti = new ThreadInfo() { _processId = pid, _threadId = (ulong)process[i].ki_tid, _basePriority = process[i].ki_nice, _startAddress = (IntPtr)process[i].ki_tdaddr }; info._threadInfoList.Add(ti); } } finally { Marshal.FreeHGlobal((IntPtr)kinfo); } return info; } /// <summary> /// Gets the process information for a given process /// </summary> /// <param name="pid">The PID (process ID) of the process</param> /// <param name="tid">The TID (thread ID) of the process</param> /// <returns> /// Returns basic info about thread. If tis is 0, it will return /// info for process e.g. main thread. /// </returns> public static unsafe proc_stats GetThreadInfo(int pid, int tid) { proc_stats ret = new proc_stats(); kinfo_proc* info = null; int count; try { info = GetProcInfo(pid, (tid != 0), out count); if (info != null && count >= 1) { if (tid == 0) { ret.startTime = (int)info->ki_start.tv_sec; ret.nice = info->ki_nice; ret.userTime = (ulong)info->ki_rusage.ru_utime.tv_sec * SecondsToNanoseconds + (ulong)info->ki_rusage.ru_utime.tv_usec; ret.systemTime = (ulong)info->ki_rusage.ru_stime.tv_sec * SecondsToNanoseconds + (ulong)info->ki_rusage.ru_stime.tv_usec; } else { var list = new ReadOnlySpan<kinfo_proc>(info, count); for (int i = 0; i < list.Length; i++) { if (list[i].ki_tid == tid) { ret.startTime = (int)list[i].ki_start.tv_sec; ret.nice = list[i].ki_nice; ret.userTime = (ulong)list[i].ki_rusage.ru_utime.tv_sec * SecondsToNanoseconds + (ulong)list[i].ki_rusage.ru_utime.tv_usec; ret.systemTime = (ulong)list[i].ki_rusage.ru_stime.tv_sec * SecondsToNanoseconds + (ulong)list[i].ki_rusage.ru_stime.tv_usec; break; } } } } } finally { Marshal.FreeHGlobal((IntPtr)info); } return ret; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 Import using System; using System.Configuration; using System.Runtime.Serialization; using ASC.Core; using ASC.Core.Common.Settings; using ASC.CRM.Core; #endregion namespace ASC.Web.CRM.Classes { [Serializable] [DataContract] public class SMTPServerSetting { public SMTPServerSetting() { Host = String.Empty; Port = 0; EnableSSL = false; RequiredHostAuthentication = false; HostLogin = String.Empty; HostPassword = String.Empty; SenderDisplayName = String.Empty; SenderEmailAddress = String.Empty; } public SMTPServerSetting(ASC.Core.Configuration.SmtpSettings smtpSettings) { Host = smtpSettings.Host; Port = smtpSettings.Port; EnableSSL = smtpSettings.EnableSSL; RequiredHostAuthentication = smtpSettings.EnableAuth; HostLogin = smtpSettings.CredentialsUserName; HostPassword = smtpSettings.CredentialsUserPassword; SenderDisplayName = smtpSettings.SenderDisplayName; SenderEmailAddress = smtpSettings.SenderAddress; } [DataMember] public String Host { get; set; } [DataMember] public int Port { get; set; } [DataMember] public bool EnableSSL { get; set; } [DataMember] public bool RequiredHostAuthentication { get; set; } [DataMember] public String HostLogin { get; set; } [DataMember] public String HostPassword { get; set; } [DataMember] public String SenderDisplayName { get; set; } [DataMember] public String SenderEmailAddress { get; set; } } [Serializable] [DataContract] public class InvoiceSetting { public InvoiceSetting() { Autogenerated = false; Prefix = String.Empty; Number = String.Empty; Terms = String.Empty; } public static InvoiceSetting DefaultSettings { get { return new InvoiceSetting { Autogenerated = true, Prefix = ConfigurationManagerExtension.AppSettings["crm.invoice.prefix"] ?? "INV-", Number = "0000001", Terms = String.Empty, CompanyName = String.Empty, CompanyLogoID = 0, CompanyAddress = String.Empty }; } } [DataMember] public bool Autogenerated { get; set; } [DataMember] public String Prefix { get; set; } [DataMember] public String Number { get; set; } [DataMember] public String Terms { get; set; } [DataMember] public String CompanyName { get; set; } [DataMember] public Int32 CompanyLogoID { get; set; } [DataMember] public String CompanyAddress { get; set; } } [Serializable] [DataContract] public class CRMSettings : BaseSettings<CRMSettings> { [DataMember(Name = "DefaultCurrency")] private string defaultCurrency; //[DataMember] public SMTPServerSetting SMTPServerSetting { get { return new SMTPServerSetting(CoreContext.Configuration.SmtpSettings); } } [DataMember(Name = "SMTPServerSetting")] public SMTPServerSetting SMTPServerSettingOld { get; set; } [DataMember] public InvoiceSetting InvoiceSetting { get; set; } [DataMember] public Guid WebFormKey { get; set; } public override Guid ID { get { return new Guid("fdf39b9a-ec96-4eb7-aeab-63f2c608eada"); } } public CurrencyInfo DefaultCurrency { get { return CurrencyProvider.Get(defaultCurrency); } set { defaultCurrency = value.Abbreviation; } } [DataMember(Name = "ChangeContactStatusGroupAuto")] public string ChangeContactStatusGroupAutoWrapper { get; set; } [IgnoreDataMember] public Boolean? ChangeContactStatusGroupAuto { get { return string.IsNullOrEmpty(ChangeContactStatusGroupAutoWrapper) ? null : (bool?)bool.Parse(ChangeContactStatusGroupAutoWrapper); } set { ChangeContactStatusGroupAutoWrapper = value.HasValue ? value.Value.ToString().ToLowerInvariant() : null; } } [DataMember(Name = "AddTagToContactGroupAuto")] public string AddTagToContactGroupAutoWrapper { get; set; } [IgnoreDataMember] public Boolean? AddTagToContactGroupAuto { get { return string.IsNullOrEmpty(AddTagToContactGroupAutoWrapper) ? null : (bool?)bool.Parse(AddTagToContactGroupAutoWrapper); } set { AddTagToContactGroupAutoWrapper = value.HasValue ? value.Value.ToString().ToLowerInvariant() : null; } } [DataMember(Name = "WriteMailToHistoryAuto")] public Boolean WriteMailToHistoryAuto { get; set; } [DataMember(Name = "IsConfiguredPortal")] public bool IsConfiguredPortal { get; set; } [DataMember(Name = "IsConfiguredSmtp")] public bool IsConfiguredSmtp { get; set; } public override ISettings GetDefault() { var languageName = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; var findedCurrency = CurrencyProvider.GetAll().Find(item => String.Compare(item.CultureName, languageName, true) == 0); return new CRMSettings { defaultCurrency = findedCurrency != null ? findedCurrency.Abbreviation : "USD", IsConfiguredPortal = false, ChangeContactStatusGroupAuto = null, AddTagToContactGroupAuto = null, WriteMailToHistoryAuto = false, WebFormKey = Guid.Empty, InvoiceSetting = InvoiceSetting.DefaultSettings }; } } [Serializable] [DataContract] public class CRMReportSampleSettings : BaseSettings<CRMReportSampleSettings> { [DataMember(Name = "NeedToGenerate")] public bool NeedToGenerate { get; set; } public override Guid ID { get { return new Guid("{54CD64AD-E73B-45A3-89E4-4D42A234D7A3}"); } } public override ISettings GetDefault() { return new CRMReportSampleSettings { NeedToGenerate = true }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class op_multiplyTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunMultiplyPositive() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Multiply Method - One Large BigInteger for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + "u*"); } // Multiply Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { try { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } catch (IndexOutOfRangeException) { // TODO: Refactor this Console.WriteLine("Array1: " + Print(tempByteArray1)); Console.WriteLine("Array2: " + Print(tempByteArray2)); throw; } } } [Fact] public static void RunMultiplyPositiveWith0() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Multiply Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } } [Fact] public static void RunMultiplyAxiomXmult1() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X*1 = X VerifyIdentityString(int.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString()); VerifyIdentityString(long.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { string randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+"); } } [Fact] public static void RunMultiplyAxiomXmult0() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X*0 = 0 VerifyIdentityString(int.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); VerifyIdentityString(long.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { string randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); } } [Fact] public static void RunMultiplyAxiomComm() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*"); // 32 bit boundary n1=0 n2=1 VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*"); } [Fact] public static void RunMultiplyBoundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*"); // 32 bit boundary n1=0 n2=1 VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*"); } [Fact] public static void RunMultiplyTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Multiply Method - One Large BigInteger for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + "u*"); } // Multiply Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { try { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } catch (IndexOutOfRangeException) { // TODO: Refactor this Console.WriteLine("Array1: " + Print(tempByteArray1)); Console.WriteLine("Array2: " + Print(tempByteArray2)); throw; } } // Multiply Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Multiply Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); tempByteArray1 = new byte[] { 0 }; tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyMultiplyString(Print(tempByteArray1) + Print(tempByteArray2) + "b*"); } // Axiom: X*1 = X VerifyIdentityString(int.MaxValue + " " + BigInteger.One + " b*", Int32.MaxValue.ToString()); VerifyIdentityString(long.MaxValue + " " + BigInteger.One + " b*", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { string randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.One + " b*", randBigInt + "u+"); } // Axiom: X*0 = 0 VerifyIdentityString(int.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); VerifyIdentityString(long.MaxValue + " " + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { string randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " b*", BigInteger.Zero.ToString()); } // Axiom: a*b = b*a VerifyIdentityString(int.MaxValue + " " + long.MaxValue + " b*", long.MaxValue + " " + int.MaxValue + " b*"); for (int i = 0; i < s_samples; i++) { string randBigInt1 = Print(GetRandomByteArray(s_random)); string randBigInt2 = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt1 + randBigInt2 + "b*", randBigInt2 + randBigInt1 + "b*"); } // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyMultiplyString(Math.Pow(2, 32) + " 2 b*"); // 32 bit boundary n1=0 n2=1 VerifyMultiplyString(Math.Pow(2, 33) + " 2 b*"); } private static void VerifyMultiplyString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(0, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetRandomByteArray(random, size); } private static string Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
// 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; class r8NaNrem { //user-defined class that overloads operator % public class numHolder { double d_num; public numHolder(double d_num) { this.d_num = Convert.ToDouble(d_num); } public static double operator %(numHolder a, double b) { return a.d_num % b; } public static double operator %(numHolder a, numHolder b) { return a.d_num % b.d_num; } } static double d_s_test1_op1 = 0.0F; static double d_s_test1_op2 = Double.NaN; static float d_s_test2_op1 = 0.0F; static float d_s_test2_op2 = 0.0F; static double d_s_test3_op1 = Double.NegativeInfinity; static double d_s_test3_op2 = 2.1234567890987654321; public static double d_test1_f(String s) { if (s == "test1_op1") return 0.0F; else return Double.NaN; } public static float d_test2_f(String s) { if (s == "test2_op1") return 0.0F; else return 0.0F; } public static double d_test3_f(String s) { if (s == "test3_op1") return Double.NegativeInfinity; else return 2.1234567890987654321; } class CL { public double d_cl_test1_op1 = 0.0F; public double d_cl_test1_op2 = Double.NaN; public float d_cl_test2_op1 = 0.0F; public float d_cl_test2_op2 = 0.0F; public double d_cl_test3_op1 = Double.NegativeInfinity; public double d_cl_test3_op2 = 2.1234567890987654321; } struct VT { public double d_vt_test1_op1; public double d_vt_test1_op2; public float d_vt_test2_op1; public float d_vt_test2_op2; public double d_vt_test3_op1; public double d_vt_test3_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.d_vt_test1_op1 = 0.0F; vt1.d_vt_test1_op2 = Double.NaN; vt1.d_vt_test2_op1 = 0.0F; vt1.d_vt_test2_op2 = 0.0F; vt1.d_vt_test3_op1 = Double.NegativeInfinity; vt1.d_vt_test3_op2 = 2.1234567890987654321; double[] d_arr1d_test1_op1 = { 0, 0.0F }; double[,] d_arr2d_test1_op1 = { { 0, 0.0F }, { 1, 1 } }; double[, ,] d_arr3d_test1_op1 = { { { 0, 0.0F }, { 1, 1 } } }; double[] d_arr1d_test1_op2 = { Double.NaN, 0, 1 }; double[,] d_arr2d_test1_op2 = { { 0, Double.NaN }, { 1, 1 } }; double[, ,] d_arr3d_test1_op2 = { { { 0, Double.NaN }, { 1, 1 } } }; float[] d_arr1d_test2_op1 = { 0, 0.0F }; float[,] d_arr2d_test2_op1 = { { 0, 0.0F }, { 1, 1 } }; float[, ,] d_arr3d_test2_op1 = { { { 0, 0.0F }, { 1, 1 } } }; float[] d_arr1d_test2_op2 = { 0.0F, 0, 1 }; float[,] d_arr2d_test2_op2 = { { 0, 0.0F }, { 1, 1 } }; float[, ,] d_arr3d_test2_op2 = { { { 0, 0.0F }, { 1, 1 } } }; double[] d_arr1d_test3_op1 = { 0, Double.NegativeInfinity }; double[,] d_arr2d_test3_op1 = { { 0, Double.NegativeInfinity }, { 1, 1 } }; double[, ,] d_arr3d_test3_op1 = { { { 0, Double.NegativeInfinity }, { 1, 1 } } }; double[] d_arr1d_test3_op2 = { 2.1234567890987654321, 0, 1 }; double[,] d_arr2d_test3_op2 = { { 0, 2.1234567890987654321 }, { 1, 1 } }; double[, ,] d_arr3d_test3_op2 = { { { 0, 2.1234567890987654321 }, { 1, 1 } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { double d_l_test1_op1 = 0.0F; double d_l_test1_op2 = Double.NaN; if (!Double.IsNaN(d_l_test1_op1 % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test1_op1 % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test1_op1 % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test1_f("test1_op1") % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test1_op1 % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test1_op1 % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test1_op1[1] % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test1_op1[index[0, 1], index[1, 0]] % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % d_l_test1_op2)) { Console.WriteLine("Test1_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % d_s_test1_op2)) { Console.WriteLine("Test1_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % d_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % cl1.d_cl_test1_op2)) { Console.WriteLine("Test1_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % vt1.d_vt_test1_op2)) { Console.WriteLine("Test1_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % d_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % d_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] % d_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 64 failed"); passed = false; } } { float d_l_test2_op1 = 0.0F; float d_l_test2_op2 = 0.0F; if (!Double.IsNaN(d_l_test2_op1 % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test2_op1 % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test2_op1 % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test2_f("test2_op1") % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test2_op1 % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test2_op1 % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test2_op1[1] % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test2_op1[index[0, 1], index[1, 0]] % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % d_l_test2_op2)) { Console.WriteLine("Test2_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % d_s_test2_op2)) { Console.WriteLine("Test2_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % d_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % cl1.d_cl_test2_op2)) { Console.WriteLine("Test2_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % vt1.d_vt_test2_op2)) { Console.WriteLine("Test2_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % d_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % d_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] % d_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 64 failed"); passed = false; } } { double d_l_test3_op1 = Double.NegativeInfinity; double d_l_test3_op2 = 2.1234567890987654321; if (!Double.IsNaN(d_l_test3_op1 % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 1 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 2 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 3 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 4 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 5 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 6 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 7 failed"); passed = false; } if (!Double.IsNaN(d_l_test3_op1 % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 8 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 9 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 10 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 11 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 12 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 13 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 14 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 15 failed"); passed = false; } if (!Double.IsNaN(d_s_test3_op1 % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 16 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 17 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 18 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 19 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 20 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 21 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 22 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 23 failed"); passed = false; } if (!Double.IsNaN(d_test3_f("test3_op1") % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 24 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 25 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 26 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 27 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 28 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 29 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 30 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 31 failed"); passed = false; } if (!Double.IsNaN(cl1.d_cl_test3_op1 % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 32 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 33 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 34 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 35 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 36 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 37 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 38 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 39 failed"); passed = false; } if (!Double.IsNaN(vt1.d_vt_test3_op1 % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 40 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 41 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 42 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 43 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 44 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 45 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 46 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 47 failed"); passed = false; } if (!Double.IsNaN(d_arr1d_test3_op1[1] % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 48 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 49 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 50 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 51 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 52 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 53 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 54 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 55 failed"); passed = false; } if (!Double.IsNaN(d_arr2d_test3_op1[index[0, 1], index[1, 0]] % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 56 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % d_l_test3_op2)) { Console.WriteLine("Test3_testcase 57 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % d_s_test3_op2)) { Console.WriteLine("Test3_testcase 58 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % d_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 59 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % cl1.d_cl_test3_op2)) { Console.WriteLine("Test3_testcase 60 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % vt1.d_vt_test3_op2)) { Console.WriteLine("Test3_testcase 61 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % d_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 62 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % d_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 63 failed"); passed = false; } if (!Double.IsNaN(d_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] % d_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 64 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.3.5. Abstract superclass for logistics PDUs /// </summary> [Serializable] [XmlRoot] public partial class LogisticsPdu : Pdu, IEquatable<LogisticsPdu> { /// <summary> /// Initializes a new instance of the <see cref="LogisticsPdu"/> class. /// </summary> public LogisticsPdu() { ProtocolFamily = (byte)3; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(LogisticsPdu left, LogisticsPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(LogisticsPdu left, LogisticsPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); return marshalSize; } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public virtual void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<LogisticsPdu>"); base.Reflection(sb); try { sb.AppendLine("</LogisticsPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as LogisticsPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(LogisticsPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); return result; } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class VideoView : android.view.SurfaceView, android.widget.MediaController.MediaPlayerControl { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected VideoView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void start() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "start", "()V", ref global::android.widget.VideoView._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual void suspend() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "suspend", "()V", ref global::android.widget.VideoView._m1); } private static global::MonoJavaBridge.MethodId _m2; public virtual void resume() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "resume", "()V", ref global::android.widget.VideoView._m2); } private static global::MonoJavaBridge.MethodId _m3; public override bool onKeyDown(int arg0, android.view.KeyEvent arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.VideoView.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z", ref global::android.widget.VideoView._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public override bool onTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.VideoView.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.VideoView._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m5; public override bool onTrackballEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.VideoView.staticClass, "onTrackballEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.widget.VideoView._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; protected override void onMeasure(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "onMeasure", "(II)V", ref global::android.widget.VideoView._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new int Duration { get { return getDuration(); } } private static global::MonoJavaBridge.MethodId _m7; public virtual int getDuration() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.VideoView.staticClass, "getDuration", "()I", ref global::android.widget.VideoView._m7); } private static global::MonoJavaBridge.MethodId _m8; public virtual void pause() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "pause", "()V", ref global::android.widget.VideoView._m8); } private static global::MonoJavaBridge.MethodId _m9; public virtual bool isPlaying() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.VideoView.staticClass, "isPlaying", "()Z", ref global::android.widget.VideoView._m9); } private static global::MonoJavaBridge.MethodId _m10; public virtual void seekTo(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "seekTo", "(I)V", ref global::android.widget.VideoView._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int CurrentPosition { get { return getCurrentPosition(); } } private static global::MonoJavaBridge.MethodId _m11; public virtual int getCurrentPosition() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.VideoView.staticClass, "getCurrentPosition", "()I", ref global::android.widget.VideoView._m11); } public new global::android.media.MediaPlayer.OnPreparedListener OnPreparedListener { set { setOnPreparedListener(value); } } private static global::MonoJavaBridge.MethodId _m12; public virtual void setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "setOnPreparedListener", "(Landroid/media/MediaPlayer$OnPreparedListener;)V", ref global::android.widget.VideoView._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnPreparedListener(global::android.media.MediaPlayer.OnPreparedListenerDelegate arg0) { setOnPreparedListener((global::android.media.MediaPlayer.OnPreparedListenerDelegateWrapper)arg0); } public new global::android.media.MediaPlayer.OnCompletionListener OnCompletionListener { set { setOnCompletionListener(value); } } private static global::MonoJavaBridge.MethodId _m13; public virtual void setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "setOnCompletionListener", "(Landroid/media/MediaPlayer$OnCompletionListener;)V", ref global::android.widget.VideoView._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnCompletionListener(global::android.media.MediaPlayer.OnCompletionListenerDelegate arg0) { setOnCompletionListener((global::android.media.MediaPlayer.OnCompletionListenerDelegateWrapper)arg0); } public new global::android.media.MediaPlayer.OnErrorListener OnErrorListener { set { setOnErrorListener(value); } } private static global::MonoJavaBridge.MethodId _m14; public virtual void setOnErrorListener(android.media.MediaPlayer.OnErrorListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "setOnErrorListener", "(Landroid/media/MediaPlayer$OnErrorListener;)V", ref global::android.widget.VideoView._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnErrorListener(global::android.media.MediaPlayer.OnErrorListenerDelegate arg0) { setOnErrorListener((global::android.media.MediaPlayer.OnErrorListenerDelegateWrapper)arg0); } public new int BufferPercentage { get { return getBufferPercentage(); } } private static global::MonoJavaBridge.MethodId _m15; public virtual int getBufferPercentage() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.VideoView.staticClass, "getBufferPercentage", "()I", ref global::android.widget.VideoView._m15); } private static global::MonoJavaBridge.MethodId _m16; public virtual bool canPause() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.VideoView.staticClass, "canPause", "()Z", ref global::android.widget.VideoView._m16); } private static global::MonoJavaBridge.MethodId _m17; public virtual bool canSeekBackward() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.VideoView.staticClass, "canSeekBackward", "()Z", ref global::android.widget.VideoView._m17); } private static global::MonoJavaBridge.MethodId _m18; public virtual bool canSeekForward() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.VideoView.staticClass, "canSeekForward", "()Z", ref global::android.widget.VideoView._m18); } private static global::MonoJavaBridge.MethodId _m19; public virtual int resolveAdjustedSize(int arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.VideoView.staticClass, "resolveAdjustedSize", "(II)I", ref global::android.widget.VideoView._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new global::java.lang.String VideoPath { set { setVideoPath(value); } } private static global::MonoJavaBridge.MethodId _m20; public virtual void setVideoPath(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "setVideoPath", "(Ljava/lang/String;)V", ref global::android.widget.VideoView._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.net.Uri VideoURI { set { setVideoURI(value); } } private static global::MonoJavaBridge.MethodId _m21; public virtual void setVideoURI(android.net.Uri arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "setVideoURI", "(Landroid/net/Uri;)V", ref global::android.widget.VideoView._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public virtual void stopPlayback() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "stopPlayback", "()V", ref global::android.widget.VideoView._m22); } public new global::android.widget.MediaController MediaController { set { setMediaController(value); } } private static global::MonoJavaBridge.MethodId _m23; public virtual void setMediaController(android.widget.MediaController arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.VideoView.staticClass, "setMediaController", "(Landroid/widget/MediaController;)V", ref global::android.widget.VideoView._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m24; public VideoView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.VideoView._m24.native == global::System.IntPtr.Zero) global::android.widget.VideoView._m24 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.VideoView.staticClass, global::android.widget.VideoView._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m25; public VideoView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.VideoView._m25.native == global::System.IntPtr.Zero) global::android.widget.VideoView._m25 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.VideoView.staticClass, global::android.widget.VideoView._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m26; public VideoView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.VideoView._m26.native == global::System.IntPtr.Zero) global::android.widget.VideoView._m26 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "<init>", "(Landroid/content/Context;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.VideoView.staticClass, global::android.widget.VideoView._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static VideoView() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.VideoView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/VideoView")); } } }
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml; using Xamarin.Forms.Internals; namespace Xamarin.Forms.Xaml { internal interface INode { List<string> IgnorablePrefixes { get; set; } IXmlNamespaceResolver NamespaceResolver { get; } INode Parent { get; set; } void Accept(IXamlNodeVisitor visitor, INode parentNode); } internal interface IValueNode : INode { } internal interface IElementNode : INode, IListNode { Dictionary<XmlName, INode> Properties { get; } List<XmlName> SkipProperties { get; } INameScope Namescope { get; } XmlType XmlType { get; } string NamespaceURI { get; } } internal interface IListNode : INode { List<INode> CollectionItems { get; } } [DebuggerDisplay("{NamespaceUri}:{Name}")] internal class XmlType { public XmlType(string namespaceUri, string name, IList<XmlType> typeArguments) { NamespaceUri = namespaceUri; Name = name; TypeArguments = typeArguments; } public string NamespaceUri { get; } public string Name { get; } public IList<XmlType> TypeArguments { get; private set; } } internal abstract class BaseNode : IXmlLineInfo, INode { protected BaseNode(IXmlNamespaceResolver namespaceResolver, int linenumber = -1, int lineposition = -1) { NamespaceResolver = namespaceResolver; LineNumber = linenumber; LinePosition = lineposition; } public IXmlNamespaceResolver NamespaceResolver { get; } public abstract void Accept(IXamlNodeVisitor visitor, INode parentNode); public INode Parent { get; set; } public List<string> IgnorablePrefixes { get; set; } public bool HasLineInfo() { return LineNumber >= 0 && LinePosition >= 0; } public int LineNumber { get; set; } public int LinePosition { get; set; } } [DebuggerDisplay("{Value}")] internal class ValueNode : BaseNode, IValueNode { public ValueNode(object value, IXmlNamespaceResolver namespaceResolver, int linenumber = -1, int lineposition = -1) : base(namespaceResolver, linenumber, lineposition) { Value = value; } public object Value { get; set; } public override void Accept(IXamlNodeVisitor visitor, INode parentNode) { visitor.Visit(this, parentNode); } } [DebuggerDisplay("{MarkupString}")] internal class MarkupNode : BaseNode, IValueNode { public MarkupNode(string markupString, IXmlNamespaceResolver namespaceResolver, int linenumber = -1, int lineposition = -1) : base(namespaceResolver, linenumber, lineposition) { MarkupString = markupString; } public string MarkupString { get; } public override void Accept(IXamlNodeVisitor visitor, INode parentNode) { visitor.Visit(this, parentNode); } } internal class ElementNode : BaseNode, IValueNode, IElementNode { public ElementNode(XmlType type, string namespaceURI, IXmlNamespaceResolver namespaceResolver, int linenumber = -1, int lineposition = -1) : base(namespaceResolver, linenumber, lineposition) { Properties = new Dictionary<XmlName, INode>(); SkipProperties = new List<XmlName>(); CollectionItems = new List<INode>(); XmlType = type; NamespaceURI = namespaceURI; } public Dictionary<XmlName, INode> Properties { get; } public List<XmlName> SkipProperties { get; } public List<INode> CollectionItems { get; } public XmlType XmlType { get; } public string NamespaceURI { get; } public INameScope Namescope { get; set; } public override void Accept(IXamlNodeVisitor visitor, INode parentNode) { if (!visitor.VisitChildrenFirst) visitor.Visit(this, parentNode); if ((!visitor.StopOnDataTemplate || !IsDataTemplate(this, parentNode)) && (!visitor.StopOnResourceDictionary || !IsResourceDictionary(this, parentNode))) { foreach (var node in Properties.Values.ToList()) node.Accept(visitor, this); foreach (var node in CollectionItems) node.Accept(visitor, this); } if (visitor.VisitChildrenFirst) visitor.Visit(this, parentNode); } internal static bool IsDataTemplate(INode node, INode parentNode) { var parentElement = parentNode as IElementNode; INode createContent; if (parentElement != null && parentElement.Properties.TryGetValue(XmlName._CreateContent, out createContent) && createContent == node) return true; return false; } internal static bool IsResourceDictionary(INode node, INode parentNode) { var enode = node as ElementNode; return enode.XmlType.Name == "ResourceDictionary"; } } internal abstract class RootNode : ElementNode { protected RootNode(XmlType xmlType, IXmlNamespaceResolver nsResolver) : base(xmlType, xmlType.NamespaceUri, nsResolver) { } public override void Accept(IXamlNodeVisitor visitor, INode parentNode) { if (!visitor.VisitChildrenFirst) visitor.Visit(this, parentNode); if ((!visitor.StopOnDataTemplate || !IsDataTemplate(this, parentNode)) && (!visitor.StopOnResourceDictionary || !IsResourceDictionary(this, parentNode))) { foreach (var node in Properties.Values.ToList()) node.Accept(visitor, this); foreach (var node in CollectionItems) node.Accept(visitor, this); } if (visitor.VisitChildrenFirst) visitor.Visit(this, parentNode); } } internal class ListNode : BaseNode, IListNode, IValueNode { public ListNode(IList<INode> nodes, IXmlNamespaceResolver namespaceResolver, int linenumber = -1, int lineposition = -1) : base(namespaceResolver, linenumber, lineposition) { CollectionItems = nodes.ToList(); } public XmlName XmlName { get; set; } public List<INode> CollectionItems { get; set; } public override void Accept(IXamlNodeVisitor visitor, INode parentNode) { if (!visitor.VisitChildrenFirst) visitor.Visit(this, parentNode); foreach (var node in CollectionItems) node.Accept(visitor, this); if (visitor.VisitChildrenFirst) visitor.Visit(this, parentNode); } } internal static class INodeExtensions { public static bool SkipPrefix(this INode node, string prefix) { do { if (node.IgnorablePrefixes != null && node.IgnorablePrefixes.Contains(prefix)) return true; node = node.Parent; } while (node != null); return false; } } }
/* * 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.Xml.Serialization; using System.Reflection; using log4net; using OpenMetaverse; namespace OpenSim.Framework { [Flags] public enum AssetFlags : int { Normal = 0, // Immutable asset Maptile = 1, // What it says Rewritable = 2, // Content can be rewritten Collectable = 4 // Can be GC'ed after some time } /// <summary> /// Asset class. All Assets are reference by this class or a class derived from this class /// </summary> [Serializable] public class AssetBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Data of the Asset /// </summary> private byte[] m_data; /// <summary> /// Meta Data of the Asset /// </summary> private AssetMetadata m_metadata; // This is needed for .NET serialization!!! // Do NOT "Optimize" away! public AssetBase() { m_metadata = new AssetMetadata(); m_metadata.FullID = UUID.Zero; m_metadata.ID = UUID.Zero.ToString(); m_metadata.Type = (sbyte)AssetType.Unknown; m_metadata.CreatorID = String.Empty; } public AssetBase(UUID assetID, string name, sbyte assetType, string creatorID) { if (assetType == (sbyte)AssetType.Unknown) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true); m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}", name, assetID, trace.ToString()); } m_metadata = new AssetMetadata(); m_metadata.FullID = assetID; m_metadata.Name = name; m_metadata.Type = assetType; m_metadata.CreatorID = creatorID; } public AssetBase(string assetID, string name, sbyte assetType, string creatorID) { if (assetType == (sbyte)AssetType.Unknown) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true); m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}", name, assetID, trace.ToString()); } m_metadata = new AssetMetadata(); m_metadata.ID = assetID; m_metadata.Name = name; m_metadata.Type = assetType; m_metadata.CreatorID = creatorID; } public bool ContainsReferences { get { return IsTextualAsset && ( Type != (sbyte)AssetType.Notecard && Type != (sbyte)AssetType.CallingCard && Type != (sbyte)AssetType.LSLText && Type != (sbyte)AssetType.Landmark); } } public bool IsTextualAsset { get { return !IsBinaryAsset; } } /// <summary> /// Checks if this asset is a binary or text asset /// </summary> public bool IsBinaryAsset { get { return (Type == (sbyte) AssetType.Animation || Type == (sbyte)AssetType.Gesture || Type == (sbyte)AssetType.Simstate || Type == (sbyte)AssetType.Unknown || Type == (sbyte)AssetType.Object || Type == (sbyte)AssetType.Sound || Type == (sbyte)AssetType.SoundWAV || Type == (sbyte)AssetType.Texture || Type == (sbyte)AssetType.TextureTGA || Type == (sbyte)AssetType.Folder || Type == (sbyte)AssetType.RootFolder || Type == (sbyte)AssetType.LostAndFoundFolder || Type == (sbyte)AssetType.SnapshotFolder || Type == (sbyte)AssetType.TrashFolder || Type == (sbyte)AssetType.ImageJPEG || Type == (sbyte) AssetType.ImageTGA || Type == (sbyte) AssetType.LSLBytecode); } } public virtual byte[] Data { get { return m_data; } set { m_data = value; } } /// <summary> /// Asset UUID /// </summary> public UUID FullID { get { return m_metadata.FullID; } set { m_metadata.FullID = value; } } /// <summary> /// Asset MetaData ID (transferring from UUID to string ID) /// </summary> public string ID { get { return m_metadata.ID; } set { m_metadata.ID = value; } } public string Name { get { return m_metadata.Name; } set { m_metadata.Name = value; } } public string Description { get { return m_metadata.Description; } set { m_metadata.Description = value; } } /// <summary> /// (sbyte) AssetType enum /// </summary> public sbyte Type { get { return m_metadata.Type; } set { m_metadata.Type = value; } } /// <summary> /// Is this a region only asset, or does this exist on the asset server also /// </summary> public bool Local { get { return m_metadata.Local; } set { m_metadata.Local = value; } } /// <summary> /// Is this asset going to be saved to the asset database? /// </summary> public bool Temporary { get { return m_metadata.Temporary; } set { m_metadata.Temporary = value; } } public AssetFlags Flags { get { return m_metadata.Flags; } set { m_metadata.Flags = value; } } [XmlIgnore] public AssetMetadata Metadata { get { return m_metadata; } set { m_metadata = value; } } public override string ToString() { return FullID.ToString(); } } [Serializable] public class AssetMetadata { private UUID m_fullid; private string m_id; private string m_name = String.Empty; private string m_description = String.Empty; private DateTime m_creation_date; private sbyte m_type = (sbyte)AssetType.Unknown; private string m_content_type; private byte[] m_sha1; private bool m_local; private bool m_temporary; private string m_creatorid; private AssetFlags m_flags; public UUID FullID { get { return m_fullid; } set { m_fullid = value; m_id = m_fullid.ToString(); } } public string ID { //get { return m_fullid.ToString(); } //set { m_fullid = new UUID(value); } get { if (String.IsNullOrEmpty(m_id)) m_id = m_fullid.ToString(); return m_id; } set { UUID uuid = UUID.Zero; if (UUID.TryParse(value, out uuid)) { m_fullid = uuid; m_id = m_fullid.ToString(); } else m_id = value; } } public string Name { get { return m_name; } set { m_name = value; } } public string Description { get { return m_description; } set { m_description = value; } } public DateTime CreationDate { get { return m_creation_date; } set { m_creation_date = value; } } public sbyte Type { get { return m_type; } set { m_type = value; } } public string ContentType { get { if (!String.IsNullOrEmpty(m_content_type)) return m_content_type; else return SLUtil.SLAssetTypeToContentType(m_type); } set { m_content_type = value; sbyte type = (sbyte)SLUtil.ContentTypeToSLAssetType(value); if (type != -1) m_type = type; } } public byte[] SHA1 { get { return m_sha1; } set { m_sha1 = value; } } public bool Local { get { return m_local; } set { m_local = value; } } public bool Temporary { get { return m_temporary; } set { m_temporary = value; } } public string CreatorID { get { return m_creatorid; } set { m_creatorid = value; } } public AssetFlags Flags { get { return m_flags; } set { m_flags = 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.IdentityModel.Tokens; using System.Runtime; using System.ServiceModel; using System.Threading.Tasks; namespace System.IdentityModel.Selectors { public abstract class SecurityTokenProvider { protected SecurityTokenProvider() { } public virtual bool SupportsTokenRenewal { get { return false; } } public virtual bool SupportsTokenCancellation { get { return false; } } #region GetToken public SecurityToken GetToken(TimeSpan timeout) { SecurityToken token = GetTokenCore(timeout); if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToGetToken, this))); } return token; } public IAsyncResult BeginGetToken(TimeSpan timeout, AsyncCallback callback, object state) { return BeginGetTokenCore(timeout, callback, state); } public SecurityToken EndGetToken(IAsyncResult result) { if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(result)); } SecurityToken token = EndGetTokenCore(result); if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToGetToken, this))); } return token; } public async Task<SecurityToken> GetTokenAsync(TimeSpan timeout) { SecurityToken token = await GetTokenCoreAsync(timeout); if (token == null) { throw Fx.Exception.AsError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToGetToken, this))); } return token; } protected abstract SecurityToken GetTokenCore(TimeSpan timeout); protected virtual IAsyncResult BeginGetTokenCore(TimeSpan timeout, AsyncCallback callback, object state) { return GetTokenCoreInternalAsync(timeout).ToApm(callback, state); } protected virtual SecurityToken EndGetTokenCore(IAsyncResult result) { return result.ToApmEnd<SecurityToken>(); } protected virtual Task<SecurityToken> GetTokenCoreAsync(TimeSpan timeout) { return Task<SecurityToken>.Factory.FromAsync(BeginGetTokenCore, EndGetTokenCore, timeout, null); } // If external concrete implementation overrides GetTokenCoreAsync and calls base.GetTokenCoreAsync, this will call into base class implementation in GetTokenCoreInternalAsync. // This pattern prevents a cycle of GetTokenCoreAsync wrapping {Begin|End}GetTokenCore and {Begin|End}GetTokenCore wrapping GetTokenCoreAsync. internal virtual Task<SecurityToken> GetTokenCoreInternalAsync(TimeSpan timeout) { return Task.FromResult(GetTokenCore(timeout)); } #endregion // GetToken #region RenewToken public SecurityToken RenewToken(TimeSpan timeout, SecurityToken tokenToBeRenewed) { if (tokenToBeRenewed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenToBeRenewed)); } SecurityToken token = RenewTokenCore(timeout, tokenToBeRenewed); if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToRenewToken, this))); } return token; } public IAsyncResult BeginRenewToken(TimeSpan timeout, SecurityToken tokenToBeRenewed, AsyncCallback callback, object state) { if (tokenToBeRenewed == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenToBeRenewed)); } return BeginRenewTokenCore(timeout, tokenToBeRenewed, callback, state); } public SecurityToken EndRenewToken(IAsyncResult result) { if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(result)); } SecurityToken token = EndRenewTokenCore(result); if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToRenewToken, this))); } return token; } public async Task<SecurityToken> RenewTokenAsync(TimeSpan timeout, SecurityToken tokenToBeRenewed) { if (tokenToBeRenewed == null) { throw Fx.Exception.ArgumentNull(nameof(tokenToBeRenewed)); } SecurityToken token = await RenewTokenCoreAsync(timeout, tokenToBeRenewed); if (token == null) { throw Fx.Exception.AsError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToRenewToken, this))); } return token; } protected virtual SecurityToken RenewTokenCore(TimeSpan timeout, SecurityToken tokenToBeRenewed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.TokenRenewalNotSupported, this))); } protected virtual IAsyncResult BeginRenewTokenCore(TimeSpan timeout, SecurityToken tokenToBeRenewed, AsyncCallback callback, object state) { return RenewTokenCoreInternalAsync(timeout, tokenToBeRenewed).ToApm(callback, state); } protected virtual SecurityToken EndRenewTokenCore(IAsyncResult result) { return result.ToApmEnd<SecurityToken>(); } protected virtual Task<SecurityToken> RenewTokenCoreAsync(TimeSpan timeout, SecurityToken tokenToBeRenewed) { return Task<SecurityToken>.Factory.FromAsync(BeginRenewTokenCore, EndRenewTokenCore, timeout, tokenToBeRenewed, null); } internal virtual Task<SecurityToken> RenewTokenCoreInternalAsync(TimeSpan timeout, SecurityToken tokenToBeRenewed) { return Task.FromResult(RenewTokenCore(timeout, tokenToBeRenewed)); } #endregion // RenewToken #region CancelToken public void CancelToken(TimeSpan timeout, SecurityToken token) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(token)); } CancelTokenCore(timeout, token); } public IAsyncResult BeginCancelToken(TimeSpan timeout, SecurityToken token, AsyncCallback callback, object state) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(token)); } return BeginCancelTokenCore(timeout, token, callback, state); } public void EndCancelToken(IAsyncResult result) { if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(result)); } EndCancelTokenCore(result); } public async Task CancelTokenAsync(TimeSpan timeout, SecurityToken token) { if (token == null) { throw Fx.Exception.ArgumentNull(nameof(token)); } await CancelTokenCoreAsync(timeout, token); } protected virtual void CancelTokenCore(TimeSpan timeout, SecurityToken token) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.TokenCancellationNotSupported, this))); } protected virtual IAsyncResult BeginCancelTokenCore(TimeSpan timeout, SecurityToken token, AsyncCallback callback, object state) { return CancelTokenCoreInternalAsync(timeout, token).ToApm(callback, state); } protected virtual void EndCancelTokenCore(IAsyncResult result) { result.ToApmEnd(); } protected virtual Task CancelTokenCoreAsync(TimeSpan timeout, SecurityToken token) { return Task.Factory.FromAsync(BeginCancelTokenCore, EndCancelTokenCore, timeout, token, null); } internal virtual Task CancelTokenCoreInternalAsync(TimeSpan timeout, SecurityToken token) { CancelTokenCore(timeout, token); return Task.CompletedTask; } #endregion // CancelToken } }
using System.Linq; using UnityEngine; using UnityEngine.UIElements; using PositionType = UnityEngine.UIElements.Position; namespace UnityEditor.VFX.UI { class LineDragger : Manipulator { VFXReorderableList m_Root; VisualElement m_Line; public LineDragger(VFXReorderableList root, VisualElement item) { m_Root = root; m_Line = item; } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<MouseDownEvent>(OnMouseDown); target.RegisterCallback<MouseUpEvent>(OnMouseUp); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseDownEvent>(OnMouseDown); target.UnregisterCallback<MouseUpEvent>(OnMouseUp); } Vector2 startPosition; object m_Ctx; void Release() { target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); target.ReleaseMouse(); m_Ctx = null; } protected void OnMouseDown(MouseDownEvent evt) { if (evt.button == 0) { evt.StopPropagation(); target.CaptureMouse(); startPosition = m_Root.WorldToLocal(evt.mousePosition); target.RegisterCallback<MouseMoveEvent>(OnMouseMove); m_Ctx = m_Root.StartDragging(m_Line); } } protected void OnMouseUp(MouseUpEvent evt) { Vector2 listRelativeMouse = m_Root.WorldToLocal(evt.mousePosition); m_Root.EndDragging(m_Ctx, m_Line, listRelativeMouse.y - startPosition.y, evt.mousePosition); evt.StopPropagation(); Release(); } protected void OnMouseMove(MouseMoveEvent evt) { evt.StopPropagation(); Vector2 listRelativeMouse = m_Root.WorldToLocal(evt.mousePosition); m_Root.ItemDragging(m_Ctx, m_Line, listRelativeMouse.y - startPosition.y, evt.mousePosition); } } class LineSelecter : Manipulator { VFXReorderableList m_Root; VisualElement m_Line; public LineSelecter(VFXReorderableList root, VisualElement item) { m_Root = root; m_Line = item; } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<MouseDownEvent>(OnMouseDown, TrickleDown.TrickleDown); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseDownEvent>(OnMouseDown, TrickleDown.TrickleDown); } void OnMouseDown(MouseDownEvent e) { m_Root.Select(m_Line); } } class VFXReorderableList : VisualElement { int m_SelectedLine = -1; class DraggingContext { public Rect[] originalPositions; public VisualElement[] items; public Rect myOriginalPosition; public int draggedIndex; } public void Select(int index) { if (m_SelectedLine != -1 && m_SelectedLine < m_ListContainer.childCount) { m_ListContainer.ElementAt(m_SelectedLine).RemoveFromClassList("selected"); } m_SelectedLine = index; if (m_SelectedLine != -1 && m_SelectedLine < m_ListContainer.childCount) { m_ListContainer.ElementAt(m_SelectedLine).AddToClassList("selected"); m_Remove.SetEnabled(CanRemove()); } else { m_Remove.SetEnabled(false); } } public virtual bool CanRemove() { return true; } public void Select(VisualElement item) { Select(m_ListContainer.IndexOf(item)); } public object StartDragging(VisualElement item) { //Fix all item so that they can be animated and we can control their positions DraggingContext context = new DraggingContext(); context.items = m_ListContainer.Children().ToArray(); context.originalPositions = context.items.Select(t => t.layout).ToArray(); context.draggedIndex = m_ListContainer.IndexOf(item); context.myOriginalPosition = m_ListContainer.layout; Select(context.draggedIndex); for (int i = 0; i < context.items.Length; ++i) { VisualElement child = context.items[i]; Rect rect = context.originalPositions[i]; child.style.position = PositionType.Absolute; child.style.left = rect.x; child.style.top = rect.y; child.style.width = rect.width; child.style.height = rect.height; } item.BringToFront(); m_ListContainer.style.width = context.myOriginalPosition.width; m_ListContainer.style.height = context.myOriginalPosition.height; return context; } public void EndDragging(object ctx, VisualElement item, float offset, Vector2 mouseWorldPosition) { DraggingContext context = (DraggingContext)ctx; foreach (var child in m_ListContainer.Children()) { child.ResetPositionProperties(); } int hoveredIndex = GetHoveredIndex(context, mouseWorldPosition); m_ListContainer.Insert(hoveredIndex != -1 ? hoveredIndex : context.draggedIndex, item); m_ListContainer.ResetPositionProperties(); if (hoveredIndex != -1) { ElementMoved(context.draggedIndex, hoveredIndex); } } public void ItemDragging(object ctx, VisualElement item, float offset, Vector2 mouseWorldPosition) { DraggingContext context = (DraggingContext)ctx; item.style.top = context.originalPositions[context.draggedIndex].y + offset; int hoveredIndex = GetHoveredIndex(context, mouseWorldPosition); if (hoveredIndex != -1) { float draggedHeight = context.originalPositions[context.draggedIndex].height; if (hoveredIndex < context.draggedIndex) { for (int i = 0; i < hoveredIndex; ++i) { context.items[i].style.top = context.originalPositions[i].y; } for (int i = hoveredIndex; i < context.draggedIndex; ++i) { context.items[i].style.top = context.originalPositions[i].y + draggedHeight; } for (int i = context.draggedIndex + 1; i < context.items.Length; ++i) { context.items[i].style.top = context.originalPositions[i].y; } } else if (hoveredIndex > context.draggedIndex) { for (int i = 0; i < context.draggedIndex; ++i) { context.items[i].style.top = context.originalPositions[i].y; } for (int i = hoveredIndex; i > context.draggedIndex; --i) { context.items[i].style.top = context.originalPositions[i].y - draggedHeight; } for (int i = hoveredIndex + 1; i < context.items.Length; ++i) { context.items[i].style.top = context.originalPositions[i].y; } } } else { for (int i = 0; i < context.items.Length; ++i) { if (i != context.draggedIndex) context.items[i].style.top = context.originalPositions[i].y; } } } int GetHoveredIndex(DraggingContext context, Vector2 mouseWorldPosition) { Vector2 mousePosition = m_ListContainer.WorldToLocal(mouseWorldPosition); int hoveredIndex = -1; for (int i = 0; i < context.items.Length; ++i) { if (i != context.draggedIndex && context.originalPositions[i].Contains(mousePosition)) { hoveredIndex = i; break; } } return hoveredIndex; } protected virtual void ElementMoved(int movedIndex, int targetIndex) { if (m_SelectedLine == movedIndex) { m_SelectedLine = targetIndex; } } VisualElement m_ListContainer; VisualElement m_Toolbar; public VFXReorderableList() { m_ListContainer = new VisualElement() {name = "ListContainer"}; Add(m_ListContainer); m_Toolbar = new VisualElement() { name = "Toolbar"}; var add = new VisualElement() { name = "Add" }; add.Add(new VisualElement() { name = "icon" }); add.AddManipulator(new Clickable(OnAdd)); m_Toolbar.Add(add); m_Remove = new VisualElement() { name = "Remove" }; m_Remove.Add(new VisualElement() { name = "icon" }); m_Remove.AddManipulator(new Clickable(OnRemoveButton)); m_Toolbar.Add(m_Remove); m_Remove.SetEnabled(false); Add(m_Toolbar); this.AddStyleSheetPathWithSkinVariant("VFXReorderableList"); AddToClassList("ReorderableList"); } VisualElement m_Remove; public void AddItem(VisualElement item) { m_ListContainer.Add(item); item.AddManipulator(new LineSelecter(this, item)); if (reorderable) { AddDragToItem(item); } Select(m_ListContainer.childCount - 1); m_Remove.SetEnabled(CanRemove()); } void AddDragToItem(VisualElement item) { var draggingHandle = new VisualElement() { name = "DraggingHandle" }; draggingHandle.Add(new VisualElement() { name = "icon" }); item.Insert(0, draggingHandle); draggingHandle.AddManipulator(new LineDragger(this, item)); } void RemoveDragFromItem(VisualElement item) { if (item.childCount < 1 || item.ElementAt(0).name != "DraggingHandle") return; item.RemoveAt(0); } public bool toolbar { get {return m_Toolbar.parent != null; } set { if (value) { if (m_Toolbar.parent == null) { Add(m_Toolbar); } } else { if (m_Toolbar.parent != null) { m_Toolbar.RemoveFromHierarchy(); } } } } bool m_Reorderable = true; public bool reorderable { get { return m_Reorderable; } set { if (m_Reorderable != value) { m_Reorderable = value; foreach (var item in m_ListContainer.Children()) { if (m_Reorderable) { AddDragToItem(item); } else { RemoveDragFromItem(item); } } } } } public void RemoveItemAt(int index) { m_ListContainer.RemoveAt(index); if (m_SelectedLine >= m_ListContainer.childCount) { Select(m_ListContainer.childCount - 1); } } public VisualElement ItemAt(int index) { return m_ListContainer.ElementAt(index); } public int itemCount { get { return m_ListContainer.childCount; } } public virtual void OnAdd() { } void OnRemoveButton() { OnRemove(m_SelectedLine); } public virtual void OnRemove(int index) { } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type PlannerBucketsCollectionRequest. /// </summary> public partial class PlannerBucketsCollectionRequest : BaseRequest, IPlannerBucketsCollectionRequest { /// <summary> /// Constructs a new PlannerBucketsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public PlannerBucketsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified PlannerBucket to the collection via POST. /// </summary> /// <param name="plannerBucket">The PlannerBucket to add.</param> /// <returns>The created PlannerBucket.</returns> public System.Threading.Tasks.Task<PlannerBucket> AddAsync(PlannerBucket plannerBucket) { return this.AddAsync(plannerBucket, CancellationToken.None); } /// <summary> /// Adds the specified PlannerBucket to the collection via POST. /// </summary> /// <param name="plannerBucket">The PlannerBucket to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created PlannerBucket.</returns> public System.Threading.Tasks.Task<PlannerBucket> AddAsync(PlannerBucket plannerBucket, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<PlannerBucket>(plannerBucket, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IPlannerBucketsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IPlannerBucketsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<PlannerBucketsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest Expand(Expression<Func<PlannerBucket, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest Select(Expression<Func<PlannerBucket, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IPlannerBucketsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// DeflaterHuffman.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the DeflaterHuffman class. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of Deflate and SetInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class DeflaterHuffman { const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6); const int LITERAL_NUM = 286; // Number of distance codes const int DIST_NUM = 30; // Number of codes used to transfer bit lengths const int BITLEN_NUM = 19; // repeat previous bit length 3-6 times (2 bits of repeat count) const int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) const int REP_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) const int REP_11_138 = 18; const int EOF_SYMBOL = 256; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit length codes. static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static readonly byte[] bit4Reverse = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; static short[] staticLCodes; static byte[] staticLLength; static short[] staticDCodes; static byte[] staticDLength; class Tree { #region Instance Fields public short[] freqs; public byte[] length; public int minNumCodes; public int numCodes; short[] codes; int[] bl_counts; int maxLength; DeflaterHuffman dh; #endregion #region Constructors public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength) { this.dh = dh; this.minNumCodes = minCodes; this.maxLength = maxLength; freqs = new short[elems]; bl_counts = new int[maxLength]; } #endregion /// <summary> /// Resets the internal state of the tree /// </summary> public void Reset() { for (int i = 0; i < freqs.Length; i++) { freqs[i] = 0; } codes = null; length = null; } public void WriteSymbol(int code) { // if (DeflaterConstants.DEBUGGING) { // freqs[code]--; // // Console.Write("writeSymbol("+freqs.length+","+code+"): "); // } dh.pending.WriteBits(codes[code] & 0xffff, length[code]); } /// <summary> /// Check that all frequencies are zero /// </summary> /// <exception cref="SharpZipBaseException"> /// At least one frequency is non-zero /// </exception> public void CheckEmpty() { bool empty = true; for (int i = 0; i < freqs.Length; i++) { if (freqs[i] != 0) { //Console.WriteLine("freqs[" + i + "] == " + freqs[i]); empty = false; } } if (!empty) { throw new SharpZipBaseException("!Empty"); } } /// <summary> /// Set static codes and length /// </summary> /// <param name="staticCodes">new codes</param> /// <param name="staticLengths">length for new codes</param> public void SetStaticCodes(short[] staticCodes, byte[] staticLengths) { codes = staticCodes; length = staticLengths; } /// <summary> /// Build dynamic codes and lengths /// </summary> public void BuildCodes() { int numSymbols = freqs.Length; int[] nextCode = new int[maxLength]; int code = 0; codes = new short[freqs.Length]; // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("buildCodes: "+freqs.Length); // } for (int bits = 0; bits < maxLength; bits++) { nextCode[bits] = code; code += bl_counts[bits] << (15 - bits); // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits] // +" nextCode: "+code); // } } #if DebugDeflation if ( DeflaterConstants.DEBUGGING && (code != 65536) ) { throw new SharpZipBaseException("Inconsistent bl_counts!"); } #endif for (int i=0; i < numCodes; i++) { int bits = length[i]; if (bits > 0) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"), // +bits); // } codes[i] = BitReverse(nextCode[bits-1]); nextCode[bits-1] += 1 << (16 - bits); } } } public void BuildTree() { int numSymbols = freqs.Length; /* heap is a priority queue, sorted by frequency, least frequent * nodes first. The heap is a binary tree, with the property, that * the parent node is smaller than both child nodes. This assures * that the smallest node is the first parent. * * The binary tree is encoded in an array: 0 is root node and * the nodes 2*n+1, 2*n+2 are the child nodes of node n. */ int[] heap = new int[numSymbols]; int heapLen = 0; int maxCode = 0; for (int n = 0; n < numSymbols; n++) { int freq = freqs[n]; if (freq != 0) { // Insert n into heap int pos = heapLen++; int ppos; while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) { heap[pos] = heap[ppos]; pos = ppos; } heap[pos] = n; maxCode = n; } } /* We could encode a single literal with 0 bits but then we * don't see the literals. Therefore we force at least two * literals to avoid this case. We don't care about order in * this case, both literals get a 1 bit code. */ while (heapLen < 2) { int node = maxCode < 2 ? ++maxCode : 0; heap[heapLen++] = node; } numCodes = Math.Max(maxCode + 1, minNumCodes); int numLeafs = heapLen; int[] childs = new int[4 * heapLen - 2]; int[] values = new int[2 * heapLen - 1]; int numNodes = numLeafs; for (int i = 0; i < heapLen; i++) { int node = heap[i]; childs[2 * i] = node; childs[2 * i + 1] = -1; values[i] = freqs[node] << 8; heap[i] = i; } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ do { int first = heap[0]; int last = heap[--heapLen]; // Propagate the hole to the leafs of the heap int ppos = 0; int path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = path * 2 + 1; } /* Now propagate the last element down along path. Normally * it shouldn't go too deep. */ int lastVal = values[last]; while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; int second = heap[0]; // Create a new node father of first and second last = numNodes++; childs[2 * last] = first; childs[2 * last + 1] = second; int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff); values[last] = lastVal = values[first] + values[second] - mindepth + 1; // Again, propagate the hole to the leafs ppos = 0; path = 1; while (path < heapLen) { if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { path++; } heap[ppos] = heap[path]; ppos = path; path = ppos * 2 + 1; } // Now propagate the new element down along path while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { heap[path] = heap[ppos]; } heap[path] = last; } while (heapLen > 1); if (heap[0] != childs.Length / 2 - 1) { throw new SharpZipBaseException("Heap invariant violated"); } BuildLength(childs); } /// <summary> /// Get encoded length /// </summary> /// <returns>Encoded length, the sum of frequencies * lengths</returns> public int GetEncodedLength() { int len = 0; for (int i = 0; i < freqs.Length; i++) { len += freqs[i] * length[i]; } return len; } /// <summary> /// Scan a literal or distance tree to determine the frequencies of the codes /// in the bit length tree. /// </summary> public void CalcBLFreq(Tree blTree) { int max_count; /* max repeat count */ int min_count; /* min repeat count */ int count; /* repeat count of the current code */ int curlen = -1; /* length of current code */ int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.freqs[nextlen]++; count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { blTree.freqs[curlen] += (short)count; } else if (curlen != 0) { blTree.freqs[REP_3_6]++; } else if (count <= 10) { blTree.freqs[REP_3_10]++; } else { blTree.freqs[REP_11_138]++; } } } /// <summary> /// Write tree values /// </summary> /// <param name="blTree">Tree to write</param> public void WriteTree(Tree blTree) { int max_count; // max repeat count int min_count; // min repeat count int count; // repeat count of the current code int curlen = -1; // length of current code int i = 0; while (i < numCodes) { count = 1; int nextlen = length[i]; if (nextlen == 0) { max_count = 138; min_count = 3; } else { max_count = 6; min_count = 3; if (curlen != nextlen) { blTree.WriteSymbol(nextlen); count = 0; } } curlen = nextlen; i++; while (i < numCodes && curlen == length[i]) { i++; if (++count >= max_count) { break; } } if (count < min_count) { while (count-- > 0) { blTree.WriteSymbol(curlen); } } else if (curlen != 0) { blTree.WriteSymbol(REP_3_6); dh.pending.WriteBits(count - 3, 2); } else if (count <= 10) { blTree.WriteSymbol(REP_3_10); dh.pending.WriteBits(count - 3, 3); } else { blTree.WriteSymbol(REP_11_138); dh.pending.WriteBits(count - 11, 7); } } } void BuildLength(int[] childs) { this.length = new byte [freqs.Length]; int numNodes = childs.Length / 2; int numLeafs = (numNodes + 1) / 2; int overflow = 0; for (int i = 0; i < maxLength; i++) { bl_counts[i] = 0; } // First calculate optimal bit lengths int[] lengths = new int[numNodes]; lengths[numNodes-1] = 0; for (int i = numNodes - 1; i >= 0; i--) { if (childs[2 * i + 1] != -1) { int bitLength = lengths[i] + 1; if (bitLength > maxLength) { bitLength = maxLength; overflow++; } lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength; } else { // A leaf node int bitLength = lengths[i]; bl_counts[bitLength - 1]++; this.length[childs[2*i]] = (byte) lengths[i]; } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Tree "+freqs.Length+" lengths:"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } if (overflow == 0) { return; } int incrBitLen = maxLength - 1; do { // Find the first bit length which could increase: while (bl_counts[--incrBitLen] == 0) ; // Move this node one down and remove a corresponding // number of overflow nodes. do { bl_counts[incrBitLen]--; bl_counts[++incrBitLen]++; overflow -= 1 << (maxLength - 1 - incrBitLen); } while (overflow > 0 && incrBitLen < maxLength - 1); } while (overflow > 0); /* We may have overshot above. Move some nodes from maxLength to * maxLength-1 in that case. */ bl_counts[maxLength-1] += overflow; bl_counts[maxLength-2] -= overflow; /* Now recompute all bit lengths, scanning in increasing * frequency. It is simpler to reconstruct all lengths instead of * fixing only the wrong ones. This idea is taken from 'ar' * written by Haruhiko Okumura. * * The nodes were inserted with decreasing frequency into the childs * array. */ int nodePtr = 2 * numLeafs; for (int bits = maxLength; bits != 0; bits--) { int n = bl_counts[bits-1]; while (n > 0) { int childPtr = 2*childs[nodePtr++]; if (childs[childPtr + 1] == -1) { // We found another leaf length[childs[childPtr]] = (byte) bits; n--; } } } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("*** After overflow elimination. ***"); // for (int i=0; i < numLeafs; i++) { // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] // + " len: "+length[childs[2*i]]); // } // } } } #region Instance Fields /// <summary> /// Pending buffer to use /// </summary> public DeflaterPending pending; Tree literalTree; Tree distTree; Tree blTree; // Buffer for distances short[] d_buf; byte[] l_buf; int last_lit; int extra_bits; #endregion static DeflaterHuffman() { // See RFC 1951 3.2.6 // Literal codes staticLCodes = new short[LITERAL_NUM]; staticLLength = new byte[LITERAL_NUM]; int i = 0; while (i < 144) { staticLCodes[i] = BitReverse((0x030 + i) << 8); staticLLength[i++] = 8; } while (i < 256) { staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7); staticLLength[i++] = 9; } while (i < 280) { staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9); staticLLength[i++] = 7; } while (i < LITERAL_NUM) { staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8); staticLLength[i++] = 8; } // Distance codes staticDCodes = new short[DIST_NUM]; staticDLength = new byte[DIST_NUM]; for (i = 0; i < DIST_NUM; i++) { staticDCodes[i] = BitReverse(i << 11); staticDLength[i] = 5; } } /// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending">Pending buffer to use</param> public DeflaterHuffman(DeflaterPending pending) { this.pending = pending; literalTree = new Tree(this, LITERAL_NUM, 257, 15); distTree = new Tree(this, DIST_NUM, 1, 15); blTree = new Tree(this, BITLEN_NUM, 4, 7); d_buf = new short[BUFSIZE]; l_buf = new byte [BUFSIZE]; } /// <summary> /// Reset internal state /// </summary> public void Reset() { last_lit = 0; extra_bits = 0; literalTree.Reset(); distTree.Reset(); blTree.Reset(); } /// <summary> /// Write all trees to pending buffer /// </summary> public void SendAllTrees(int blTreeCodes) { blTree.BuildCodes(); literalTree.BuildCodes(); distTree.BuildCodes(); pending.WriteBits(literalTree.numCodes - 257, 5); pending.WriteBits(distTree.numCodes - 1, 5); pending.WriteBits(blTreeCodes - 4, 4); for (int rank = 0; rank < blTreeCodes; rank++) { pending.WriteBits(blTree.length[BL_ORDER[rank]], 3); } literalTree.WriteTree(blTree); distTree.WriteTree(blTree); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { blTree.CheckEmpty(); } #endif } /// <summary> /// Compress current buffer writing data to pending buffer /// </summary> public void CompressBlock() { for (int i = 0; i < last_lit; i++) { int litlen = l_buf[i] & 0xff; int dist = d_buf[i]; if (dist-- != 0) { // if (DeflaterConstants.DEBUGGING) { // Console.Write("["+(dist+1)+","+(litlen+3)+"]: "); // } int lc = Lcode(litlen); literalTree.WriteSymbol(lc); int bits = (lc - 261) / 4; if (bits > 0 && bits <= 5) { pending.WriteBits(litlen & ((1 << bits) - 1), bits); } int dc = Dcode(dist); distTree.WriteSymbol(dc); bits = dc / 2 - 1; if (bits > 0) { pending.WriteBits(dist & ((1 << bits) - 1), bits); } } else { // if (DeflaterConstants.DEBUGGING) { // if (litlen > 32 && litlen < 127) { // Console.Write("("+(char)litlen+"): "); // } else { // Console.Write("{"+litlen+"}: "); // } // } literalTree.WriteSymbol(litlen); } } #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.Write("EOF: "); } #endif literalTree.WriteSymbol(EOF_SYMBOL); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { literalTree.CheckEmpty(); distTree.CheckEmpty(); } #endif } /// <summary> /// Flush block to output with no compression /// </summary> /// <param name="stored">Data to write</param> /// <param name="storedOffset">Index of first byte to write</param> /// <param name="storedLength">Count of bytes to write</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { #if DebugDeflation // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Flushing stored block "+ storedLength); // } #endif pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3); pending.AlignToByte(); pending.WriteShort(storedLength); pending.WriteShort(~storedLength); pending.WriteBlock(stored, storedOffset, storedLength); Reset(); } /// <summary> /// Flush block to output with compression /// </summary> /// <param name="stored">Data to flush</param> /// <param name="storedOffset">Index of first byte to flush</param> /// <param name="storedLength">Count of bytes to flush</param> /// <param name="lastBlock">True if this is the last block</param> public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { literalTree.freqs[EOF_SYMBOL]++; // Build trees literalTree.BuildTree(); distTree.BuildTree(); // Calculate bitlen frequency literalTree.CalcBLFreq(blTree); distTree.CalcBLFreq(blTree); // Build bitlen tree blTree.BuildTree(); int blTreeCodes = 4; for (int i = 18; i > blTreeCodes; i--) { if (blTree.length[BL_ORDER[i]] > 0) { blTreeCodes = i+1; } } int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() + literalTree.GetEncodedLength() + distTree.GetEncodedLength() + extra_bits; int static_len = extra_bits; for (int i = 0; i < LITERAL_NUM; i++) { static_len += literalTree.freqs[i] * staticLLength[i]; } for (int i = 0; i < DIST_NUM; i++) { static_len += distTree.freqs[i] * staticDLength[i]; } if (opt_len >= static_len) { // Force static trees opt_len = static_len; } if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) { // Store Block // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len // + " <= " + static_len); // } FlushStoredBlock(stored, storedOffset, storedLength, lastBlock); } else if (opt_len == static_len) { // Encode with static tree pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3); literalTree.SetStaticCodes(staticLCodes, staticLLength); distTree.SetStaticCodes(staticDCodes, staticDLength); CompressBlock(); Reset(); } else { // Encode with dynamic tree pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3); SendAllTrees(blTreeCodes); CompressBlock(); Reset(); } } /// <summary> /// Get value indicating if internal buffer is full /// </summary> /// <returns>true if buffer is full</returns> public bool IsFull() { return last_lit >= BUFSIZE; } /// <summary> /// Add literal to buffer /// </summary> /// <param name="literal">Literal value to add to buffer.</param> /// <returns>Value indicating internal buffer is full</returns> public bool TallyLit(int literal) { // if (DeflaterConstants.DEBUGGING) { // if (lit > 32 && lit < 127) { // //Console.WriteLine("("+(char)lit+")"); // } else { // //Console.WriteLine("{"+lit+"}"); // } // } d_buf[last_lit] = 0; l_buf[last_lit++] = (byte)literal; literalTree.freqs[literal]++; return IsFull(); } /// <summary> /// Add distance code and length to literal and distance trees /// </summary> /// <param name="distance">Distance code</param> /// <param name="length">Length</param> /// <returns>Value indicating if internal buffer is full</returns> public bool TallyDist(int distance, int length) { // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("[" + distance + "," + length + "]"); // } d_buf[last_lit] = (short)distance; l_buf[last_lit++] = (byte)(length - 3); int lc = Lcode(length - 3); literalTree.freqs[lc]++; if (lc >= 265 && lc < 285) { extra_bits += (lc - 261) / 4; } int dc = Dcode(distance - 1); distTree.freqs[dc]++; if (dc >= 4) { extra_bits += dc / 2 - 1; } return IsFull(); } /// <summary> /// Reverse the bits of a 16 bit value. /// </summary> /// <param name="toReverse">Value to reverse bits</param> /// <returns>Value with bits reversed</returns> public static short BitReverse(int toReverse) { return (short) (bit4Reverse[toReverse & 0xF] << 12 | bit4Reverse[(toReverse >> 4) & 0xF] << 8 | bit4Reverse[(toReverse >> 8) & 0xF] << 4 | bit4Reverse[toReverse >> 12]); } static int Lcode(int length) { if (length == 255) { return 285; } int code = 257; while (length >= 8) { code += 4; length >>= 1; } return code + length; } static int Dcode(int distance) { int code = 0; while (distance >= 4) { code += 2; distance >>= 1; } return code + distance; } } }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.X509 { /// <summary>An implementation of a version 2 X.509 Attribute Certificate.</summary> public class X509V2AttributeCertificate : X509ExtensionBase, IX509AttributeCertificate { private readonly AttributeCertificate cert; private readonly DateTime notBefore; private readonly DateTime notAfter; private static AttributeCertificate GetObject(Stream input) { try { return AttributeCertificate.GetInstance(Asn1Object.FromStream(input)); } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("exception decoding certificate structure", e); } } public X509V2AttributeCertificate( Stream encIn) : this(GetObject(encIn)) { } public X509V2AttributeCertificate( byte[] encoded) : this(new MemoryStream(encoded, false)) { } internal X509V2AttributeCertificate( AttributeCertificate cert) { this.cert = cert; try { this.notAfter = cert.ACInfo.AttrCertValidityPeriod.NotAfterTime.ToDateTime(); this.notBefore = cert.ACInfo.AttrCertValidityPeriod.NotBeforeTime.ToDateTime(); } catch (Exception e) { throw new IOException("invalid data structure in certificate!", e); } } public virtual int Version { get { return cert.ACInfo.Version.Value.IntValue + 1; } } public virtual IBigInteger SerialNumber { get { return cert.ACInfo.SerialNumber.Value; } } public virtual AttributeCertificateHolder Holder { get { return new AttributeCertificateHolder((Asn1Sequence)cert.ACInfo.Holder.ToAsn1Object()); } } public virtual AttributeCertificateIssuer Issuer { get { return new AttributeCertificateIssuer(cert.ACInfo.Issuer); } } public virtual DateTime NotBefore { get { return notBefore; } } public virtual DateTime NotAfter { get { return notAfter; } } public virtual bool[] GetIssuerUniqueID() { DerBitString id = cert.ACInfo.IssuerUniqueID; if (id != null) { byte[] bytes = id.GetBytes(); bool[] boolId = new bool[bytes.Length * 8 - id.PadBits]; for (int i = 0; i != boolId.Length; i++) { //boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0; boolId[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0; } return boolId; } return null; } public virtual bool IsValidNow { get { return IsValid(DateTime.UtcNow); } } public virtual bool IsValid( DateTime date) { return date.CompareTo(NotBefore) >= 0 && date.CompareTo(NotAfter) <= 0; } public virtual void CheckValidity() { this.CheckValidity(DateTime.UtcNow); } public virtual void CheckValidity( DateTime date) { if (date.CompareTo(NotAfter) > 0) throw new CertificateExpiredException("certificate expired on " + NotAfter); if (date.CompareTo(NotBefore) < 0) throw new CertificateNotYetValidException("certificate not valid until " + NotBefore); } public virtual byte[] GetSignature() { return cert.SignatureValue.GetBytes(); } public virtual void Verify( IAsymmetricKeyParameter publicKey) { if (!cert.SignatureAlgorithm.Equals(cert.ACInfo.Signature)) { throw new CertificateException("Signature algorithm in certificate info not same as outer certificate"); } ISigner signature = SignerUtilities.GetSigner(cert.SignatureAlgorithm.ObjectID.Id); signature.Init(false, publicKey); try { byte[] b = cert.ACInfo.GetEncoded(); signature.BlockUpdate(b, 0, b.Length); } catch (IOException e) { throw new SignatureException("Exception encoding certificate info object", e); } if (!signature.VerifySignature(this.GetSignature())) { throw new InvalidKeyException("Public key presented not for certificate signature"); } } public virtual byte[] GetEncoded() { return cert.GetEncoded(); } protected override X509Extensions GetX509Extensions() { return cert.ACInfo.Extensions; } public virtual X509Attribute[] GetAttributes() { Asn1Sequence seq = cert.ACInfo.Attributes; X509Attribute[] attrs = new X509Attribute[seq.Count]; for (int i = 0; i != seq.Count; i++) { attrs[i] = new X509Attribute((Asn1Encodable)seq[i]); } return attrs; } public virtual X509Attribute[] GetAttributes( string oid) { Asn1Sequence seq = cert.ACInfo.Attributes; IList list = Platform.CreateArrayList(); for (int i = 0; i != seq.Count; i++) { X509Attribute attr = new X509Attribute((Asn1Encodable)seq[i]); if (attr.Oid.Equals(oid)) { list.Add(attr); } } if (list.Count < 1) { return null; } X509Attribute[] result = new X509Attribute[list.Count]; for (int i = 0; i < list.Count; ++i) { result[i] = (X509Attribute)list[i]; } return result; } public override bool Equals( object obj) { if (obj == this) return true; X509V2AttributeCertificate other = obj as X509V2AttributeCertificate; if (other == null) return false; return cert.Equals(other.cert); // NB: May prefer this implementation of Equals if more than one certificate implementation in play //return Arrays.AreEqual(this.GetEncoded(), other.GetEncoded()); } public override int GetHashCode() { return cert.GetHashCode(); } } }
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="GlobalLB.RuleBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBRuleRuleDefinition))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(GlobalLBRuleRuleStatistics))] public partial class GlobalLBRule : iControlInterface { public GlobalLBRule() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void add_metadata( string [] rule_names, string [] [] names, string [] [] values ) { this.Invoke("add_metadata", new object [] { rule_names, names, values}); } public System.IAsyncResult Beginadd_metadata(string [] rule_names,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_metadata", new object[] { rule_names, names, values}, callback, asyncState); } public void Endadd_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void create( GlobalLBRuleRuleDefinition [] rules ) { this.Invoke("create", new object [] { rules}); } public System.IAsyncResult Begincreate(GlobalLBRuleRuleDefinition [] rules, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { rules}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_rules //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void delete_all_rules( ) { this.Invoke("delete_all_rules", new object [0]); } public System.IAsyncResult Begindelete_all_rules(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_rules", new object[0], callback, asyncState); } public void Enddelete_all_rules(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void delete_rule( string [] rule_names ) { this.Invoke("delete_rule", new object [] { rule_names}); } public System.IAsyncResult Begindelete_rule(string [] rule_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_rule", new object[] { rule_names}, callback, asyncState); } public void Enddelete_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBRuleRuleStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((GlobalLBRuleRuleStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public GlobalLBRuleRuleStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBRuleRuleStatistics)(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [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_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_metadata( string [] rule_names ) { object [] results = this.Invoke("get_metadata", new object [] { rule_names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_metadata(string [] rule_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata", new object[] { rule_names}, callback, asyncState); } public string [] [] Endget_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_metadata_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_metadata_description( string [] rule_names, string [] [] names ) { object [] results = this.Invoke("get_metadata_description", new object [] { rule_names, names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_metadata_description(string [] rule_names,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata_description", new object[] { rule_names, names}, callback, asyncState); } public string [] [] Endget_metadata_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_metadata_persistence //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonMetadataPersistence [] [] get_metadata_persistence( string [] rule_names, string [] [] names ) { object [] results = this.Invoke("get_metadata_persistence", new object [] { rule_names, names}); return ((CommonMetadataPersistence [] [])(results[0])); } public System.IAsyncResult Beginget_metadata_persistence(string [] rule_names,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata_persistence", new object[] { rule_names, names}, callback, asyncState); } public CommonMetadataPersistence [] [] Endget_metadata_persistence(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonMetadataPersistence [] [])(results[0])); } //----------------------------------------------------------------------- // get_metadata_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_metadata_value( string [] rule_names, string [] [] names ) { object [] results = this.Invoke("get_metadata_value", new object [] { rule_names, names}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_metadata_value(string [] rule_names,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_metadata_value", new object[] { rule_names, names}, callback, asyncState); } public string [] [] Endget_metadata_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBRuleRuleStatistics get_statistics( string [] rule_names ) { object [] results = this.Invoke("get_statistics", new object [] { rule_names}); return ((GlobalLBRuleRuleStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] rule_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { rule_names}, callback, asyncState); } public GlobalLBRuleRuleStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBRuleRuleStatistics)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [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])); } //----------------------------------------------------------------------- // modify_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void modify_rule( GlobalLBRuleRuleDefinition [] rules ) { this.Invoke("modify_rule", new object [] { rules}); } public System.IAsyncResult Beginmodify_rule(GlobalLBRuleRuleDefinition [] rules, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("modify_rule", new object[] { rules}, callback, asyncState); } public void Endmodify_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // query_all_rules //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBRuleRuleDefinition [] query_all_rules( ) { object [] results = this.Invoke("query_all_rules", new object [0]); return ((GlobalLBRuleRuleDefinition [])(results[0])); } public System.IAsyncResult Beginquery_all_rules(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("query_all_rules", new object[0], callback, asyncState); } public GlobalLBRuleRuleDefinition [] Endquery_all_rules(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBRuleRuleDefinition [])(results[0])); } //----------------------------------------------------------------------- // query_rule //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public GlobalLBRuleRuleDefinition [] query_rule( string [] rule_names ) { object [] results = this.Invoke("query_rule", new object [] { rule_names}); return ((GlobalLBRuleRuleDefinition [])(results[0])); } public System.IAsyncResult Beginquery_rule(string [] rule_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("query_rule", new object[] { rule_names}, callback, asyncState); } public GlobalLBRuleRuleDefinition [] Endquery_rule(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((GlobalLBRuleRuleDefinition [])(results[0])); } //----------------------------------------------------------------------- // remove_all_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void remove_all_metadata( string [] rule_names ) { this.Invoke("remove_all_metadata", new object [] { rule_names}); } public System.IAsyncResult Beginremove_all_metadata(string [] rule_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_metadata", new object[] { rule_names}, callback, asyncState); } public void Endremove_all_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_metadata //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void remove_metadata( string [] rule_names, string [] [] names ) { this.Invoke("remove_metadata", new object [] { rule_names, names}); } public System.IAsyncResult Beginremove_metadata(string [] rule_names,string [] [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_metadata", new object[] { rule_names, names}, callback, asyncState); } public void Endremove_metadata(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void reset_statistics( string [] rule_names ) { this.Invoke("reset_statistics", new object [] { rule_names}); } public System.IAsyncResult Beginreset_statistics(string [] rule_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { rule_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_metadata_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void set_metadata_description( string [] rule_names, string [] [] names, string [] [] descriptions ) { this.Invoke("set_metadata_description", new object [] { rule_names, names, descriptions}); } public System.IAsyncResult Beginset_metadata_description(string [] rule_names,string [] [] names,string [] [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_metadata_description", new object[] { rule_names, names, descriptions}, callback, asyncState); } public void Endset_metadata_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_metadata_persistence //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void set_metadata_persistence( string [] rule_names, string [] [] names, CommonMetadataPersistence [] [] values ) { this.Invoke("set_metadata_persistence", new object [] { rule_names, names, values}); } public System.IAsyncResult Beginset_metadata_persistence(string [] rule_names,string [] [] names,CommonMetadataPersistence [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_metadata_persistence", new object[] { rule_names, names, values}, callback, asyncState); } public void Endset_metadata_persistence(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_metadata_value //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:GlobalLB/Rule", RequestNamespace="urn:iControl:GlobalLB/Rule", ResponseNamespace="urn:iControl:GlobalLB/Rule")] public void set_metadata_value( string [] rule_names, string [] [] names, string [] [] values ) { this.Invoke("set_metadata_value", new object [] { rule_names, names, values}); } public System.IAsyncResult Beginset_metadata_value(string [] rule_names,string [] [] names,string [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_metadata_value", new object[] { rule_names, names, values}, callback, asyncState); } public void Endset_metadata_value(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Rule.RuleDefinition", Namespace = "urn:iControl")] public partial class GlobalLBRuleRuleDefinition { private string rule_nameField; public string rule_name { get { return this.rule_nameField; } set { this.rule_nameField = value; } } private string rule_definitionField; public string rule_definition { get { return this.rule_definitionField; } set { this.rule_definitionField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Rule.RuleStatisticEntry", Namespace = "urn:iControl")] public partial class GlobalLBRuleRuleStatisticEntry { private string rule_nameField; public string rule_name { get { return this.rule_nameField; } set { this.rule_nameField = value; } } private string event_nameField; public string event_name { get { return this.event_nameField; } set { this.event_nameField = value; } } private long priorityField; public long priority { get { return this.priorityField; } set { this.priorityField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "GlobalLB.Rule.RuleStatistics", Namespace = "urn:iControl")] public partial class GlobalLBRuleRuleStatistics { private GlobalLBRuleRuleStatisticEntry [] statisticsField; public GlobalLBRuleRuleStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Linq.Expressions.Compiler; using System.Reflection; using System.Threading; using System.Runtime.CompilerServices; using System.Linq.Expressions; namespace System.Linq.Expressions { /// <summary> /// Creates a <see cref="LambdaExpression"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> [DebuggerTypeProxy(typeof(Expression.LambdaExpressionProxy))] public abstract class LambdaExpression : Expression { private readonly string _name; private readonly Expression _body; private readonly ReadOnlyCollection<ParameterExpression> _parameters; private readonly Type _delegateType; private readonly bool _tailCall; internal LambdaExpression( Type delegateType, string name, Expression body, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters ) { Debug.Assert(delegateType != null); _name = name; _body = body; _parameters = parameters; _delegateType = delegateType; _tailCall = tailCall; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _delegateType; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Lambda; } } /// <summary> /// Gets the parameters of the lambda expression. /// </summary> public ReadOnlyCollection<ParameterExpression> Parameters { get { return _parameters; } } /// <summary> /// Gets the name of the lambda expression. /// </summary> /// <remarks>Used for debugging purposes.</remarks> public string Name { get { return _name; } } /// <summary> /// Gets the body of the lambda expression. /// </summary> public Expression Body { get { return _body; } } /// <summary> /// Gets the return type of the lambda expression. /// </summary> public Type ReturnType { get { return Type.GetMethod("Invoke").ReturnType; } } /// <summary> /// Gets the value that indicates if the lambda expression will be compiled with /// tail call optimization. /// </summary> public bool TailCall { get { return _tailCall; } } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile() { #if FEATURE_CORECLR return Compiler.LambdaCompiler.Compile(this); #else return new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } #if FEATURE_CORECLR internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller); #endif } /// <summary> /// Defines a <see cref="Expression{TDelegate}"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <typeparam name="TDelegate">The type of the delegate.</typeparam> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> public sealed class Expression<TDelegate> : LambdaExpression { public Expression(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) : base(typeof(TDelegate), name, body, tailCall, parameters) { } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile() { #if FEATURE_CORECLR return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this); #else return (TDelegate)(object)new System.Linq.Expressions.Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="LambdaExpression.Body">Body</see> property of the result.</param> /// <param name="parameters">The <see cref="LambdaExpression.Parameters">Parameters</see> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters) { if (body == Body && parameters == Parameters) { return this; } return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters); } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitLambda(this); } #if FEATURE_CORECLR internal override LambdaExpression Accept(Compiler.StackSpiller spiller) { return spiller.Rewrite(this); } internal static LambdaExpression Create(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { return new Expression<TDelegate>(body, name, tailCall, parameters); } #endif } #if !FEATURE_CORECLR // Seperate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T> public class ExpressionCreator<TDelegate> { public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { return new Expression<TDelegate>(body, name, tailCall, parameters); } } #endif public partial class Expression { /// <summary> /// Creates an Expression{T} given the delegate type. Caches the /// factory method to speed up repeated creations for the same T. /// </summary> internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { // Get or create a delegate to the public Expression.Lambda<T> // method and call that will be used for creating instances of this // delegate type Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath; var factories = s_lambdaFactories; if (factories == null) { s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50); } MethodInfo create = null; if (!factories.TryGetValue(delegateType, out fastPath)) { #if FEATURE_CORECLR create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic); #else create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public); #endif if (TypeUtils.CanCache(delegateType)) { factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)); } } if (fastPath != null) { return fastPath(body, name, tailCall, parameters); } Debug.Assert(create != null); return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters }); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, tailCall, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, name, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type. </typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="P:NodeType"/> property equal to <see cref="P:Lambda"/> and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, String name, bool tailCall, IEnumerable<ParameterExpression> parameters) { var parameterList = parameters.ToReadOnly(); ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList); return new Expression<TDelegate>(body, name, tailCall, parameterList); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters) { return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, tailCall, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda(body, name, false, parameters); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ContractUtils.RequiresNotNull(body, "body"); var parameterList = parameters.ToReadOnly(); int paramCount = parameterList.Count; Type[] typeArgs = new Type[paramCount + 1]; if (paramCount > 0) { var set = new Set<ParameterExpression>(parameterList.Count); for (int i = 0; i < paramCount; i++) { var param = parameterList[i]; ContractUtils.RequiresNotNull(param, "parameter"); typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type; if (set.Contains(param)) { throw Error.DuplicateVariable(param); } set.Add(param); } } typeArgs[paramCount] = body.Type; Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs); return CreateLambda(delegateType, body, name, tailCall, parameterList); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters) { var paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList); return CreateLambda(delegateType, body, name, false, paramList); } /// <summary> /// Creates a LambdaExpression by first constructing a delegate type. /// </summary> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <param name="body">An <see cref="Expression"/> to set the <see cref="P:Body"/> property equal to. </param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="Boolean"/> that indicates if tail call optimization will be applied when compiling the created expression. </param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="P:Parameters"/> collection. </param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="P:NodeType"/> property equal to Lambda and the <see cref="P:Body"/> and <see cref="P:Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { var paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList); return CreateLambda(delegateType, body, name, tailCall, paramList); } private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters) { ContractUtils.RequiresNotNull(delegateType, "delegateType"); RequiresCanRead(body, "body"); if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) { throw Error.LambdaTypeMustBeDerivedFromSystemDelegate(); } MethodInfo mi; var ldc = s_lambdaDelegateCache; if (!ldc.TryGetValue(delegateType, out mi)) { mi = delegateType.GetMethod("Invoke"); if (TypeUtils.CanCache(delegateType)) { ldc[delegateType] = mi; } } ParameterInfo[] pis = mi.GetParametersCached(); if (pis.Length > 0) { if (pis.Length != parameters.Count) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } var set = new Set<ParameterExpression>(pis.Length); for (int i = 0, n = pis.Length; i < n; i++) { ParameterExpression pex = parameters[i]; ParameterInfo pi = pis[i]; RequiresCanRead(pex, "parameters"); Type pType = pi.ParameterType; if (pex.IsByRef) { if (!pType.IsByRef) { //We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type. throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType); } pType = pType.GetElementType(); } if (!TypeUtils.AreReferenceAssignable(pex.Type, pType)) { throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType); } if (set.Contains(pex)) { throw Error.DuplicateVariable(pex); } set.Add(pex); } } else if (parameters.Count > 0) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type)) { if (!TryQuote(mi.ReturnType, ref body)) { throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType); } } } private static bool ValidateTryGetFuncActionArgs(Type[] typeArgs) { if (typeArgs == null) { throw new ArgumentNullException("typeArgs"); } for (int i = 0, n = typeArgs.Length; i < n; i++) { var a = typeArgs[i]; if (a == null) { throw new ArgumentNullException("typeArgs"); } if (a.IsByRef) { return false; } } return true; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param> /// <returns>The type of a System.Func delegate that has the specified type arguments.</returns> public static Type GetFuncType(params Type[] typeArgs) { if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef(); Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForFunc(); } return result; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Func delegate type.</param> /// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetFuncType(Type[] typeArgs, out Type funcType) { if (ValidateTryGetFuncActionArgs(typeArgs)) { return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null; } funcType = null; return false; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param> /// <returns>The type of a System.Action delegate that has the specified type arguments.</returns> public static Type GetActionType(params Type[] typeArgs) { if (!ValidateTryGetFuncActionArgs(typeArgs)) throw Error.TypeMustNotBeByRef(); Type result = Compiler.DelegateHelpers.GetActionType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForAction(); } return result; } /// <summary> /// Creates a <see cref="Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of Type objects that specify the type arguments for the System.Action delegate type.</param> /// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetActionType(Type[] typeArgs, out Type actionType) { if (ValidateTryGetFuncActionArgs(typeArgs)) { return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null; } actionType = null; return false; } /// <summary> /// Gets a <see cref="Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments. /// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom /// delegate type. /// </summary> /// <param name="typeArgs">The type arguments of the delegate.</param> /// <returns>The delegate type.</returns> /// <remarks> /// As with Func, the last argument is the return type. It can be set /// to System.Void to produce an Action.</remarks> public static Type GetDelegateType(params Type[] typeArgs) { ContractUtils.RequiresNotEmpty(typeArgs, "typeArgs"); ContractUtils.RequiresNotNullItems(typeArgs, "typeArgs"); return Compiler.DelegateHelpers.MakeDelegateType(typeArgs); } } }
using System; using System.Text; using System.Linq; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using System.IO.Compression; using System.Threading; using System.Net; namespace pikoboard { class crawler_runner { public static void run() { bool running = true; var @crawler = new crawler(); @crawler.changed += () => { if (@crawler.pending == 0) running = false; else running = true; }; @crawler.crawl(); while (running) Thread.Sleep(1000); Console.WriteLine("Finished downloading."); } } class crawler { private const string user_agent_file = "useragent.config"; private const string downloaded_file = "downloaded.txt"; private const string places_file = "places.txt"; private const string img_pattern = "href=\"[:A-Za-z0-9/\\-\\.]*\\.jpe?g\""; private int _pending = 0; public int pending { get { return _pending; } set { if (value < 0) value = 0; _pending = value; changed(); } } public event Action changed = delegate {}; List<string> places; readonly HashSet<string> downloaded; readonly WebHeaderCollection headers; void check_places() { if (File.Exists(places_file)) places = new List<string>(File.ReadAllLines(places_file)); else { File.WriteAllText(places_file, "# put urls to threads here, each at new line:\n"); places = new List<string>(); } } public crawler() { try { if (!File.Exists(user_agent_file)) File.WriteAllText(user_agent_file, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36"); string user_agent = File.ReadAllLines(user_agent_file).First(l => !l.StartsWith("#")).Trim(); headers = new WebHeaderCollection(); headers[HttpRequestHeader.UserAgent] = user_agent; headers[HttpRequestHeader.Accept] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; headers[HttpRequestHeader.AcceptLanguage] = "en-US,en;q=0.8"; headers[HttpRequestHeader.CacheControl] = "max-age=0"; if (File.Exists(downloaded_file)) downloaded = new HashSet<string>(File.ReadAllLines(downloaded_file)); else downloaded = new HashSet<string>(); check_places(); } catch (Exception e) { Console.WriteLine("Error while creating crawler:\n" + e.Message); } } public void crawl() { try { check_places(); bool empty = true; foreach (string place in places) { if (!place.StartsWith("#")) { empty = false; parse_text(place); } } if (empty) pending = 0; } catch (Exception e) { Console.WriteLine("Error while parsing from places.txt:\n" + e.Message); } } private static void add_proxy(WebClient client) { if (File.Exists("proxy.txt")) { var url = File.ReadAllText("proxy.txt"); WebProxy proxy = new WebProxy(); proxy.Address = new Uri(url); proxy.BypassProxyOnLocal = true; client.Proxy = proxy; } } private void parse_text(string address) { var client = new WebClient(); add_proxy(client); client.Headers = headers; client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => { Console.WriteLine("Finished: " + address); string image_url = ""; try { string text = Encoding.UTF8.GetString(e.Result); string host = Regex.Match(address, "https?://[A-z\\.0-9-]*").Value; var images = Regex.Matches(text, img_pattern); foreach (Match im in images) { image_url = im.Value.Replace("href=", "").Trim('"'); if (!(image_url.Contains("http://") || image_url.Contains("https://"))) image_url = host + image_url; parse_image(image_url); } } catch (Exception ex) { Console.WriteLine("Error:" + image_url); if (e.Error != null) Console.WriteLine(e.Error.Message); Console.WriteLine(ex.Message); } pending -= 1; }; pending += 1; Console.WriteLine("Starting download: " + address); client.DownloadDataAsync(new Uri(address)); } private void parse_image(string address) { if (downloaded.Contains(address)) return; downloaded.Add(address); try { File.AppendAllText(downloaded_file, address + "\n"); } catch { System.Threading.Thread.Sleep(1000); try { File.AppendAllText(downloaded_file, address + "\n"); } catch (Exception e) { Console.WriteLine("downloaded.txt appending error:\n" + e.Message); } } var client = new WebClient(); add_proxy(client); client.Headers = headers; client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => { pending -= 1; try { utils.mkdir("temp"); utils.mkdir(app.download_dir); var name = Guid.NewGuid().ToString().Trim('{', '}'); File.WriteAllBytes("temp" + app.slash + name, e.Result); File.Move("temp" + app.slash + name, app.download_dir + app.slash + name); GC.Collect(); Console.WriteLine("Downloaded: " + address); } catch (Exception ex) { Console.WriteLine("Error: " + address); if (e.Error != null) Console.WriteLine(e.Error.Message); Console.WriteLine(ex.Message); } }; pending += 1; Console.WriteLine("Starting download: " + address); client.DownloadDataAsync(new Uri(address)); } } abstract class piko_entry { public abstract string hash { get; } public abstract byte[] serialized { get; } } class hasher { public static string calc(string msg) { return calc(msg.bytes()); } public static string calc(byte[] bytes) { bytes = new System.Security.Cryptography.SHA256Cng().ComputeHash(bytes); return bytes.Take(16).Aggregate("", (str, b) => str + b.ToString("x2")); } } class piko_post : piko_entry { public override byte[] serialized { get { return (thread + message).bytes(); } } public override string hash { get { return hasher.calc(thread + message); } } public string thread; public string message; public piko_post() {} public piko_post(string post) { thread = post.Substring(0, 32); message = post.Substring(32); } } class piko_file : piko_entry { public override byte[] serialized { get { return bytes; } } public byte[] bytes; public override string hash { get { return hasher.calc(bytes); } } } class piko { public static piko_entry[] read(byte[] bytes) { if (bytes == null || bytes.Length == 0) return new piko_entry[0]; var list = new List<piko_entry>(); for (int i = 0; i < bytes.Length; i++) { if (bytes[i] == 'E') break; bool is_post = bytes[i] == 'P'; i += 1; int len = BitConverter.ToInt32(bytes, i); if (len < 0 || i + len > bytes.Length) return new piko_entry[0]; i += 4; var slice = new byte[len]; for (int x = 0; x < len; x++) slice[x] = bytes[i + x]; i += len - 1; if (is_post) { var content = slice.utf8(); if (content.Length <= app.max_post_size && Regex.IsMatch(content, "^[a-f0-9]{32}.*")) list.Add(new piko_post(content)); } else list.Add(new piko_file { bytes = slice }); } return list.ToArray(); } public static byte[] write(piko_entry[] entries) { var bytes = new List<byte>(); foreach (var entry in entries) { bytes.Add(entry is piko_file ? (byte)'F' : (byte)'P'); var serialized = entry.serialized; bytes.AddRange(BitConverter.GetBytes(serialized.Length)); bytes.AddRange(serialized); } bytes.Add((byte)'E'); return bytes.ToArray(); } } static class gzip { public static void copy(this Stream input, Stream output) { byte[] buffer = new byte[16384]; int bytes_read; while ((bytes_read = input.Read(buffer, 0, buffer.Length)) > 0) output.Write(buffer, 0, bytes_read); } public static byte[] zip(byte[] input) { try { using (var output = new MemoryStream()) { using (var gz = new GZipStream(output, CompressionMode.Compress)) using (var ms = new MemoryStream(input)) ms.CopyTo(gz); return output.ToArray(); } } catch { return null; } } public static byte[] unzip(byte[] input) { try { using (var output = new MemoryStream()) { using (var ms = new MemoryStream(input)) using (var gz = new GZipStream(ms, CompressionMode.Decompress)) gz.CopyTo(output); return output.ToArray(); } } catch { return null; } } } static class utils { public static void mkdir(string dir) { if (Directory.Exists(dir)) return; Directory.CreateDirectory(dir); } public static string[] files(string dir) { return Directory.GetFiles(dir); } public static void write(string path, byte[] bytes) { File.WriteAllBytes(path, bytes); } public static byte[] read(string path) { return File.ReadAllBytes(path); } public static string utf8(this byte[] bytes) { return Encoding.UTF8.GetString(bytes); } public static byte[] bytes(this string str) { return Encoding.UTF8.GetBytes(str); } public static List<piko_entry> get_refs(string text) { var list = new List<piko_entry>(); var refs = Regex.Matches(text, "\\[ref=[a-f0-9]{32}\\]"); foreach (Match r in refs) { var hash = r.Value.Substring(5, 32); if (File.Exists(app.files_dir + app.slash + hash)) list.Add(new piko_file { bytes = utils.read(app.files_dir + app.slash + hash) }); } return list; } public static void random_pack(List<piko_entry> entries, string uploadName) { var containers = utils.files(app.containers_dir); var container = containers[new Random().Next(containers.Length)]; jpg.hide(container, uploadName, piko.write(entries.ToArray())); } public static piko_entry[] unpack(string jpeg) { try { return piko.read(jpg.extract(jpeg)); } catch { } return new piko_entry[0]; } } class jpg { public static void hide(string input, string output, byte[] data) { data = gzip.zip(data); var jpeg = utils.read(input); var list = new List<byte>(); list.AddRange(jpeg); list.AddRange(data); list.AddRange(BitConverter.GetBytes((int)data.Length)); utils.write(output, list.ToArray()); } public static byte[] extract(string input) { var bytes = utils.read(input); int len = BitConverter.ToInt32(bytes, bytes.Length - 4); if (len >= bytes.Length - 4 || len < 0) return null; var res = new byte[len]; for (int i = bytes.Length - len - 4; i < bytes.Length - 4; i++) { res[i - (bytes.Length - len - 4)] = bytes[i]; } return gzip.unzip(res); } } class css { public const string style = @"g { color: #888; font-style: italic; font-size: 75%; } .post { background-color: #ddd; border: 1px solid #aaa; border-radius: .4em; margin: .4em 0; max-width: 600px; margin-right: auto; } .post:not(:first-child) { margin-left: 20px; } body { background: #eee; font-size: 14px; font-family: Helvetica; } textarea { width: 300px; height: 100px; font-size: 12px; } a { text-decoration: none; color: darkorange; } img { max-width: 150px; transition: max-width 1s ease-in-out; -moz-transition: max-width 1s ease-in-out; -webkit-transition: max-width 1s ease-in-out; } img:hover { max-width: 100%; transition: max-width 1s ease-in-out; -moz-transition: max-width 1s ease-in-out; -webkit-transition: max-width 1s ease-in-out; } img:target { max-width: 100%; } .post:target { border: 1px dashed #bbb; background-color: #fed; } a:hover { color: salmon; } spoiler { background-color: #000; } spoiler:hover { background-color: #ddd; } .post-inner { word-break: normal; overflow: auto; max-height: 40em; padding: 0em 0.25em; margin: .5em; }"; } static class html { public const string head = "<!DOCTYPE html><html><head><link rel='stylesheet' type='text/css' href='../styles/piko.css' /><script src='../scripts/piko.js'></script></head>"; static int index_of(this piko_post[] posts, string hash) { for (int i = 0; i < posts.Length; i++) if (posts[i].hash == hash) return i; return -1; } static string first_ref(this piko_post post) { if (Regex.IsMatch(post.message, ">>[a-f0-9]{32}")) return Regex.Match(post.message, ">>[a-f0-9]{32}").Value.Substring(2); return ""; } static string create_ref(bool image, string hash, string rel) { if (image) return "<img src='" + rel + app.files_dir + "/" + hash + "'>"; else return "<a target=_blank href='" + rel + app.files_dir + "/" + hash + "'>[file:"+hash+"]</a>"; } static piko_post[] sort(piko_post[] posts) { int max = 100000; for (int i = 0; i < posts.Length; i++) { if (posts[i].thread == new string('0', 32) && i > 0) { var root = posts[i]; var newarr = posts.ToList(); newarr.Remove(root); newarr.Insert(0, root); posts = newarr.ToArray(); i = -1; continue; } if (posts.index_of(posts[i].first_ref()) > i) { if (max-- <= 0) continue; var wrong = posts[i]; var newarr = posts.ToList(); newarr.Remove(wrong); newarr.Insert(newarr.ToArray().index_of(wrong.first_ref()) + 1, wrong); posts = newarr.ToArray(); i = -1; } } return posts; } public static string wrap_post(piko_post p) { return "<div id='" + p.hash + "' class='post'><div class='post-inner'><g>" + p.hash + "</g><br/>" + format(p.message) + "</div></div>"; } public static string wrap_post_upd(piko_post p) { return "<div id='" + p.hash + "' class='post'><div class='post-inner'><a href='html/"+((p.thread==new string('0',32))?p.hash:p.thread)+".html#"+p.hash+"'>" + p.hash + "</a><br/>" + format(p.message, "") + "</div></div>"; } public static string format(string msg, string rel = "../") { msg = msg.Replace("<", "&lt;"); msg = msg.Replace(">", "&gt;"); msg = msg.Replace("\n", "<br/>"); var refs = Regex.Matches(msg, "\\[(ref|raw)=[a-f0-9]{32}\\]"); foreach (Match r in refs) { msg = msg.Replace(r.Value, create_ref(r.Value.StartsWith("[ref"), r.Value.Substring(5, 32), rel)); } var thread_links = Regex.Matches(msg, "&gt;&gt;&gt;[a-f0-9]{32}"); foreach (Match m in thread_links) { var hash = m.Value.Substring(12); msg = msg.Replace(m.Value, "<a href='" + hash + ".html'>[" + m.Value.Substring(12) + "]</a>"); } var post_links = Regex.Matches(msg, "&gt;&gt;[a-f0-9]{32}"); foreach (Match m in post_links) { var hash = m.Value.Substring(8); msg = msg.Replace(m.Value, "<a href='#" + hash + "'>" + m.Value + "</a>"); } foreach (var ch in "biusg") msg = msg.Replace("["+ch+"]", "<"+ch+">").Replace("[/"+ch+"]", "</"+ch+">"); msg = msg.Replace("[spoiler]", "<spoiler>"); msg = msg.Replace("[/spoiler]", "</spoiler>"); msg = msg.Replace("[sp]", "<spoiler>"); msg = msg.Replace("[/sp]", "</spoiler>"); return msg; } public static void refresh(string thread) { var files = utils.files(app.db_dir + app.slash + thread); files = files.Where(f => Regex.IsMatch(f, ".*[a-f0-9]{32}$")).ToArray(); files = files.OrderBy(f => Directory.GetCreationTime(f).ToFileTimeUtc()).ToArray(); var posts = new List<piko_post>(); foreach (var f in files) { var content = utils.read(f).utf8(); if (Regex.IsMatch(content, "^[a-f0-9]{32}.*")) posts.Add(new piko_post(content)); } posts = sort(posts.ToArray()).ToList(); var sb = new StringBuilder(); sb.Append(head); sb.Append("<body>"); foreach (var p in posts) sb.Append(wrap_post(p)); sb.Append("<textarea>thread="+thread+"\nenter your message... >>hash references the post within a thread, >>>hash - thread\nand save this as post.txt and feed to the app</textarea>"); sb.Append("</body></html>"); utils.write(app.html_dir + app.slash + thread + ".html", sb.ToString().bytes()); } } class app { public const string containers_dir = "jpeg_containers"; public const string files_dir = "board_files"; public const string download_dir = "download"; public const string db_dir = "database"; public const string html_dir = "html"; public const string upload_dir = "for_upload"; const string styles_dir = "styles"; const string pikocss = "piko.css"; public const int max_post_size = 5 * 1000 + 32; public const int max_ref_retranslate = 1536; public const int max_jpeg_size = (int)(3.5 * 1024 * 1024); public static char slash = Path.DirectorySeparatorChar; public const string posttxt = "post.txt"; public static void add_post(string text) { var list = new List<piko_entry>(); var lines = text.Replace("\r\n", "\n").Split('\n'); var thread = lines[0].Split('=')[1]; bool is_oppost = thread.Length == 0; int byte_count = 0, index = 0; list.AddRange(utils.get_refs(text)); list.ForEach(e => byte_count += e.serialized.Length); var post = (is_oppost ? new string('0', 32) : thread) + string.Join("\n", lines.Skip(1)); if (post.Length > max_post_size) { Console.WriteLine("Error: max post size " + max_post_size + " exceeded."); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } var post_hash = hasher.calc(post); var prefix = upload_dir + slash + "upload" + post_hash + "_"; if (is_oppost) thread = post_hash; utils.mkdir(db_dir + slash + thread); utils.write(db_dir + slash + thread + slash + post_hash, post.bytes()); html.refresh(thread); var files = utils.files(db_dir + slash + thread); foreach (var file in files) { if (byte_count > max_jpeg_size) { utils.random_pack(list, prefix + (++index) + ".jpg"); list.Clear(); byte_count = 0; } var bytes = utils.read(file); var str = bytes.utf8(); utils.get_refs(str).Cast<piko_file>().Where(r => r.bytes.Length <= max_ref_retranslate) .Take(1).ToList().ForEach(r => list.Add(r)); list.Add(new piko_post(str)); } if (list.Count > 0) utils.random_pack(list, prefix + (++index) + ".jpg"); } public static void Main(string[] args) { new[]{ styles_dir, containers_dir, download_dir, files_dir, db_dir, upload_dir, html_dir }.ToList().ForEach(utils.mkdir); if (!File.Exists(styles_dir + slash + pikocss)) utils.write(styles_dir + slash + pikocss, css.style.bytes()); if (args.Length == 0) { Console.WriteLine("pikoboard -a collect jpegs from places.txt urls"); Console.WriteLine("pikoboard -r hash refresh html of some thread"); Console.WriteLine("pikoboard -ra refresh html of all threads (warning may be long operation)"); Console.WriteLine("pikoboard file_with_post.txt create container(s) from thread of this post and its file(s)"); Console.WriteLine(" /" + containers_dir + " should have one or more jpegs"); Console.WriteLine(" result will be in /" + upload_dir); Console.WriteLine("pikoboard any_file create post template with this file referenced"); Console.WriteLine("pikoboard create template of post - post.txt and show this help"); File.WriteAllText(posttxt, "thread=\r\nmessage"); return; } if (args.Length == 2 && args[0] == "-r") { var hash = args[1]; html.refresh(hash); return; } if (args.Length == 1 && args[0] == "-ra") { Directory.GetDirectories(db_dir).ToList().ForEach(hash => html.refresh(hash)); return; } if (args.Length == 1 && args[0] == "-a") { Console.WriteLine("Running crawler..."); crawler_runner.run(); Console.WriteLine("Checking new images..."); HashSet<string> to_upd = new HashSet<string>(), fresh = new HashSet<string>(); var files = utils.files(download_dir); foreach (var f in files) { var entries = piko.read(jpg.extract(f)); foreach (var e in entries) { if (e is piko_post) { var pp = e as piko_post; var thread = pp.thread==new string('0',32)?pp.hash:pp.thread; utils.mkdir(db_dir + slash + thread); var file = db_dir + slash + thread + slash + pp.hash; if (File.Exists(file)) continue; utils.write(file, pp.serialized); to_upd.Add(thread); fresh.Add(pp.thread + pp.hash + pp.message); } else if (e is piko_file) { var pf = e as piko_file; var file = files_dir + slash + pf.hash; if (File.Exists(file)) continue; utils.write(file, pf.serialized); } } } foreach (var u in to_upd) html.refresh(u); var sb = new StringBuilder(); sb.Append(html.head.Replace("../","")); sb.Append("<body>"); sb.Append(html.wrap_post(new piko_post(new string('0', 32) + "Recently recevied posts:"))); foreach (var f in fresh) sb.Append(html.wrap_post_upd(new piko_post { thread = f.Substring(0, 32), message = f.Substring(64) })); sb.Append("</body></html>"); utils.write("updates_" + DateTime.UtcNow.ToFileTimeUtc().ToString("x") + ".html", sb.ToString().bytes()); Console.WriteLine("Cleaning up..."); foreach (var f in files) File.Delete(f); Console.WriteLine("Done!"); return; } var bytes = utils.read(args[0]); if (bytes[0] == 't' && bytes[1] == 'h' && bytes[2] == 'r' && bytes[3] == 'e' && bytes[4] == 'a' && bytes[5] == 'd') { add_post(File.ReadAllText(args[0])); } else { var hash = hasher.calc(bytes); File.WriteAllText(posttxt, "thread=enter hash of thread here or just leave thread= for new thread\r\n" + "[ref=" + hash + "]\r\n" + "change ref to raw to link file not image, put your message here, limit is " + max_post_size / 1000 + "k chars."); utils.write(files_dir + slash + hash, bytes); } } } }
// 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.Runtime.CompilerServices; using System.Reflection; using System.Runtime; using System.Threading; using Internal.Metadata.NativeFormat; using Internal.Runtime.CompilerServices; using Internal.TypeSystem; namespace Internal.TypeSystem.NativeFormat { public sealed class NativeFormatMethod : MethodDesc, NativeFormatMetadataUnit.IHandleObject { private static class MethodFlags { public const int BasicMetadataCache = 0x0001; public const int Virtual = 0x0002; public const int NewSlot = 0x0004; public const int Abstract = 0x0008; public const int Final = 0x0010; public const int NoInlining = 0x0020; public const int AggressiveInlining = 0x0040; public const int RuntimeImplemented = 0x0080; public const int InternalCall = 0x0100; public const int Synchronized = 0x0200; public const int AttributeMetadataCache = 0x1000; public const int Intrinsic = 0x2000; public const int NativeCallable = 0x4000; public const int RuntimeExport = 0x8000; }; private NativeFormatType _type; private MethodHandle _handle; // Cached values private ThreadSafeFlags _methodFlags; private MethodSignature _signature; private string _name; private TypeDesc[] _genericParameters; // TODO: Optional field? internal NativeFormatMethod(NativeFormatType type, MethodHandle handle) { _type = type; _handle = handle; #if DEBUG // Initialize name eagerly in debug builds for convenience InitializeName(); #endif } Handle NativeFormatMetadataUnit.IHandleObject.Handle { get { return _handle; } } NativeFormatType NativeFormatMetadataUnit.IHandleObject.Container { get { return _type; } } public override TypeSystemContext Context { get { return _type.Module.Context; } } public override TypeDesc OwningType { get { return _type; } } private MethodSignature InitializeSignature() { var metadataReader = MetadataReader; NativeFormatSignatureParser parser = new NativeFormatSignatureParser(MetadataUnit, MetadataReader.GetMethod(_handle).Signature, metadataReader); var signature = parser.ParseMethodSignature(); return (_signature = signature); } public override MethodSignature Signature { get { if (_signature == null) return InitializeSignature(); return _signature; } } public NativeFormatModule NativeFormatModule { get { return _type.NativeFormatModule; } } public MetadataReader MetadataReader { get { return _type.MetadataReader; } } public NativeFormatMetadataUnit MetadataUnit { get { return _type.MetadataUnit; } } public MethodHandle Handle { get { return _handle; } } [MethodImpl(MethodImplOptions.NoInlining)] private int InitializeMethodFlags(int mask) { int flags = 0; if ((mask & MethodFlags.BasicMetadataCache) != 0) { var methodAttributes = Attributes; var methodImplAttributes = ImplAttributes; if ((methodAttributes & MethodAttributes.Virtual) != 0) flags |= MethodFlags.Virtual; if ((methodAttributes & MethodAttributes.NewSlot) != 0) flags |= MethodFlags.NewSlot; if ((methodAttributes & MethodAttributes.Abstract) != 0) flags |= MethodFlags.Abstract; if ((methodAttributes & MethodAttributes.Final) != 0) flags |= MethodFlags.Final; if ((methodImplAttributes & MethodImplAttributes.NoInlining) != 0) flags |= MethodFlags.NoInlining; if ((methodImplAttributes & MethodImplAttributes.AggressiveInlining) != 0) flags |= MethodFlags.AggressiveInlining; if ((methodImplAttributes & MethodImplAttributes.Runtime) != 0) flags |= MethodFlags.RuntimeImplemented; if ((methodImplAttributes & MethodImplAttributes.InternalCall) != 0) flags |= MethodFlags.InternalCall; if ((methodImplAttributes & MethodImplAttributes.Synchronized) != 0) flags |= MethodFlags.Synchronized; flags |= MethodFlags.BasicMetadataCache; } // Fetching custom attribute based properties is more expensive, so keep that under // a separate cache that might not be accessed very frequently. if ((mask & MethodFlags.AttributeMetadataCache) != 0) { var metadataReader = this.MetadataReader; var methodDefinition = MetadataReader.GetMethod(_handle); foreach (var attributeHandle in methodDefinition.CustomAttributes) { ConstantStringValueHandle nameHandle; string namespaceName; if (!metadataReader.GetAttributeNamespaceAndName(attributeHandle, out namespaceName, out nameHandle)) continue; if (namespaceName.Equals("System.Runtime.CompilerServices")) { if (nameHandle.StringEquals("IntrinsicAttribute", metadataReader)) { flags |= MethodFlags.Intrinsic; } } else if (namespaceName.Equals("System.Runtime.InteropServices")) { if (nameHandle.StringEquals("NativeCallableAttribute", metadataReader)) { flags |= MethodFlags.NativeCallable; } } else if (namespaceName.Equals("System.Runtime")) { if (nameHandle.StringEquals("RuntimeExportAttribute", metadataReader)) { flags |= MethodFlags.RuntimeExport; } } } flags |= MethodFlags.AttributeMetadataCache; } Debug.Assert((flags & mask) != 0); _methodFlags.AddFlags(flags); return flags & mask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int GetMethodFlags(int mask) { int flags = _methodFlags.Value & mask; if (flags != 0) return flags; return InitializeMethodFlags(mask); } public override bool IsVirtual { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Virtual) & MethodFlags.Virtual) != 0; } } public override bool IsNewSlot { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NewSlot) & MethodFlags.NewSlot) != 0; } } public override bool IsAbstract { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Abstract) & MethodFlags.Abstract) != 0; } } public override bool IsFinal { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Final) & MethodFlags.Final) != 0; } } public override bool IsNoInlining { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.NoInlining) & MethodFlags.NoInlining) != 0; } } public override bool IsAggressiveInlining { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.AggressiveInlining) & MethodFlags.AggressiveInlining) != 0; } } public override bool IsRuntimeImplemented { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.RuntimeImplemented) & MethodFlags.RuntimeImplemented) != 0; } } public override bool IsIntrinsic { get { return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.Intrinsic) & MethodFlags.Intrinsic) != 0; } } public override bool IsInternalCall { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.InternalCall) & MethodFlags.InternalCall) != 0; } } public override bool IsSynchronized { get { return (GetMethodFlags(MethodFlags.BasicMetadataCache | MethodFlags.Synchronized) & MethodFlags.Synchronized) != 0; } } public override bool IsNativeCallable { get { return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.NativeCallable) & MethodFlags.NativeCallable) != 0; } } public override bool IsRuntimeExport { get { return (GetMethodFlags(MethodFlags.AttributeMetadataCache | MethodFlags.RuntimeExport) & MethodFlags.RuntimeExport) != 0; } } public override bool IsDefaultConstructor { get { MethodAttributes attributes = Attributes; return attributes.IsRuntimeSpecialName() && attributes.IsPublic() && Signature.Length == 0 && Name == ".ctor" && !_type.IsAbstract; } } public MethodAttributes Attributes { get { return MetadataReader.GetMethod(_handle).Flags; } } public MethodImplAttributes ImplAttributes { get { return MetadataReader.GetMethod(_handle).ImplFlags; } } private string InitializeName() { var metadataReader = MetadataReader; var name = metadataReader.GetString(MetadataReader.GetMethod(_handle).Name); return (_name = name); } public override string Name { get { if (_name == null) return InitializeName(); return _name; } } private void ComputeGenericParameters() { var genericParameterHandles = MetadataReader.GetMethod(_handle).GenericParameters; int count = genericParameterHandles.Count; if (count > 0) { TypeDesc[] genericParameters = new TypeDesc[count]; int i = 0; foreach (var genericParameterHandle in genericParameterHandles) { genericParameters[i++] = new NativeFormatGenericParameter(MetadataUnit, genericParameterHandle); } Interlocked.CompareExchange(ref _genericParameters, genericParameters, null); } else { _genericParameters = TypeDesc.EmptyTypes; } } public override Instantiation Instantiation { get { if (_genericParameters == null) ComputeGenericParameters(); return new Instantiation(_genericParameters); } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return MetadataReader.HasCustomAttribute(MetadataReader.GetMethod(_handle).CustomAttributes, attributeNamespace, attributeName); } public override MethodNameAndSignature NameAndSignature { get { int handleAsToken = _handle.ToInt(); TypeManagerHandle moduleHandle = Internal.Runtime.TypeLoader.ModuleList.Instance.GetModuleForMetadataReader(MetadataReader); return new MethodNameAndSignature(Name, RuntimeSignature.CreateFromMethodHandle(moduleHandle, handleAsToken)); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Mvc.Html; using System.Web.Routing; using HyperSlackers.Bootstrap; using System.Diagnostics.Contracts; using System.Text; using HyperSlackers.Bootstrap.Core; using HyperSlackers.Bootstrap.Extensions; namespace HyperSlackers.Bootstrap.Controls { public class ActionLinkButtonControl<TModel> : ControlBase<ActionLinkButtonControl<TModel>, TModel> { internal readonly AjaxHelper ajax; internal readonly ActionResult result; internal readonly Task<ActionResult> taskResult; internal readonly AjaxOptions ajaxOptions; internal readonly ActionType actionTypePassed; internal string routeName; internal string actionName; internal string controllerName; internal string protocol; internal string hostName; internal string fragment; internal string title; internal RouteValueDictionary routeValues = new RouteValueDictionary(); //internal bool isTextHtml; internal bool buttonBlock; internal bool disabled; internal Icon iconAppend; internal Icon iconPrepend; internal bool isDropDownToggle; internal string loadingText; internal string name; internal ButtonSize size = ButtonSize.Default; internal ButtonStyle style = ButtonStyle.Default; internal string text; internal Tooltip tooltip; internal string value; internal Badge badge; internal ActionLinkButtonControl(HtmlHelper<TModel> html, string linkText, ActionResult result) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(result != null, "result"); text = linkText; this.result = result; size = ButtonSize.Default; actionTypePassed = ActionType.HtmlActionResult; } internal ActionLinkButtonControl(HtmlHelper<TModel> html, string linkText, Task<ActionResult> taskResult) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(taskResult != null, "taskResult"); text = linkText; this.taskResult = taskResult; size = ButtonSize.Default; actionTypePassed = ActionType.HtmlTaskResult; } internal ActionLinkButtonControl(HtmlHelper<TModel> html, string linkText, string actionName) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrWhiteSpace()); text = linkText; this.actionName = actionName; size = ButtonSize.Default; actionTypePassed = ActionType.HtmlRegular; } internal ActionLinkButtonControl(HtmlHelper<TModel> html, string linkText, string actionName, string controllerName) : base(html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!controllerName.IsNullOrWhiteSpace()); text = linkText; this.actionName = actionName; this.controllerName = controllerName; size = ButtonSize.Default; actionTypePassed = ActionType.HtmlRegular; } internal ActionLinkButtonControl(AjaxHelper<TModel> ajax, string linkText, ActionResult result, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(result != null, "result"); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; text = linkText; this.result = result; size = ButtonSize.Default; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxActionResult; } internal ActionLinkButtonControl(AjaxHelper<TModel> ajax, string linkText, Task<ActionResult> taskResult, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(taskResult != null, "taskResult"); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; text = linkText; this.taskResult = taskResult; size = ButtonSize.Default; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxTaskResult; } internal ActionLinkButtonControl(AjaxHelper<TModel> ajax, string linkText, string actionName, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; text = linkText; this.actionName = actionName; size = ButtonSize.Default; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxRegular; } internal ActionLinkButtonControl(AjaxHelper<TModel> ajax, string linkText, string actionName, string controllerName, AjaxOptions ajaxOptions) : base(new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection)) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!actionName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentException>(!controllerName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(ajaxOptions != null, "ajaxOptions"); this.ajax = ajax; text = linkText; this.actionName = actionName; this.controllerName = controllerName; size = ButtonSize.Default; this.ajaxOptions = ajaxOptions; actionTypePassed = ActionType.AjaxRegular; } public ActionLinkButtonControl<TModel> Active() { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); ControlClass("active"); return this; } public ActionLinkButtonControl<TModel> AppendIcon(GlyphIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconAppend = icon; return this; } public ActionLinkButtonControl<TModel> AppendIcon(FontAwesomeIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconAppend = icon; return this; } public ActionLinkButtonControl<TModel> AppendIcon(GlyphIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconAppend = new GlyphIcon(icon, isWhite); return this; } public ActionLinkButtonControl<TModel> AppendIcon(FontAwesomeIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconAppend = new FontAwesomeIcon(icon, isWhite); return this; } public ActionLinkButtonControl<TModel> AppendIcon(string cssClass) { Contract.Requires<ArgumentException>(!cssClass.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconAppend = new GlyphIcon(cssClass); return this; } public ActionLinkButtonControl<TModel> AutoFocus(bool isFocused = true) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); if (isFocused) { controlHtmlAttributes.AddIfNotExist("autofocus", null); } else { controlHtmlAttributes.Remove("autofocus"); } return this; } public ActionLinkButtonControl<TModel> ButtonBlock() { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); buttonBlock = true; return this; } public ActionLinkButtonControl<TModel> Disabled(bool isDisabled = true) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); disabled = isDisabled; return this; } public ActionLinkButtonControl<TModel> DropDownToggle() { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); isDropDownToggle = true; return this; } public ActionLinkButtonControl<TModel> Fragment(string fragment) { Contract.Requires<ArgumentException>(!fragment.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.fragment = fragment; return this; } public ActionLinkButtonControl<TModel> HostName(string hostName) { Contract.Requires<ArgumentException>(!hostName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.hostName = hostName; return this; } //public ActionLinkButtonControl<TModel> LinkTextAsHtml(bool isHtml = true) //{ // Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); // isTextHtml = isHtml; // return this; //} public ActionLinkButtonControl<TModel> LoadingText(string loadingText) { Contract.Requires<ArgumentException>(!loadingText.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.loadingText = loadingText; return this; } public ActionLinkButtonControl<TModel> Name(string name) { Contract.Requires<ArgumentException>(!name.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.name = name; return this; } public ActionLinkButtonControl<TModel> PrependIcon(GlyphIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconPrepend = icon; return this; } public ActionLinkButtonControl<TModel> PrependIcon(GlyphIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconPrepend = new GlyphIcon(icon, isWhite); return this; } public ActionLinkButtonControl<TModel> PrependIcon(FontAwesomeIcon icon) { Contract.Requires<ArgumentNullException>(icon != null, "icon"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconPrepend = icon; return this; } public ActionLinkButtonControl<TModel> PrependIcon(FontAwesomeIconType icon, bool isWhite = false) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconPrepend = new FontAwesomeIcon(icon, isWhite); return this; } public ActionLinkButtonControl<TModel> PrependIcon(string cssClass) { Contract.Requires<ArgumentException>(!cssClass.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); iconPrepend = new GlyphIcon(cssClass); return this; } public ActionLinkButtonControl<TModel> Protocol(string protocol) { Contract.Requires<ArgumentException>(!protocol.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.protocol = protocol; return this; } public ActionLinkButtonControl<TModel> RouteName(string routeName) { Contract.Requires<ArgumentException>(!routeName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.routeName = routeName; return this; } public ActionLinkButtonControl<TModel> RouteValues(object routeValues) { Contract.Requires<ArgumentNullException>(routeValues != null, "routeValues"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.routeValues.AddOrReplaceHtmlAttributes(routeValues.ToDictionary()); return this; } public ActionLinkButtonControl<TModel> RouteValues(RouteValueDictionary routeValues) { Contract.Requires<ArgumentNullException>(routeValues != null, "routeValues"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.routeValues.AddOrReplaceHtmlAttributes(routeValues); return this; } public ActionLinkButtonControl<TModel> Style(ButtonStyle style) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.style = style; return this; } public ActionLinkButtonControl<TModel> Size(ButtonSize size) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.size = size; return this; } public ActionLinkButtonControl<TModel> Text(string text) { Contract.Requires<ArgumentException>(!text.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.text = text; return this; } public ActionLinkButtonControl<TModel> Tooltip(Tooltip tooltip) { Contract.Requires<ArgumentNullException>(tooltip != null, "tooltip"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.tooltip = tooltip; return this; } public ActionLinkButtonControl<TModel> Tooltip(string text) { Contract.Requires<ArgumentException>(!text.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); tooltip = new Tooltip(text); return this; } public ActionLinkButtonControl<TModel> Tooltip(IHtmlString html) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); tooltip = new Tooltip(html); return this; } public ActionLinkButtonControl<TModel> Value(string value) { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.value = value; return this; } public ActionLinkButtonControl<TModel> Title(string title) { Contract.Requires<ArgumentException>(!title.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); this.title = title; return this; } internal ActionLinkButtonControl<TModel> AlertLink() { Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); ControlClass("alert-link"); return this; } public ActionLinkButtonControl<TModel> Badge(string text) { Contract.Requires<ArgumentException>(!text.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ActionLinkButtonControl<TModel>>() != null); badge = new Controls.Badge(text); return this; } private string GenerateActionLink(string linkText, IDictionary<string, object> htmlAttributes) { Contract.Requires<ArgumentException>(!linkText.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace()); switch (actionTypePassed) { case ActionType.HtmlRegular: { return html.ActionLink(linkText, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes).ToHtmlString(); } case ActionType.HtmlActionResult: { return html.ActionLink(linkText, result, htmlAttributes, protocol, hostName, fragment).ToHtmlString(); } case ActionType.HtmlTaskResult: { return html.ActionLink(linkText, taskResult, htmlAttributes, protocol, hostName, fragment).ToHtmlString(); } case ActionType.AjaxRegular: { return ajax.ActionLink(linkText, actionName, controllerName, protocol, hostName, fragment, routeValues, ajaxOptions, htmlAttributes).ToHtmlString(); } case ActionType.AjaxActionResult: { return ajax.ActionLink(linkText, result, ajaxOptions, htmlAttributes).ToHtmlString(); } case ActionType.AjaxTaskResult: { return ajax.ActionLink(linkText, taskResult, ajaxOptions, htmlAttributes).ToHtmlString(); } } return string.Empty; } protected override string Render() { Contract.Ensures(!Contract.Result<string>().IsNullOrWhiteSpace()); IDictionary<string, object> attributes = controlHtmlAttributes.FormatHtmlAttributes(); if (tooltip != null) { attributes.AddOrReplaceHtmlAttributes(tooltip.ToDictionary()); } attributes.AddIfNotExistsCssClass("btn"); if (!id.IsNullOrWhiteSpace()) { attributes.AddOrReplaceHtmlAttribute("id", id); } attributes.AddIfNotExistsCssClass(Helpers.GetCssClass(size)); attributes.AddIfNotExistsCssClass(Helpers.GetCssClass(this.html, style)); if (buttonBlock) { attributes.AddIfNotExistsCssClass("btn-block"); } if (isDropDownToggle) { attributes.AddIfNotExistsCssClass("dropdown-toggle"); attributes.AddIfNotExist("data-toggle", "dropdown"); } if (disabled) { attributes.AddIfNotExistsCssClass("disabled"); //x attributes.Add("disabled", ""); } if (!loadingText.IsNullOrWhiteSpace()) { attributes.AddOrReplaceHtmlAttribute("data-loading-text", loadingText); } if (!title.IsNullOrWhiteSpace()) { attributes.Add("title", title); } if (!name.IsNullOrWhiteSpace()) { attributes.Add("name", name); } string replaceMe = Guid.NewGuid().ToString(); string linkText = text + (badge == null ? "" : " {0}".FormatWith(badge.ToHtmlString())); string linkHtml = GenerateActionLink(replaceMe, attributes); if (iconPrepend != null || iconAppend != null) { string prepend = string.Empty; string append = string.Empty; if (iconPrepend != null) { prepend = iconPrepend.ToHtmlString(); } if (iconAppend != null) { append = iconAppend.ToHtmlString(); } StringBuilder html = new StringBuilder(); html.Append(prepend); if (html.Length > 0 && !text.IsNullOrWhiteSpace()) { html.Append(" "); } html.Append(replaceMe); if (html.Length > 0 && iconAppend != null) { html.Append(" "); } html.Append(append); linkText = html.ToString().Replace(replaceMe, text); } return MvcHtmlString.Create(linkHtml.Replace(replaceMe, linkText)).ToString(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using RRLab.PhysiologyWorkbench.Devices; using RRLab.PhysiologyWorkbench.Data; using RRLab.PhysiologyWorkbench.GUI; namespace RRLab.PhysiologyWorkbench { public partial class MainWindow : Form, IPhysiologyWorkbenchProgramProvider { public event EventHandler ProgramChanged; private PhysiologyWorkbenchProgram _Program; public PhysiologyWorkbenchProgram Program { get { return _Program; } set { _Program = value; OnProgramChanged(EventArgs.Empty); } } protected virtual void OnProgramChanged(EventArgs e) { if (Program != null) { ProgramBindingSource.DataSource = Program; try { this.DataBindings.Add("DataManager", Program, "DataManager"); this.DataBindings.Add("DeviceManager", Program, "DeviceManager"); } catch (Exception x) { ; } if (Program.DataManager != null) { try { Program.DataManager.StartingDatabaseUpdate -= new EventHandler(OnDatabaseUpdateStarted); Program.DataManager.FinishedDatabaseUpdate -= new EventHandler(OnDatabaseUpdateFinished); } catch { ; } Program.DataManager.StartingDatabaseUpdate += new EventHandler(OnDatabaseUpdateStarted); Program.DataManager.FinishedDatabaseUpdate += new EventHandler(OnDatabaseUpdateFinished); } } else ProgramBindingSource.DataSource = typeof(PhysiologyWorkbenchProgram); if (ProgramChanged != null) ProgramChanged(this, e); } protected virtual void OnDatabaseUpdateStarted(object sender, EventArgs e) { ValidateChildren(ValidationConstraints.Enabled); SuspendDataBinding(); } protected virtual void OnDatabaseUpdateFinished(object sender, EventArgs e) { ResumeDataBinding(); } public event EventHandler DeviceManagerChanged; public DeviceManager DeviceManager { get { return _DeviceManager; } set { _DeviceManager = value; if (DeviceManager != null) DeviceManagerBindingSource.DataSource = DeviceManager; else DeviceManagerBindingSource.DataSource = typeof(DeviceManager); if (DeviceManagerChanged != null) DeviceManagerChanged(this, EventArgs.Empty); } } public event EventHandler DataManagerChanged; public DataManager DataManager { get { return _DataManager; } set { if (DataManager != null) { DataManager.DataChanged -= new EventHandler(OnDataSetChanged); DataManager.CurrentCellChanged -= new EventHandler(OnCurrentCellChanged); DataManager.CurrentRecordingChanged -= new EventHandler(OnCurrentRecordingChanged); } _DataManager = value; if (DataManager != null) { DataManager.DataChanged += new EventHandler(OnDataSetChanged); DataManager.CurrentCellChanged += new EventHandler(OnCurrentCellChanged); DataManager.CurrentRecordingChanged += new EventHandler(OnCurrentRecordingChanged); DataManagerBindingSource.DataSource = DataManager; } else DataManagerBindingSource.DataSource = typeof(DataManager); if (DataManagerChanged != null) DataManagerChanged(this, EventArgs.Empty); OnDataSetChanged(this, EventArgs.Empty); } } protected virtual void OnDataSetChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnDataSetChanged), sender, e); return; } if (DataManager != null) { CellInfoControl.DataSet = DataManager.Data; RecordingInfoControl.DataSet = DataManager.Data; } OnCurrentCellChanged(this, e); OnCurrentRecordingChanged(this, e); } protected virtual void OnCurrentCellChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnCurrentCellChanged), sender, e); return; } if (DataManager != null) CellInfoControl.Cell = DataManager.CurrentCell; } protected virtual void OnCurrentRecordingChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnCurrentRecordingChanged), sender, e); return; } if (DataManager != null) RecordingInfoControl.Recording = DataManager.CurrentRecording; } public MainWindow() { InitializeComponent(); mainWindowBindingSource.DataSource = this; } public MainWindow(PhysiologyWorkbenchProgram program) { InitializeComponent(); Program = program; if (Program == null) Program = new PhysiologyWorkbenchProgram(); Program.DeviceManager.RestoreSavedDeviceSettings(); Program.HotkeyManager.RestoreSavedHotkeys(); mainWindowBindingSource.DataSource = this; } private void NewCellMenuItem_Click(object sender, EventArgs e) { if (Program == null || Program.DataManager == null) return; else Program.DataManager.CreateNewCell(); } private void ExitMenuItem_Click(object sender, EventArgs e) { // TODO: Request save first before exiting Application.Exit(); } private void TrashCurrentRecordingSetMenuItem_Click(object sender, EventArgs e) { if (Program == null || Program.DataManager == null) return; // TODO: Request confirmation //Program.DataManager.TrashCurrentCell(); } private void TrashCurrentRecordingMenuItem_Click(object sender, EventArgs e) { if (Program == null || Program.DataManager == null) return; // TODO: Request confirmation //Program.DataManager.TrashCurrentRecording(); } private void OpenDeviceManagerMenuItem_Click(object sender, EventArgs e) { if (Program == null || Program.DeviceManager == null) return; if (InvokeRequired) { Invoke(new EventHandler(OpenDeviceManagerMenuItem_Click), sender, e); return; } DeviceManagerDialog dialog = new DeviceManagerDialog(Program.DeviceManager); dialog.ShowDialog(this); } protected virtual void OpenManualControlButton_Click(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OpenManualControlButton_Click), sender, e); return; } RRLab.PhysiologyWorkbench.GUI.DeviceManualControlDialog dialog = new RRLab.PhysiologyWorkbench.GUI.DeviceManualControlDialog(Program.DeviceManager); dialog.Show(); } private void saveCurrentCellToolStripMenuItem_Click(object sender, EventArgs e) { if (Program == null || Program.DataManager == null) { MessageBox.Show("File not saved."); return; } //else Program.DataManager.SaveCell(); } private void saveCurrentRecordingToolStripMenuItem_Click(object sender, EventArgs e) { if (Program == null || Program.DataManager == null) { MessageBox.Show("File not saved."); return; } //else Program.DataManager.SaveRecording(); } protected virtual void OnSaveAllDataClicked(object sender, EventArgs e) { if (Program != null) Program.DataManager.RequestUserToSaveDataToFile(); } protected virtual void OnSaveCurrentRecordingInExcelClicked(object sender, EventArgs e) { //if ((DataManager == null) || (DataManager.CurrentRecording == null)) return; //RRLab.PhysiologyWorkbench.ExcelExporter.ExcelExporterComponent excel = new RRLab.PhysiologyWorkbench.ExcelExporter.ExcelExporterComponent(); //excel.ExportRecordingToExcel(DataManager.CurrentRecording); } private void OnOpenHotkeyManagerClicked(object sender, EventArgs e) { if (Program.HotkeyManager == null) return; HotkeyManagerDialog dialog = new HotkeyManagerDialog(); dialog.HotkeyManager = Program.HotkeyManager; dialog.ShowDialog(this); } private void OnKeyDown(object sender, KeyEventArgs e) { if(Program != null && Program.HotkeyManager != null) Program.HotkeyManager.ProcessKeyDownEvent(e); } private void OnSelectedTabChanged(object sender, EventArgs e) { if (TabControl.SelectedIndex != 0) TestPulsePanel.NotifyNotVisible(); } private void autoSaveMenuItem_Click(object sender, EventArgs e) { } private void saveAllDataToDatabaseMenuItem_Click(object sender, EventArgs e) { if (Program != null && Program.DataManager != null) Program.DataManager.UpdateAllToDatabase(); } public virtual void SuspendDataBinding() { if (InvokeRequired) { Invoke(new System.Threading.ThreadStart(SuspendDataBinding)); return; } DataManagerBindingSource.SuspendBinding(); CellInfoControl.SuspendDataBinding(); RecordingInfoControl.SuspendDataBinding(); } public virtual void ResumeDataBinding() { if (InvokeRequired) { Invoke(new System.Threading.ThreadStart(ResumeDataBinding)); return; } DataManagerBindingSource.ResumeBinding(); CellInfoControl.ResumeDataBinding(); RecordingInfoControl.ResumeDataBinding(); DataManagerBindingSource.ResetBindings(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.Diagnostics; using System; using System.Threading; using System.Collections.Generic; using System.Runtime.InteropServices; // disable warning about unused weakref #pragma warning disable 414 internal interface PinnedObject { void CleanUp(); bool IsPinned(); } namespace GCSimulator { public enum LifeTimeENUM { Short, Medium, Long } public interface LifeTime { LifeTimeENUM LifeTime { get; set; } } public interface LifeTimeStrategy { int NextObject(LifeTimeENUM lifeTime); bool ShouldDie(LifeTime o, int index); } /// <summary> /// This interfact abstract the object contaienr , allowing us to specify differnt datastructures /// implementation. /// The only restriction on the ObjectContainer is that the objects contained in it must implement /// LifeTime interface. /// Right now we have a simple array container as a stock implementation for that. for more information /// see code:#ArrayContainer /// </summary> /// <param name="o"></param> /// <param name="index"></param> public interface ObjectContainer<T> where T : LifeTime { void Init(int numberOfObjects); void AddObjectAt(T o, int index); T GetObject(int index); T SetObjectAt(T o, int index); int Count { get; } } public sealed class BinaryTreeObjectContainer<T> : ObjectContainer<T> where T : LifeTime { private class Node { public Node LeftChild; public Node RightChild; public int id; public T Data; } private Node _root; private int _count; public BinaryTreeObjectContainer() { _root = null; _count = 0; } public void Init(int numberOfObjects) { if (numberOfObjects <= 0) { return; } _root = new Node(); _root.id = 0; // the total number of objects in a binary search tree = (2^n+1) - 1 // where n is the depth of the tree int depth = (int)Math.Log(numberOfObjects, 2); _count = numberOfObjects; _root.LeftChild = CreateTree(depth, 1); _root.RightChild = CreateTree(depth, 2); } public void AddObjectAt(T o, int index) { Node node = Find(index, _root); if (node != null) { node.Data = o; } } public T GetObject(int index) { Node node = Find(index, _root); if (node == null) { return default(T); } return node.Data; } public T SetObjectAt(T o, int index) { Node node = Find(index, _root); if (node == null) { return default(T); } T old = node.Data; node.Data = o; return old; } public int Count { get { return _count; } } private Node CreateTree(int depth, int id) { if (depth <= 0 || id >= Count) { return null; } Node node = new Node(); node.id = id; node.LeftChild = CreateTree(depth - 1, id * 2 + 1); node.RightChild = CreateTree(depth - 1, id * 2 + 2); return node; } private Node Find(int id, Node node) { // we want to implement find and try to avoid creating temp objects.. // Our Tree is fixed size, we don;t allow modifying the actual // tree by adding or deleting nodes ( that would be more // interesting, but would give us inconsistent perf numbers. // Traverse the tree ( slow, but avoids allocation ), we can write // another tree that is a BST, or use SortedList<T,T> which uses // BST as the implementation if (node == null) return null; if (id == node.id) return node; Node retNode = null; // find in the left child retNode = Find(id, node.LeftChild); // if not found, try the right child. if (retNode == null) retNode = Find(id, node.RightChild); return retNode; } } //#ArrayContainer Simple Array Stock Implemntation for ObjectContainer public sealed class ArrayObjectContainer<T> : ObjectContainer<T> where T : LifeTime { private T[] _objContainer = null; public void Init(int numberOfObjects) { _objContainer = new T[numberOfObjects]; } public void AddObjectAt(T o, int index) { _objContainer[index] = o; } public T GetObject(int index) { return _objContainer[index]; } public T SetObjectAt(T o, int index) { T old = _objContainer[index]; _objContainer[index] = o; return old; } public int Count { get { return _objContainer.Length; } } } public delegate void ObjectDiedEventHandler(LifeTime o, int index); public sealed class ObjectLifeTimeManager { private LifeTimeStrategy _strategy; private ObjectContainer<LifeTime> _objectContainer = null; // public void SetObjectContainer(ObjectContainer<LifeTime> objectContainer) { _objectContainer = objectContainer; } public event ObjectDiedEventHandler objectDied; public void Init(int numberObjects) { _objectContainer.Init(numberObjects); //objContainer = new object[numberObjects]; } public LifeTimeStrategy LifeTimeStrategy { set { _strategy = value; } } public void AddObject(LifeTime o, int index) { _objectContainer.AddObjectAt(o, index); //objContainer[index] = o; } public void Run() { LifeTime objLifeTime; for (int i = 0; i < _objectContainer.Count; ++i) { objLifeTime = _objectContainer.GetObject(i); //object o = objContainer[i]; //objLifeTime = o as LifeTime; if (_strategy.ShouldDie(objLifeTime, i)) { int index = _strategy.NextObject(objLifeTime.LifeTime); LifeTime oldObject = _objectContainer.SetObjectAt(null, index); //objContainer[index] = null; // fire the event objectDied(oldObject, index); } } } } internal class RandomLifeTimeStrategy : LifeTimeStrategy { private int _counter = 0; private int _mediumLifeTime = 30; private int _shortLifeTime = 3; private int _mediumDataCount = 1000000; private int _shortDataCount = 5000; private Random _rand = new Random(123456); public RandomLifeTimeStrategy(int mediumlt, int shortlt, int mdc, int sdc) { _mediumLifeTime = mediumlt; _shortLifeTime = shortlt; _mediumDataCount = mdc; _shortDataCount = sdc; } public int MediumLifeTime { set { _mediumLifeTime = value; } } public int ShortLifeTime { set { _shortLifeTime = value; } } public int NextObject(LifeTimeENUM lifeTime) { switch (lifeTime) { case LifeTimeENUM.Short: return _rand.Next() % _shortDataCount; case LifeTimeENUM.Medium: return (_rand.Next() % _mediumDataCount) + _shortDataCount; case LifeTimeENUM.Long: return 0; } return 0; } public bool ShouldDie(LifeTime o, int index) { _counter++; LifeTimeENUM lifeTime = o.LifeTime; switch (lifeTime) { case LifeTimeENUM.Short: if (_counter % _shortLifeTime == 0) return true; break; case LifeTimeENUM.Medium: if (_counter % _mediumLifeTime == 0) return true; break; case LifeTimeENUM.Long: return false; } return false; } } /// <summary> /// we might want to implement a different strategy that decide the life time of the object based on the time /// elabsed since the last object acceess. /// /// </summary> internal class TimeBasedLifeTimeStrategy : LifeTimeStrategy { private int _lastMediumTickCount = Environment.TickCount; private int _lastShortTickCount = Environment.TickCount; private int _lastMediumIndex = 0; private int _lastShortIndex = 0; public int NextObject(LifeTimeENUM lifeTime) { switch (lifeTime) { case LifeTimeENUM.Short: return _lastShortIndex; case LifeTimeENUM.Medium: return _lastMediumIndex; case LifeTimeENUM.Long: return 0; } return 0; } public bool ShouldDie(LifeTime o, int index) { LifeTimeENUM lifeTime = o.LifeTime; // short objects will live for 20 seconds, long objects will live for more. switch (lifeTime) { case LifeTimeENUM.Short: if (Environment.TickCount - _lastShortTickCount > 1) // this is in accureat enumber, since // we will be finsh iterating throuh the short life time object in less than 1 ms , so we need // to switch either to QueryPeroformanceCounter, or to block the loop for some time through // Thread.Sleep, the other solution is to increase the number of objects a lot. { _lastShortTickCount = Environment.TickCount; _lastShortIndex = index; return true; } break; case LifeTimeENUM.Medium: if (Environment.TickCount - _lastMediumTickCount > 20) { _lastMediumTickCount = Environment.TickCount; _lastMediumIndex = index; return true; } break; case LifeTimeENUM.Long: break; } return false; } } internal class ObjectWrapper : LifeTime, PinnedObject { private bool _pinned; private bool _weakReferenced; private GCHandle _gcHandle; private LifeTimeENUM _lifeTime; private WeakReference _weakRef; private byte[] _data; private int _dataSize; public int DataSize { set { _dataSize = value; _data = new byte[_dataSize]; if (_pinned) { _gcHandle = GCHandle.Alloc(_data, GCHandleType.Pinned); } if (_weakReferenced) { _weakRef = new WeakReference(_data); _data = null; } } } public LifeTimeENUM LifeTime { get { return _lifeTime; } set { _lifeTime = value; } } public bool IsPinned() { return _pinned; } public bool IsWeak() { return _weakReferenced; } public void CleanUp() { if (_gcHandle.IsAllocated) { _gcHandle.Free(); } } public ObjectWrapper(bool runFinalizer, bool pinned, bool weakReferenced) { _pinned = pinned; _weakReferenced = weakReferenced; if (!runFinalizer) { GC.SuppressFinalize(this); } } ~ObjectWrapper() { // DO SOMETHING UNCONVENTIONAL IN FINALIZER _data = new byte[_dataSize]; CleanUp(); } } internal class ClientSimulator { [ThreadStatic] private static ObjectLifeTimeManager s_lifeTimeManager; private static int s_meanAllocSize = 17; private static int s_mediumLifeTime = 30; private static int s_shortLifeTime = 3; private static int s_mediumDataSize = s_meanAllocSize; private static int s_shortDataSize = s_meanAllocSize; private static int s_mediumDataCount = 1000000; private static int s_shortDataCount = 5000; private static int s_countIters = 500; private static float s_percentPinned = 0.1F; private static float s_percentWeak = 0.0F; private static int s_numThreads = 1; private static bool s_runFinalizer = false; private static string s_strategy = "Random"; private static string s_objectGraph = "List"; private static List<Thread> s_threadList = new List<Thread>(); private static Stopwatch s_stopWatch = new Stopwatch(); private static Object s_objLock = new Object(); private static uint s_currentIterations = 0; //keep track of the collection count for generations 0, 1, 2 private static int[] s_currentCollections = new int[3]; private static int s_outputFrequency = 0; //after how many iterations the data is printed private static System.TimeSpan s_totalTime; public static int Main(string[] args) { s_stopWatch.Start(); for (int i = 0; i < 3; i++) { s_currentCollections[i] = 0; } if (!ParseArgs(args)) return 101; // Run the test. for (int i = 0; i < s_numThreads; ++i) { Thread thread = new Thread(RunTest); s_threadList.Add(thread); thread.Start(); } foreach (Thread t in s_threadList) { t.Join(); } return 100; } public static void RunTest() { // Allocate the objects. s_lifeTimeManager = new ObjectLifeTimeManager(); LifeTimeStrategy ltStrategy; int threadMediumLifeTime = s_mediumLifeTime; int threadShortLifeTime = s_shortLifeTime; int threadMediumDataSize = s_mediumDataSize; int threadShortDataSize = s_shortDataSize; int threadMediumDataCount = s_mediumDataCount; int threadShortDataCount = s_shortDataCount; float threadPercentPinned = s_percentPinned; float threadPercentWeak = s_percentWeak; bool threadRunFinalizer = s_runFinalizer; string threadStrategy = s_strategy; string threadObjectGraph = s_objectGraph; if (threadObjectGraph.ToLower() == "tree") { s_lifeTimeManager.SetObjectContainer(new BinaryTreeObjectContainer<LifeTime>()); } else { s_lifeTimeManager.SetObjectContainer(new ArrayObjectContainer<LifeTime>()); } s_lifeTimeManager.Init(threadShortDataCount + threadMediumDataCount); if (threadStrategy.ToLower() == "random") { ltStrategy = new RandomLifeTimeStrategy(threadMediumLifeTime, threadShortLifeTime, threadMediumDataCount, threadShortDataCount); } else { // may be we need to specify the elapsed time. ltStrategy = new TimeBasedLifeTimeStrategy(); } s_lifeTimeManager.LifeTimeStrategy = ltStrategy; s_lifeTimeManager.objectDied += new ObjectDiedEventHandler(objectDied); for (int i = 0; i < threadShortDataCount + threadMediumDataCount; ++i) { bool pinned = false; if (threadPercentPinned != 0) { pinned = (i % ((int)(1 / threadPercentPinned)) == 0); } bool weak = false; if (threadPercentWeak != 0) { weak = (i % ((int)(1 / threadPercentWeak)) == 0); } ObjectWrapper oWrapper = new ObjectWrapper(threadRunFinalizer, pinned, weak); if (i < threadShortDataCount) { oWrapper.DataSize = threadShortDataSize; oWrapper.LifeTime = LifeTimeENUM.Short; } else { oWrapper.DataSize = threadMediumDataSize; oWrapper.LifeTime = LifeTimeENUM.Medium; } s_lifeTimeManager.AddObject(oWrapper, i); } lock (s_objLock) { Console.WriteLine("Thread {0} Running With Configuration: ", System.Threading.Thread.CurrentThread.ManagedThreadId); Console.WriteLine("=============================="); Console.WriteLine("[Thread] Medium Lifetime " + threadMediumLifeTime); Console.WriteLine("[Thread] Short Lifetime " + threadShortLifeTime); Console.WriteLine("[Thread] Medium Data Size " + threadMediumDataSize); Console.WriteLine("[Thread] Short Data Size " + threadShortDataSize); Console.WriteLine("[Thread] Medium Data Count " + threadMediumDataCount); Console.WriteLine("[Thread] Short Data Count " + threadShortDataCount); Console.WriteLine("[Thread] % Pinned " + threadPercentPinned); Console.WriteLine("[Thread] % Weak " + threadPercentWeak); Console.WriteLine("[Thread] RunFinalizers " + threadRunFinalizer); Console.WriteLine("[Thread] Strategy " + threadStrategy); Console.WriteLine("[Thread] Object Graph " + threadObjectGraph); Console.WriteLine("=============================="); } for (int i = 0; i < s_countIters; ++i) { // Run the test. s_lifeTimeManager.Run(); if (s_outputFrequency > 0) { lock (s_objLock) { s_currentIterations++; if (s_currentIterations % s_outputFrequency == 0) { Console.WriteLine("Iterations = {0}", s_currentIterations); Console.WriteLine("AllocatedMemory = {0} bytes", GC.GetTotalMemory(false)); //get the number of collections and the elapsed time for this group of iterations int[] collectionCount = new int[3]; for (int j = 0; j < 3; j++) { collectionCount[j] = GC.CollectionCount(j); } int[] newCollections = new int[3]; for (int j = 0; j < 3; j++) { newCollections[j] = collectionCount[j] - s_currentCollections[j]; } //update the running count of collections for (int j = 0; j < 3; j++) { s_currentCollections[j] = collectionCount[j]; } Console.WriteLine("Gen 0 Collections = {0}", newCollections[0]); Console.WriteLine("Gen 1 Collections = {0}", newCollections[1]); Console.WriteLine("Gen 2 Collections = {0}", newCollections[2]); s_stopWatch.Stop(); Console.Write("Elapsed time: "); System.TimeSpan tSpan = s_stopWatch.Elapsed; if (tSpan.Days > 0) Console.Write("{0} days, ", tSpan.Days); if (tSpan.Hours > 0) Console.Write("{0} hours, ", tSpan.Hours); if (tSpan.Minutes > 0) Console.Write("{0} minutes, ", tSpan.Minutes); Console.Write("{0} seconds, ", tSpan.Seconds); Console.Write("{0} milliseconds", tSpan.Milliseconds); s_totalTime += tSpan; s_stopWatch.Reset(); s_stopWatch.Start(); Console.Write(" (Total time: "); if (s_totalTime.Days > 0) Console.Write("{0} days, ", s_totalTime.Days); if (s_totalTime.Hours > 0) Console.Write("{0} hours, ", s_totalTime.Hours); if (s_totalTime.Minutes > 0) Console.Write("{0} minutes, ", s_totalTime.Minutes); Console.Write("{0} seconds, ", s_totalTime.Seconds); Console.WriteLine("{0} milliseconds)", s_totalTime.Milliseconds); Console.WriteLine("----------------------------------"); } } } } } private static void objectDied(LifeTime lifeTime, int index) { // put a new fresh object instead; ObjectWrapper oWrapper = lifeTime as ObjectWrapper; oWrapper.CleanUp(); oWrapper = new ObjectWrapper(s_runFinalizer, oWrapper.IsPinned(), oWrapper.IsWeak()); oWrapper.LifeTime = lifeTime.LifeTime; oWrapper.DataSize = lifeTime.LifeTime == LifeTimeENUM.Short ? s_shortDataSize : s_mediumDataSize; s_lifeTimeManager.AddObject(oWrapper, index); } /// <summary> /// Parse the arguments, no error checking is done yet. /// TODO: Add more error checking. /// /// Populate variables with defaults, then overwrite them with config settings. Finally overwrite them with command line parameters /// </summary> public static bool ParseArgs(string[] args) { s_countIters = 500; try { for (int i = 0; i < args.Length; ++i) { string currentArg = args[i]; string currentArgValue; if (currentArg.StartsWith("-") || currentArg.StartsWith("/")) { currentArg = currentArg.Substring(1); } else { Console.WriteLine("Error! Unexpected argument {0}", currentArg); return false; } if (currentArg.StartsWith("?")) { Usage(); System.Environment.FailFast("displayed help"); } else if (currentArg.StartsWith("iter") || currentArg.Equals("i")) // number of iterations { currentArgValue = args[++i]; s_countIters = Int32.Parse(currentArgValue); } else if (currentArg.StartsWith("datasize") || currentArg.Equals("dz")) { currentArgValue = args[++i]; s_mediumDataSize = Int32.Parse(currentArgValue); } else if (currentArg.StartsWith("sdatasize") || currentArg.Equals("sdz")) { currentArgValue = args[++i]; s_shortDataSize = Int32.Parse(currentArgValue); } else if (currentArg.StartsWith("datacount") || currentArg.Equals("dc")) { currentArgValue = args[++i]; s_mediumDataCount = Int32.Parse(currentArgValue); } else if (currentArg.StartsWith("sdatacount") || currentArg.Equals("sdc")) { currentArgValue = args[++i]; s_shortDataCount = Int32.Parse(currentArgValue); } else if (currentArg.StartsWith("lifetime") || currentArg.Equals("lt")) { currentArgValue = args[++i]; s_shortLifeTime = Int32.Parse(currentArgValue); s_mediumLifeTime = s_shortLifeTime * 10; } else if (currentArg.StartsWith("threads") || currentArg.Equals("t")) { currentArgValue = args[++i]; s_numThreads = Int32.Parse(currentArgValue); } else if (currentArg.StartsWith("fin") || currentArg.Equals("f")) { s_runFinalizer = true; } else if (currentArg.StartsWith("datapinned") || currentArg.StartsWith("dp")) // percentage data pinned { currentArgValue = args[++i]; s_percentPinned = float.Parse(currentArgValue); if (s_percentPinned < 0 || s_percentPinned > 1) { Console.WriteLine("Error! datapinned should be a number from 0 to 1"); return false; } } else if (currentArg.StartsWith("strategy")) //strategy that if the object died or not { currentArgValue = args[++i]; if ((currentArgValue.ToLower() == "random") || (currentArgValue.ToLower() == "time")) s_strategy = currentArgValue; else { Console.WriteLine("Error! Unexpected argument for strategy: {0}", currentArgValue); return false; } } else if (currentArg.StartsWith("dataweak") || currentArg.StartsWith("dw")) { currentArgValue = args[++i]; s_percentWeak = float.Parse(currentArgValue); if (s_percentWeak < 0 || s_percentWeak > 1) { Console.WriteLine("Error! dataweak should be a number from 0 to 1"); return false; } } else if (currentArg.StartsWith("objectgraph") || currentArg.StartsWith("og")) { currentArgValue = args[++i]; if ((currentArgValue.ToLower() == "tree") || (currentArgValue.ToLower() == "list")) s_objectGraph = currentArgValue; else { Console.WriteLine("Error! Unexpected argument for objectgraph: {0}", currentArgValue); return false; } } else if (currentArg.Equals("out")) //output frequency { currentArgValue = args[++i]; s_outputFrequency = int.Parse(currentArgValue); } else { Console.WriteLine("Error! Unexpected argument {0}", currentArg); return false; } } } catch (System.Exception e) { Console.WriteLine("Incorrect arguments"); Console.WriteLine(e.ToString()); return false; } return true; } public static void Usage() { Console.WriteLine("GCSimulator [-?] [options]"); Console.WriteLine("\nOptions"); Console.WriteLine("\nGlobal:"); Console.WriteLine("-? Display the usage and exit"); Console.WriteLine("-i [-iter] <num iterations> : specify number of iterations for the test, default is " + s_countIters); Console.WriteLine("\nThreads:"); Console.WriteLine("-t [-threads] <number of threads> : specifiy number of threads, default is " + s_numThreads); Console.WriteLine("\nData:"); Console.WriteLine("-dz [-datasize] <data size> : specify the data size in bytes, default is " + s_mediumDataSize); Console.WriteLine("-sdz [sdatasize] <data size> : specify the short lived data size in bytes, default is " + s_shortDataSize); Console.WriteLine("-dc [datacount] <data count> : specify the medium lived data count, default is " + s_mediumDataCount); Console.WriteLine("-sdc [sdatacount] <data count> : specify the short lived data count, default is " + s_shortDataCount); Console.WriteLine("-lt [-lifetime] <number> : specify the life time of the objects, default is " + s_shortLifeTime); Console.WriteLine("-f [-fin] : specify whether to do allocation in finalizer or not, default is no"); Console.WriteLine("-dp [-datapinned] <percent of data pinned> : specify the percentage of data that we want to pin (number from 0 to 1), default is " + s_percentPinned); Console.WriteLine("-dw [-dataweak] <percent of data weak referenced> : specify the percentage of data that we want to weak reference, (number from 0 to 1) default is " + s_percentWeak); Console.WriteLine("-strategy < indicate the strategy for deciding when the objects should die, right now we support only Random and Time strategy, default is Random"); Console.WriteLine("-og [-objectgraph] <List|Tree> : specify whether to use a List- or Tree-based object graph, default is " + s_objectGraph); Console.WriteLine("-out <iterations> : after how many iterations to output data"); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; 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 ErrorHandling.Areas.HelpPage.ModelDescriptions; using ErrorHandling.Areas.HelpPage.Models; namespace ErrorHandling.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; } if (complexTypeDescription != null) { 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 ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using HtmlAgilityPack; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp { public class Subreddit : Thing { private const string SubredditPostUrl = "/r/{0}.json"; private const string SubredditNewUrl = "/r/{0}/new.json?sort=new"; private const string SubredditHotUrl = "/r/{0}/hot.json"; private const string SubscribeUrl = "/api/subscribe"; private const string GetSettingsUrl = "/r/{0}/about/edit.json"; private const string GetReducedSettingsUrl = "/r/{0}/about.json"; private const string ModqueueUrl = "/r/{0}/about/modqueue.json"; private const string UnmoderatedUrl = "/r/{0}/about/unmoderated.json"; private const string FlairTemplateUrl = "/api/flairtemplate"; private const string ClearFlairTemplatesUrl = "/api/clearflairtemplates"; private const string SetUserFlairUrl = "/api/flair"; private const string StylesheetUrl = "/r/{0}/about/stylesheet.json"; private const string UploadImageUrl = "/api/upload_sr_img"; private const string FlairSelectorUrl = "/api/flairselector"; private const string AcceptModeratorInviteUrl = "/api/accept_moderator_invite"; private const string LeaveModerationUrl = "/api/unfriend"; private const string BanUserUrl = "/api/friend"; private const string AddModeratorUrl = "/api/friend"; private const string AddContributorUrl = "/api/friend"; private const string ModeratorsUrl = "/r/{0}/about/moderators.json"; private const string FrontPageUrl = "/.json"; private const string SubmitLinkUrl = "/api/submit"; private const string FlairListUrl = "/r/{0}/api/flairlist.json"; private const string CommentsUrl = "/r/{0}/comments.json"; [JsonIgnore] private Reddit Reddit { get; set; } [JsonIgnore] private IWebAgent WebAgent { get; set; } [JsonIgnore] public Wiki Wiki { get; private set; } [JsonProperty("created")] [JsonConverter(typeof(UnixTimestampConverter))] public DateTime? Created { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("description_html")] public string DescriptionHTML { get; set; } [JsonProperty("display_name")] public string DisplayName { get; set; } [JsonProperty("header_img")] public string HeaderImage { get; set; } [JsonProperty("header_title")] public string HeaderTitle { get; set; } [JsonProperty("over18")] public bool? NSFW { get; set; } [JsonProperty("public_description")] public string PublicDescription { get; set; } [JsonProperty("subscribers")] public int? Subscribers { get; set; } [JsonProperty("accounts_active")] public int? ActiveUsers { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("url")] [JsonConverter(typeof(UrlParser))] public Uri Url { get; set; } [JsonIgnore] public string Name { get; set; } public Listing<Post> Posts { get { if (Name == "/") return new Listing<Post>(Reddit, "/.json", WebAgent); return new Listing<Post>(Reddit, string.Format(SubredditPostUrl, Name), WebAgent); } } public Listing<Comment> Comments { get { if (Name == "/") return new Listing<Comment>(Reddit, "/comments.json", WebAgent); return new Listing<Comment>(Reddit, string.Format(CommentsUrl, Name), WebAgent); } } public Listing<Post> New { get { if (Name == "/") return new Listing<Post>(Reddit, "/new.json", WebAgent); return new Listing<Post>(Reddit, string.Format(SubredditNewUrl, Name), WebAgent); } } public Listing<Post> Hot { get { if (Name == "/") return new Listing<Post>(Reddit, "/.json", WebAgent); return new Listing<Post>(Reddit, string.Format(SubredditHotUrl, Name), WebAgent); } } public Listing<VotableThing> ModQueue { get { return new Listing<VotableThing>(Reddit, string.Format(ModqueueUrl, Name), WebAgent); } } public Listing<Post> UnmoderatedLinks { get { return new Listing<Post>(Reddit, string.Format(UnmoderatedUrl, Name), WebAgent); } } public SubredditSettings Settings { get { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); try { var request = WebAgent.CreateGet(string.Format(GetSettingsUrl, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); return new SubredditSettings(this, Reddit, json, WebAgent); } catch // TODO: More specific catch { // Do it unauthed var request = WebAgent.CreateGet(string.Format(GetReducedSettingsUrl, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); return new SubredditSettings(this, Reddit, json, WebAgent); } } } public UserFlairTemplate[] UserFlairTemplates // Hacky, there isn't a proper endpoint for this { get { var request = WebAgent.CreatePost(FlairSelectorUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { name = Reddit.User.Name, r = Name, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var document = new HtmlDocument(); document.LoadHtml(data); if (document.DocumentNode.Descendants("div").First().Attributes["error"] != null) throw new InvalidOperationException("This subreddit does not allow users to select flair."); var templateNodes = document.DocumentNode.Descendants("li"); var list = new List<UserFlairTemplate>(); foreach (var node in templateNodes) { list.Add(new UserFlairTemplate { CssClass = node.Descendants("span").First().Attributes["class"].Value.Split(' ')[1], Text = node.Descendants("span").First().InnerText }); } return list.ToArray(); } } public SubredditStyle Stylesheet { get { var request = WebAgent.CreateGet(string.Format(StylesheetUrl, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); return new SubredditStyle(Reddit, this, json, WebAgent); } } public IEnumerable<ModeratorUser> Moderators { get { var request = WebAgent.CreateGet(string.Format(ModeratorsUrl, Name)); var response = request.GetResponse(); var responseString = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(responseString); var type = json["kind"].ToString(); if (type != "UserList") throw new FormatException("Reddit responded with an object that is not a user listing."); var data = json["data"]; var mods = data["children"].ToArray(); var result = new ModeratorUser[mods.Length]; for (var i = 0; i < mods.Length; i++) { var mod = new ModeratorUser(Reddit, mods[i]); result[i] = mod; } return result; } } /// <summary> /// This constructor only exists for internal use and serialization. /// You would be wise not to use it. /// </summary> public Subreddit() : base(null) { } protected internal Subreddit(Reddit reddit, JToken json, IWebAgent webAgent) : base(json) { Reddit = reddit; WebAgent = webAgent; Wiki = new Wiki(reddit, this, webAgent); JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings); Name = Url.ToString(); if (Name.StartsWith("/r/")) Name = Name.Substring(3); if (Name.StartsWith("r/")) Name = Name.Substring(2); Name = Name.TrimEnd('/'); } public static Subreddit GetRSlashAll(Reddit reddit) { var rSlashAll = new Subreddit { DisplayName = "/r/all", Title = "/r/all", Url = new Uri("/r/all", UriKind.Relative), Name = "all", Reddit = reddit, WebAgent = reddit._webAgent }; return rSlashAll; } public static Subreddit GetFrontPage(Reddit reddit) { var frontPage = new Subreddit { DisplayName = "Front Page", Title = "reddit: the front page of the internet", Url = new Uri("/", UriKind.Relative), Name = "/", Reddit = reddit, WebAgent = reddit._webAgent }; return frontPage; } public void Subscribe() { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(SubscribeUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { action = "sub", sr = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); // Discard results } public void Unsubscribe() { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(SubscribeUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { action = "unsub", sr = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); // Discard results } public void ClearFlairTemplates(FlairType flairType) { var request = WebAgent.CreatePost(ClearFlairTemplatesUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { flair_type = flairType == FlairType.Link ? "LINK_FLAIR" : "USER_FLAIR", uh = Reddit.User.Modhash, r = Name }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void AddFlairTemplate(string cssClass, FlairType flairType, string text, bool userEditable) { var request = WebAgent.CreatePost(FlairTemplateUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { css_class = cssClass, flair_type = flairType == FlairType.Link ? "LINK_FLAIR" : "USER_FLAIR", text = text, text_editable = userEditable, uh = Reddit.User.Modhash, r = Name, api_type = "json" }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); } public string GetFlairText(string user) { var request = WebAgent.CreateGet(String.Format(FlairListUrl + "?name=" + user, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); return (string)json["users"][0]["flair_text"]; } public string GetFlairCssClass(string user) { var request = WebAgent.CreateGet(String.Format(FlairListUrl + "?name=" + user, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); return (string)json["users"][0]["flair_css_class"]; } public void SetUserFlair(string user, string cssClass, string text) { var request = WebAgent.CreatePost(SetUserFlairUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { css_class = cssClass, text = text, uh = Reddit.User.Modhash, r = Name, name = user }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void UploadHeaderImage(string name, ImageType imageType, byte[] file) { var request = WebAgent.CreatePost(UploadImageUrl); var formData = new MultipartFormBuilder(request); formData.AddDynamic(new { name, uh = Reddit.User.Modhash, r = Name, formid = "image-upload", img_type = imageType == ImageType.PNG ? "png" : "jpg", upload = "", header = 1 }); formData.AddFile("file", "foo.png", file, imageType == ImageType.PNG ? "image/png" : "image/jpeg"); formData.Finish(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); // TODO: Detect errors } public void AddModerator(string user) { var request = WebAgent.CreatePost(AddModeratorUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "moderator", name = user }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void AcceptModeratorInvite() { var request = WebAgent.CreatePost(AcceptModeratorInviteUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void RemoveModerator(string id) { var request = WebAgent.CreatePost(LeaveModerationUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "moderator", id }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public override string ToString() { return "/r/" + DisplayName; } public void AddContributor(string user) { var request = WebAgent.CreatePost(AddContributorUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "contributor", name = user }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void RemoveContributor(string id) { var request = WebAgent.CreatePost(LeaveModerationUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "contributor", id }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void BanUser(string user, string reason) { var request = WebAgent.CreatePost(BanUserUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "banned", id = "#banned", name = user, note = reason, action = "add", container = FullName }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } private Post Submit(SubmitData data) { if (Reddit.User == null) throw new RedditException("No user logged in."); var request = WebAgent.CreatePost(SubmitLinkUrl); WebAgent.WritePostBody(request.GetRequestStream(), data); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); ICaptchaSolver solver = Reddit.CaptchaSolver; if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null) { data.Iden = json["json"]["captcha"].ToString(); CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(data.Iden)); // We throw exception due to this method being expected to return a valid Post object, but we cannot // if we got a Captcha error. if (captchaResponse.Cancel) throw new CaptchaFailedException("Captcha verification failed when submitting " + data.Kind + " post"); data.Captcha = captchaResponse.Answer; return Submit(data); } else if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "ALREADY_SUB") { throw new DuplicateLinkException(String.Format("Post failed when submitting. The following link has already been submitted: {0}", SubmitLinkUrl)); } return new Post(Reddit, json["json"], WebAgent); } /// <summary> /// Submits a link post in the current subreddit using the logged-in user /// </summary> /// <param name="title">The title of the submission</param> /// <param name="url">The url of the submission link</param> public Post SubmitPost(string title, string url, string captchaId = "", string captchaAnswer = "", bool resubmit = false) { return Submit( new LinkData { Subreddit = Name, UserHash = Reddit.User.Modhash, Title = title, URL = url, Resubmit = resubmit, Iden = captchaId, Captcha = captchaAnswer }); } /// <summary> /// Submits a text post in the current subreddit using the logged-in user /// </summary> /// <param name="title">The title of the submission</param> /// <param name="text">The raw markdown text of the submission</param> public Post SubmitTextPost(string title, string text, string captchaId = "", string captchaAnswer = "") { return Submit( new TextData { Subreddit = Name, UserHash = Reddit.User.Modhash, Title = title, Text = text, Iden = captchaId, Captcha = captchaAnswer }); } #region Obsolete Getter Methods [Obsolete("Use Posts property instead")] public Listing<Post> GetPosts() { return Posts; } [Obsolete("Use New property instead")] public Listing<Post> GetNew() { return New; } [Obsolete("Use Hot property instead")] public Listing<Post> GetHot() { return Hot; } [Obsolete("Use ModQueue property instead")] public Listing<VotableThing> GetModQueue() { return ModQueue; } [Obsolete("Use UnmoderatedLinks property instead")] public Listing<Post> GetUnmoderatedLinks() { return UnmoderatedLinks; } [Obsolete("Use Settings property instead")] public SubredditSettings GetSettings() { return Settings; } [Obsolete("Use UserFlairTemplates property instead")] public UserFlairTemplate[] GetUserFlairTemplates() // Hacky, there isn't a proper endpoint for this { return UserFlairTemplates; } [Obsolete("Use Stylesheet property instead")] public SubredditStyle GetStylesheet() { return Stylesheet; } [Obsolete("Use Moderators property instead")] public IEnumerable<ModeratorUser> GetModerators() { return Moderators; } #endregion Obsolete Getter Methods } }
#pragma warning disable 1591 using System.Collections.Generic; namespace AjaxControlToolkit { public abstract class HtmlEditorExtenderButton { public abstract string CommandName { get; } public virtual string Tooltip { get { return CommandName; } } // Get list of elements associated to the button public abstract Dictionary<string, string[]> ElementWhiteList { get; } // Get list of Attribute and its values associated to the button public abstract Dictionary<string, string[]> AttributeWhiteList { get; } } #region button classes // Bold class represents to bold tag public class Bold : HtmlEditorExtenderButton { public override string CommandName { get { return "Bold"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("b", new string[] { "style" }); elementWhiteList.Add("strong", new string[] { "style" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { }); return attributeWhiteList; } } } public class Italic : HtmlEditorExtenderButton { public override string CommandName { get { return "Italic"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("i", new string[] { "style" }); elementWhiteList.Add("em", new string[] { "style" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { }); return attributeWhiteList; } } } public class Underline : HtmlEditorExtenderButton { public override string CommandName { get { return "Underline"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("u", new string[] { "style" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { }); return attributeWhiteList; } } } public class StrikeThrough : HtmlEditorExtenderButton { public override string CommandName { get { return "StrikeThrough"; } } public override string Tooltip { get { return "Strike Through"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("strike", new string[] { "style" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { }); return attributeWhiteList; } } } public class Subscript : HtmlEditorExtenderButton { public override string CommandName { get { return "Subscript"; } } public override string Tooltip { get { return "Sub Script"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("sub", new string[] { }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class Superscript : HtmlEditorExtenderButton { public override string CommandName { get { return "Superscript"; } } public override string Tooltip { get { return "Super Script"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("sup", new string[] { }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class JustifyLeft : HtmlEditorExtenderButton { public override string CommandName { get { return "JustifyLeft"; } } public override string Tooltip { get { return "Justify Left"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("p", new string[] { "align" }); elementWhiteList.Add("div", new string[] { "style", "align" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { "text-align" }); attributeWhiteList.Add("align", new string[] { "left" }); return attributeWhiteList; } } } public class JustifyRight : HtmlEditorExtenderButton { public override string CommandName { get { return "JustifyRight"; } } public override string Tooltip { get { return "Justify Right"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("p", new string[] { "align" }); elementWhiteList.Add("div", new string[] { "style", "align" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { "text-align" }); attributeWhiteList.Add("align", new string[] { "right" }); return attributeWhiteList; } } } public class JustifyCenter : HtmlEditorExtenderButton { public override string CommandName { get { return "JustifyCenter"; } } public override string Tooltip { get { return "Justify Center"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("p", new string[] { "align" }); elementWhiteList.Add("div", new string[] { "style", "align" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { "text-align" }); attributeWhiteList.Add("align", new string[] { "center" }); return attributeWhiteList; } } } public class JustifyFull : HtmlEditorExtenderButton { public override string CommandName { get { return "JustifyFull"; } } public override string Tooltip { get { return "Justify Full"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("p", new string[] { "align" }); elementWhiteList.Add("div", new string[] { "style", "align" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { "text-align" }); attributeWhiteList.Add("align", new string[] { "justify" }); return attributeWhiteList; } } } public class InsertOrderedList : HtmlEditorExtenderButton { public override string CommandName { get { return "insertOrderedList"; } } public override string Tooltip { get { return "Insert Ordered List"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("ol", new string[] { }); elementWhiteList.Add("li", new string[] { }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class InsertUnorderedList : HtmlEditorExtenderButton { public override string CommandName { get { return "insertUnorderedList"; } } public override string Tooltip { get { return "Insert Unordered List"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("ul", new string[] { }); elementWhiteList.Add("li", new string[] { }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class Undo : HtmlEditorExtenderButton { public override string CommandName { get { return "Undo"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class Redo : HtmlEditorExtenderButton { public override string CommandName { get { return "Redo"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class CreateLink : HtmlEditorExtenderButton { public override string CommandName { get { return "createLink"; } } public override string Tooltip { get { return "Create Link"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("a", new string[] { "href" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("href", new string[] { }); return null; } } } public class Delete : HtmlEditorExtenderButton { public override string CommandName { get { return "Delete"; } } public override string Tooltip { get { return "Delete"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class SelectAll : HtmlEditorExtenderButton { public override string CommandName { get { return "SelectAll"; } } public override string Tooltip { get { return "Select All"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class UnSelect : HtmlEditorExtenderButton { public override string CommandName { get { return "UnSelect"; } } public override string Tooltip { get { return "UnSelect"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class UnLink : HtmlEditorExtenderButton { public override string CommandName { get { return "UnLink"; } } public override string Tooltip { get { return "UnLink"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class BackgroundColorSelector : HtmlEditorExtenderButton { public override string CommandName { get { return "BackColor"; } } public override string Tooltip { get { return "Back Color"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("font", new string[] { "style" }); elementWhiteList.Add("span", new string[] { "style" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { "background-color" }); return attributeWhiteList; } } } public class Copy : HtmlEditorExtenderButton { public override string CommandName { get { return "Copy"; } } public override string Tooltip { get { return "Copy"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class Cut : HtmlEditorExtenderButton { public override string CommandName { get { return "Cut"; } } public override string Tooltip { get { return "Cut"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class Paste : HtmlEditorExtenderButton { public override string CommandName { get { return "Paste"; } } public override string Tooltip { get { return "Paste"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class CleanWord : HtmlEditorExtenderButton { public override string CommandName { get { return "CleanWord"; } } public override string Tooltip { get { return "Clean Word HTML"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class FontNameSelector : HtmlEditorExtenderButton { public override string CommandName { get { return "FontName"; } } public override string Tooltip { get { return "Font Name"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("font", new string[] { "face" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("face", new string[] { }); return attributeWhiteList; } } } public class FontSizeSelector : HtmlEditorExtenderButton { public override string CommandName { get { return "FontSize"; } } public override string Tooltip { get { return "Font Size"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("font", new string[] { "size" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("size", new string[] { }); return attributeWhiteList; } } } public class ForeColorSelector : HtmlEditorExtenderButton { public override string CommandName { get { return "ForeColor"; } } public override string Tooltip { get { return "Fore Color"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("font", new string[] { "color" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("color", new string[] { }); return attributeWhiteList; } } } public class Indent : HtmlEditorExtenderButton { public override string CommandName { get { return "Indent"; } } public override string Tooltip { get { return "Indent"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("blockquote", new string[] { "style", "dir" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("style", new string[] { "margin-right", "margin", "padding", "border" }); attributeWhiteList.Add("dir", new string[] { "ltr", "rtl", "auto" }); return attributeWhiteList; } } } public class InsertHorizontalRule : HtmlEditorExtenderButton { public override string CommandName { get { return "InsertHorizontalRule"; } } public override string Tooltip { get { return "Insert Horizontal Rule"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("hr", new string[] { "size", "width" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("size", new string[] { }); attributeWhiteList.Add("width", new string[] { }); return attributeWhiteList; } } } public class Outdent : HtmlEditorExtenderButton { public override string CommandName { get { return "Outdent"; } } public override string Tooltip { get { return "Outdent"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class RemoveFormat : HtmlEditorExtenderButton { public override string CommandName { get { return "RemoveFormat"; } } public override string Tooltip { get { return "Remove Format"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class HorizontalSeparator : HtmlEditorExtenderButton { public override string CommandName { get { return "HorizontalSeparator"; } } public override string Tooltip { get { return "Separator"; } } public override Dictionary<string, string[]> ElementWhiteList { get { return null; } } public override Dictionary<string, string[]> AttributeWhiteList { get { return null; } } } public class InsertImage : HtmlEditorExtenderButton { public override string CommandName { get { return "InsertImage"; } } public override string Tooltip { get { return "Insert Image"; } } public override Dictionary<string, string[]> ElementWhiteList { get { var elementWhiteList = new Dictionary<string, string[]>(); elementWhiteList.Add("img", new string[] { "src" }); return elementWhiteList; } } public override Dictionary<string, string[]> AttributeWhiteList { get { var attributeWhiteList = new Dictionary<string, string[]>(); attributeWhiteList.Add("src", new string[] { }); return attributeWhiteList; } } } #endregion } #pragma warning restore 1591
/* Copyright (c) 2001 Lapo Luchini. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ /* This file is a port of jzlib v1.0.7, com.jcraft.jzlib.ZInputStream.java */ using System; using System.Diagnostics; using System.IO; namespace Raksha.Utilities.Zlib { public class ZInputStream : Stream { private const int BufferSize = 512; protected ZStream z = new ZStream(); protected int flushLevel = JZlib.Z_NO_FLUSH; // TODO Allow custom buf protected byte[] buf = new byte[BufferSize]; protected byte[] buf1 = new byte[1]; protected bool compress; protected Stream input; protected bool closed; private bool nomoreinput = false; public ZInputStream(Stream input) : this(input, false) { } public ZInputStream(Stream input, bool nowrap) { Debug.Assert(input.CanRead); this.input = input; this.z.inflateInit(nowrap); this.compress = false; this.z.next_in = buf; this.z.next_in_index = 0; this.z.avail_in = 0; } public ZInputStream(Stream input, int level) { Debug.Assert(input.CanRead); this.input = input; this.z.deflateInit(level); this.compress = true; this.z.next_in = buf; this.z.next_in_index = 0; this.z.avail_in = 0; } /*public int available() throws IOException { return inf.finished() ? 0 : 1; }*/ public sealed override bool CanRead { get { return !closed; } } public sealed override bool CanSeek { get { return false; } } public sealed override bool CanWrite { get { return false; } } protected override void Dispose(bool disposing) { try { if (!disposing || closed) { return; } closed = true; input.Dispose(); } finally { base.Dispose(disposing); } } public sealed override void Flush() {} public virtual int FlushMode { get { return flushLevel; } set { this.flushLevel = value; } } public sealed override long Length { get { throw new NotSupportedException(); } } public sealed override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] b, int off, int len) { if (len==0) return 0; z.next_out = b; z.next_out_index = off; z.avail_out = len; int err; do { if (z.avail_in == 0 && !nomoreinput) { // if buffer is empty and more input is available, refill it z.next_in_index = 0; z.avail_in = input.Read(buf, 0, buf.Length); //(bufsize<z.avail_out ? bufsize : z.avail_out)); if (z.avail_in <= 0) { z.avail_in = 0; nomoreinput = true; } } err = compress ? z.deflate(flushLevel) : z.inflate(flushLevel); if (nomoreinput && err == JZlib.Z_BUF_ERROR) return 0; if (err != JZlib.Z_OK && err != JZlib.Z_STREAM_END) // TODO // throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg); throw new IOException((compress ? "de" : "in") + "flating: " + z.msg); if ((nomoreinput || err == JZlib.Z_STREAM_END) && z.avail_out == len) return 0; } while(z.avail_out == len && err == JZlib.Z_OK); //Console.Error.WriteLine("("+(len-z.avail_out)+")"); return len - z.avail_out; } public override int ReadByte() { if (Read(buf1, 0, 1) <= 0) return -1; return buf1[0]; } // public long skip(long n) throws IOException { // int len=512; // if(n<len) // len=(int)n; // byte[] tmp=new byte[len]; // return((long)read(tmp)); // } public sealed override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public sealed override void SetLength(long value) { throw new NotSupportedException(); } public virtual long TotalIn { get { return z.total_in; } } public virtual long TotalOut { get { return z.total_out; } } public sealed override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } }
using System; using System.Threading.Tasks; using Cirrious.MvvmCross.ViewModels; using System.Windows.Input; using WTM.Core.Services; using WTM.Domain; namespace WTM.Mobile.Core.ViewModels { public class ShotViewModel : ViewModelBase { private readonly IShotService shotService; public ShotViewModel(IContext context, IShotService shotService) : base(context) { this.shotService = shotService; } public void Init(int shotId) { NavigateToShotByIdCommand.Execute(shotId); } private void Reset() { InvokeOnMainThread(() => { Response = null; GuessTitle = null; }); } public Shot Shot { get { return shot; } set { shot = value; RaiseAllPropertiesChanged(); } } private Shot shot; public string GuessTitle { get { return guessTitle; } set { guessTitle = value; RaisePropertyChanged(() => GuessTitle); } } private string guessTitle; public GuessTitleResponse Response { get { return response; } set { response = value; RaisePropertyChanged(() => Response); } } private GuessTitleResponse response; protected override void ExecuteSyncAction(Action action) { var actionWithReset = new Action(() => { Reset(); action(); }); base.ExecuteSyncAction(actionWithReset); } #region NavigateToFirstShotCommand public ICommand NavigateToFirstShotCommand { get { if (navigateToFirstShotCommand == null) { navigateToFirstShotCommand = new MvxCommand(() => { ExecuteSyncAction(() => Shot = shotService.GetById(Shot.Navigation.FirstId.Value, Context.Token)); }, () => { return Shot != null && Shot.Navigation != null && Shot.Navigation.FirstId.HasValue && Shot.Navigation.FirstId.Value != Shot.ShotId; }); } return navigateToFirstShotCommand; } } private MvxCommand navigateToFirstShotCommand; #endregion #region NavigateToPreviousShotCommand public ICommand NavigateToPreviousShotCommand { get { if (navigateToPreviousShotCommand == null) { navigateToPreviousShotCommand = new MvxCommand(() => { ExecuteSyncAction(() => { // ToDo : Choose between previous and unsolved previous Shot = shotService.GetById(Shot.Navigation.PreviousId.Value, Context.Token); }); }, () => { return Shot != null && Shot.Navigation != null && Shot.Navigation.PreviousId.HasValue && Shot.Navigation.PreviousId.Value != Shot.ShotId; }); } return navigateToPreviousShotCommand; } } private MvxCommand navigateToPreviousShotCommand; #endregion #region NavigateToRandomShotCommand public ICommand NavigateToRandomShotCommand { get { if (navigateToRandomShotCommand == null) { navigateToRandomShotCommand = new MvxCommand(() => ExecuteSyncAction(() => Shot = shotService.GetRandomShot(Context.Token))); } return navigateToRandomShotCommand; } } private MvxCommand navigateToRandomShotCommand; #endregion #region NavigateToNextShotCommand public ICommand NavigateToNextShotCommand { get { if (navigateToNextShotCommand == null) { navigateToNextShotCommand = new MvxCommand(() => { ExecuteSyncAction(() => { // ToDo : Choose between next and unsolved next previous Shot = shotService.GetById(Shot.Navigation.NextId.Value, Context.Token); }); }, () => { return Shot != null && Shot.Navigation != null && Shot.Navigation.NextId.HasValue && Shot.Navigation.NextId.Value != Shot.ShotId; }); } return navigateToNextShotCommand; } } private MvxCommand navigateToNextShotCommand; #endregion #region NavigateToLastShotCommand public ICommand NavigateToLastShotCommand { get { if (navigateToLastShotCommand == null) { navigateToLastShotCommand = new MvxCommand(() => { ExecuteSyncAction(() => Shot = shotService.GetById(Shot.Navigation.LastId.Value, Context.Token)); }, () => { return Shot != null && Shot.Navigation != null && Shot.Navigation.LastId.HasValue && Shot.Navigation.LastId.Value != Shot.ShotId; }); } return navigateToLastShotCommand; } } private MvxCommand navigateToLastShotCommand; #endregion #region NavigateToShotByIdCommand public ICommand NavigateToShotByIdCommand { get { if (navigateToShotByIdCommand == null) { navigateToShotByIdCommand = new MvxCommand<int>(shotId => ExecuteSyncAction(() => { Shot = shotService.GetById(shotId, Context.Token); })); } return navigateToShotByIdCommand; } } private MvxCommand<int> navigateToShotByIdCommand; #endregion #region GuessTitleCommand public ICommand GuessTitleCommand { get { if (guessTitleCommand == null) { guessTitleCommand = new MvxCommand(() => { InvokeOnMainThread(() => Busy = true); Task.Run(() => { try { if (!string.IsNullOrWhiteSpace(GuessTitle)) { Response = shotService.GuessTitle(shot.ShotId, GuessTitle, Context.Token); } else { Response = null; } } finally { InvokeOnMainThread(() => Busy = false); } }); }, () => { return Shot != null; }); } return guessTitleCommand; } } private MvxCommand guessTitleCommand; #endregion #region GetSolutionCommand public ICommand GetSolutionCommand { get { if (getSolutionCommand == null) { getSolutionCommand = new MvxCommand(() => { InvokeOnMainThread(() => Busy = true); Task.Run(() => { try { Response = shotService.GetSolution(Shot.ShotId, Context.Token); } finally { InvokeOnMainThread(() => Busy = false); } }); }, () => { return Shot != null && Shot.IsSolutionAvailable.GetValueOrDefault(false); }); } return getSolutionCommand; } } private MvxCommand getSolutionCommand; #endregion #region ShowMovieDetailCommand public ICommand ShowMovieDetailCommand { get { if (showMovieDetailCommand == null) { showMovieDetailCommand = new MvxCommand(() => ShowViewModel<MovieViewModel>(new { movieId = Response.MovieId })); } return showMovieDetailCommand; } } private MvxCommand showMovieDetailCommand; #endregion #region ShowUser public ICommand ShowUserCommand { get { if (showUserCommand == null) { showUserCommand = new MvxCommand(() => ShowViewModel<UserViewModel>(new { username = Shot.FirstSolver })); } return showUserCommand; } } private MvxCommand showUserCommand; #endregion #region ShowFullscreenShotCommand public ICommand ShowFullscreenShotCommand { get { if (showFullscreenShotCommand == null) { showFullscreenShotCommand = new MvxCommand(() => ShowViewModel<ShotFullscreenViewModel>(new { uri = Shot.ImageUri.ToString() })); } return showFullscreenShotCommand; } } private MvxCommand showFullscreenShotCommand; #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.NotificationHubs; using Microsoft.Azure.Management.NotificationHubs.Models; namespace Microsoft.Azure.Management.NotificationHubs { /// <summary> /// .Net client wrapper for the REST API for Azure NotificationHub Service /// </summary> public static partial class NamespaceOperationsExtensions { /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static NamespaceLongRunningResponse BeginDelete(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).BeginDeleteAsync(resourceGroupName, namespaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<NamespaceLongRunningResponse> BeginDeleteAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return operations.BeginDeleteAsync(resourceGroupName, namespaceName, CancellationToken.None); } /// <summary> /// Checks the availability of the given service namespace across all /// Windows Azure subscriptions. This is useful because the domain /// name is created based on the service namespace name. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='parameters'> /// Required. The namespace name. /// </param> /// <returns> /// Response of the Check NameAvailability operation. /// </returns> public static CheckAvailabilityResponse CheckAvailability(this INamespaceOperations operations, CheckAvailabilityParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).CheckAvailabilityAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks the availability of the given service namespace across all /// Windows Azure subscriptions. This is useful because the domain /// name is created based on the service namespace name. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='parameters'> /// Required. The namespace name. /// </param> /// <returns> /// Response of the Check NameAvailability operation. /// </returns> public static Task<CheckAvailabilityResponse> CheckAvailabilityAsync(this INamespaceOperations operations, CheckAvailabilityParameters parameters) { return operations.CheckAvailabilityAsync(parameters, CancellationToken.None); } /// <summary> /// Creates/Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create a Namespace Resource. /// </param> /// <returns> /// The response of the CreateOrUpdate Namespace. /// </returns> public static NamespaceCreateOrUpdateResponse CreateOrUpdate(this INamespaceOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates/Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// (see http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create a Namespace Resource. /// </param> /// <returns> /// The response of the CreateOrUpdate Namespace. /// </returns> public static Task<NamespaceCreateOrUpdateResponse> CreateOrUpdateAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters, CancellationToken.None); } /// <summary> /// The create namespace authorization rule operation creates an /// authorization rule for a namespace /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <param name='parameters'> /// Required. The shared access authorization rule. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the AuthorizationRules /// </returns> public static SharedAccessAuthorizationRuleCreateOrUpdateResponse CreateOrUpdateAuthorizationRule(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The create namespace authorization rule operation creates an /// authorization rule for a namespace /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <param name='parameters'> /// Required. The shared access authorization rule. /// </param> /// <returns> /// Response of the CreateOrUpdate operation on the AuthorizationRules /// </returns> public static Task<SharedAccessAuthorizationRuleCreateOrUpdateResponse> CreateOrUpdateAuthorizationRuleAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, CancellationToken.None); } /// <summary> /// Delete existing Namespace /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The name of the namespace. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static NamespaceLongRunningResponse Delete(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).DeleteAsync(resourceGroupName, namespaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete existing Namespace /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The name of the namespace. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<NamespaceLongRunningResponse> DeleteAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return operations.DeleteAsync(resourceGroupName, namespaceName, CancellationToken.None); } /// <summary> /// The delete a namespace authorization rule operation /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse DeleteAuthorizationRule(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete a namespace authorization rule operation /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Required. The namespace authorizationRuleName name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAuthorizationRuleAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, CancellationToken.None); } /// <summary> /// Returns the description for the specified namespace. (see /// http://msdn.microsoft.com/library/azure/dn140232.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <returns> /// The response of the Get Namespace operation. /// </returns> public static NamespaceGetResponse Get(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).GetAsync(resourceGroupName, namespaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns the description for the specified namespace. (see /// http://msdn.microsoft.com/library/azure/dn140232.aspx for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <returns> /// The response of the Get Namespace operation. /// </returns> public static Task<NamespaceGetResponse> GetAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return operations.GetAsync(resourceGroupName, namespaceName, CancellationToken.None); } /// <summary> /// The get authorization rule operation gets an authorization rule for /// a namespace by name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace to get the authorization rule for. /// </param> /// <param name='authorizationRuleName'> /// Required. The entity name to get the authorization rule for. /// </param> /// <returns> /// The response of the Get Namespace operation. /// </returns> public static SharedAccessAuthorizationRuleGetResponse GetAuthorizationRule(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The get authorization rule operation gets an authorization rule for /// a namespace by name. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace to get the authorization rule for. /// </param> /// <param name='authorizationRuleName'> /// Required. The entity name to get the authorization rule for. /// </param> /// <returns> /// The response of the Get Namespace operation. /// </returns> public static Task<SharedAccessAuthorizationRuleGetResponse> GetAuthorizationRuleAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, CancellationToken.None); } /// <summary> /// The Get namespace Delete Operation Status operation returns the /// status of the delete operation. After calling the operation, you /// can call Get namespace Delete Operation Status to determine /// whether the operation has succeeded, failed, or is still in /// progress. This method differs from GetLongRunningOperationStatus /// in providing NotificationHub service resource description. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static NamespaceLongRunningResponse GetDeleteNamespaceOperationStatus(this INamespaceOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).GetDeleteNamespaceOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get namespace Delete Operation Status operation returns the /// status of the delete operation. After calling the operation, you /// can call Get namespace Delete Operation Status to determine /// whether the operation has succeeded, failed, or is still in /// progress. This method differs from GetLongRunningOperationStatus /// in providing NotificationHub service resource description. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The response of the CreateOrUpdate Api Management service long /// running operation. /// </returns> public static Task<NamespaceLongRunningResponse> GetDeleteNamespaceOperationStatusAsync(this INamespaceOperations operations, string operationStatusLink) { return operations.GetDeleteNamespaceOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse GetLongRunningOperationStatus(this INamespaceOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).GetLongRunningOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(this INamespaceOperations operations, string operationStatusLink) { return operations.GetLongRunningOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Lists the available namespaces within a resourceGroup. (see /// http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. If resourceGroupName /// value is null the method lists all the namespaces within /// subscription /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static NamespaceListResponse List(this INamespaceOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists the available namespaces within a resourceGroup. (see /// http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. If resourceGroupName /// value is null the method lists all the namespaces within /// subscription /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static Task<NamespaceListResponse> ListAsync(this INamespaceOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. (see /// http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static NamespaceListResponse ListAll(this INamespaceOperations operations) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).ListAllAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. (see /// http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static Task<NamespaceListResponse> ListAllAsync(this INamespaceOperations operations) { return operations.ListAllAsync(CancellationToken.None); } /// <summary> /// The get authorization rules operation gets the authorization rules /// for a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace to get the authorization rule for. /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static SharedAccessAuthorizationRuleListResponse ListAuthorizationRules(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The get authorization rules operation gets the authorization rules /// for a namespace. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace to get the authorization rule for. /// </param> /// <returns> /// The response of the List Namespace operation. /// </returns> public static Task<SharedAccessAuthorizationRuleListResponse> ListAuthorizationRulesAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName) { return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, CancellationToken.None); } /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Required. The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <returns> /// Namespace/NotificationHub Connection String /// </returns> public static ResourceListKeys ListKeys(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return Task.Factory.StartNew((object s) => { return ((INamespaceOperations)s).ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.NotificationHubs.INamespaceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='namespaceName'> /// Required. The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Required. The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <returns> /// Namespace/NotificationHub Connection String /// </returns> public static Task<ResourceListKeys> ListKeysAsync(this INamespaceOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return operations.ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName, CancellationToken.None); } } }
/* * MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2020, 2021 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Linq; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Xml.Serialization; using Minio.DataModel; using Minio.DataModel.Tags; using Minio.DataModel.ObjectLock; namespace Minio { internal class SelectObjectContentResponse : GenericResponse { internal SelectResponseStream ResponseStream { get; private set; } internal SelectObjectContentResponse(HttpStatusCode statusCode, string responseContent, byte[] responseRawBytes) : base(statusCode, responseContent) { this.ResponseStream = new SelectResponseStream(new MemoryStream(responseRawBytes)); } } internal class StatObjectResponse : GenericResponse { internal ObjectStat ObjectInfo { get; set; } internal StatObjectResponse(HttpStatusCode statusCode, string responseContent, Dictionary<string, string> responseHeaders, StatObjectArgs args) : base(statusCode, responseContent) { // StatObjectResponse object is populated with available stats from the response. this.ObjectInfo = ObjectStat.FromResponseHeaders(args.ObjectName, responseHeaders); } } internal class RemoveObjectsResponse : GenericResponse { internal DeleteObjectsResult DeletedObjectsResult { get; private set; } internal RemoveObjectsResponse(HttpStatusCode statusCode, string responseContent) : base(statusCode, responseContent) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent))) { this.DeletedObjectsResult = (DeleteObjectsResult)new XmlSerializer(typeof(DeleteObjectsResult)).Deserialize(stream); } } } internal class GetMultipartUploadsListResponse : GenericResponse { internal Tuple<ListMultipartUploadsResult, List<Upload>> UploadResult { get; private set; } internal GetMultipartUploadsListResponse(HttpStatusCode statusCode, string responseContent) : base(statusCode, responseContent) { ListMultipartUploadsResult uploadsResult = null; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent))) { uploadsResult = (ListMultipartUploadsResult)new XmlSerializer(typeof(ListMultipartUploadsResult)).Deserialize(stream); } XDocument root = XDocument.Parse(responseContent); var itemCheck = root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}Upload").FirstOrDefault(); if (uploadsResult == null || itemCheck == null || !itemCheck.HasElements) { return; } var uploads = from c in root.Root.Descendants("{http://s3.amazonaws.com/doc/2006-03-01/}Upload") select new Upload { Key = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Key").Value, UploadId = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}UploadId").Value, Initiated = c.Element("{http://s3.amazonaws.com/doc/2006-03-01/}Initiated").Value }; this.UploadResult = new Tuple<ListMultipartUploadsResult, List<Upload>>(uploadsResult, uploads.ToList()); } } public class PresignedPostPolicyResponse { internal Tuple<string, Dictionary<string, string>> URIPolicyTuple { get; private set; } public PresignedPostPolicyResponse(PresignedPostPolicyArgs args, Uri URI) { URIPolicyTuple = Tuple.Create(URI.AbsolutePath, args.Policy.GetFormData()); } } public class GetLegalHoldResponse : GenericResponse { internal ObjectLegalHoldConfiguration CurrentLegalHoldConfiguration { get; private set; } internal string Status { get; private set; } public GetLegalHoldResponse(HttpStatusCode statusCode, string responseContent) : base(statusCode, responseContent) { if (string.IsNullOrEmpty(responseContent) || !HttpStatusCode.OK.Equals(statusCode)) { this.CurrentLegalHoldConfiguration = null; return; } using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent))) { CurrentLegalHoldConfiguration = (ObjectLegalHoldConfiguration)new XmlSerializer(typeof(ObjectLegalHoldConfiguration)).Deserialize(stream); } if (this.CurrentLegalHoldConfiguration == null || string.IsNullOrEmpty(this.CurrentLegalHoldConfiguration.Status)) { Status = "OFF"; } else { Status = this.CurrentLegalHoldConfiguration.Status; } } } internal class GetObjectTagsResponse : GenericResponse { public GetObjectTagsResponse(HttpStatusCode statusCode, string responseContent) : base(statusCode, responseContent) { if (string.IsNullOrEmpty(responseContent) || !HttpStatusCode.OK.Equals(statusCode)) { this.ObjectTags = null; return; } responseContent = utils.RemoveNamespaceInXML(responseContent); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent))) { this.ObjectTags = (Tagging)new XmlSerializer(typeof(Tagging)).Deserialize(stream); } } public Tagging ObjectTags { get; set; } } internal class GetRetentionResponse : GenericResponse { internal ObjectRetentionConfiguration CurrentRetentionConfiguration { get; private set; } public GetRetentionResponse(HttpStatusCode statusCode, string responseContent) : base(statusCode, responseContent) { if (string.IsNullOrEmpty(responseContent) && !HttpStatusCode.OK.Equals(statusCode)) { this.CurrentRetentionConfiguration = null; return; } using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent))) { CurrentRetentionConfiguration = (ObjectRetentionConfiguration)new XmlSerializer(typeof(ObjectRetentionConfiguration)).Deserialize(stream); } } } internal class CopyObjectResponse : GenericResponse { internal CopyObjectResult CopyObjectRequestResult { get; set; } internal CopyPartResult CopyPartRequestResult { get; set; } public CopyObjectResponse(HttpStatusCode statusCode, string content, Type reqType) : base(statusCode, content) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content))) { if (reqType == typeof(CopyObjectResult)) { this.CopyObjectRequestResult = (CopyObjectResult)new XmlSerializer(typeof(CopyObjectResult)).Deserialize(stream); } else { this.CopyPartRequestResult = (CopyPartResult)new XmlSerializer(typeof(CopyPartResult)).Deserialize(stream); } } } } internal class NewMultipartUploadResponse : GenericResponse { internal string UploadId { get; private set; } internal NewMultipartUploadResponse(HttpStatusCode statusCode, string responseContent) : base(statusCode, responseContent) { InitiateMultipartUploadResult newUpload = null; using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent))) { newUpload = (InitiateMultipartUploadResult)new XmlSerializer(typeof(InitiateMultipartUploadResult)).Deserialize(stream); } this.UploadId = newUpload.UploadId; } } internal class PutObjectResponse : GenericResponse { internal string Etag; internal PutObjectResponse(HttpStatusCode statusCode, string responseContent, Dictionary<string, string> responseHeaders) : base(statusCode, responseContent) { if (responseHeaders.ContainsKey("Etag")) { if (!string.IsNullOrEmpty("Etag")) this.Etag = responseHeaders["ETag"]; return; } foreach (KeyValuePair<string, string> parameter in responseHeaders) { if (parameter.Key.Equals("ETag", StringComparison.OrdinalIgnoreCase)) { this.Etag = parameter.Value.ToString(); return; } } } } }
//------------------------------------------------------------------------------ // <copyright file="Int16Storage.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.Common { using System; using System.Xml; using System.Data.SqlTypes; using System.Collections; internal sealed class Int16Storage : DataStorage { private const Int16 defaultValue = 0; private Int16[] values; internal Int16Storage(DataColumn column) : base(column, typeof(Int16), defaultValue, StorageType.Int16) { } override public Object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: Int64 sum = defaultValue; foreach (int record in records) { if (HasValue(record)) { checked { sum += values[record];} hasData = true; } } if (hasData) { return sum; } return NullValue; case AggregateType.Mean: Int64 meanSum = (Int64)defaultValue; int meanCount = 0; foreach (int record in records) { if (HasValue(record)) { checked { meanSum += (Int64)values[record];} meanCount++; hasData = true; } } if (hasData) { Int16 mean; checked {mean = (Int16)(meanSum / meanCount);} return mean; } return NullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = 0.0f; double prec = 0.0f; double dsum = 0.0f; double sqrsum = 0.0f; foreach (int record in records) { if (HasValue(record)) { dsum += (double)values[record]; sqrsum += (double)values[record]*(double)values[record]; count++; } } if (count > 1) { var = ((double)count * sqrsum - (dsum * dsum)); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var <0)) var = 0; else var = var / (count * (count -1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return NullValue; case AggregateType.Min: Int16 min = Int16.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { min=Math.Min(values[record], min); hasData = true; } } if (hasData) { return min; } return NullValue; case AggregateType.Max: Int16 max = Int16.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { max=Math.Max(values[record], max); hasData = true; } } if (hasData) { return max; } return NullValue; case AggregateType.First: if (records.Length > 0) { return values[records[0]]; } return null; case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) { if (HasValue(records[i])) { count++; } } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(Int16)); } throw ExceptionBuilder.AggregateException(kind, DataType); } override public int Compare(int recordNo1, int recordNo2) { Int16 valueNo1 = values[recordNo1]; Int16 valueNo2 = values[recordNo2]; if (valueNo1 == defaultValue || valueNo2 == defaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) { return bitCheck; } } //return valueNo1.CompareTo(valueNo2); return(valueNo1 - valueNo2); // copied from Int16.CompareTo(Int16) } public override int CompareValueTo(int recordNo, object value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (NullValue == value) { return (HasValue(recordNo) ? 1 : 0); } Int16 valueNo1 = values[recordNo]; if ((defaultValue == valueNo1) && !HasValue(recordNo)) { return -1; } return valueNo1.CompareTo((Int16)value); //return(valueNo1 - valueNo2); // copied from Int16.CompareTo(Int16) } public override object ConvertValue(object value) { if (NullValue != value) { if (null != value) { value = ((IConvertible)value).ToInt16(FormatProvider); } else { value = NullValue; } } return value; } override public void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); values[recordNo2] = values[recordNo1]; } override public Object Get(int record) { Int16 value = values[record]; if (value != defaultValue) { return value; } return GetBits(record); } override public void Set(int record, Object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (NullValue == value) { values[record] = defaultValue; SetNullBit(record, true); } else { values[record] = ((IConvertible)value).ToInt16(FormatProvider); SetNullBit(record, false); } } override public void SetCapacity(int capacity) { Int16[] newValues = new Int16[capacity]; if (null != values) { Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length)); } values = newValues; base.SetCapacity(capacity); } override public object ConvertXmlToObject(string s) { return XmlConvert.ToInt16(s); } override public string ConvertObjectToXml(object value) { return XmlConvert.ToString((Int16) value); } override protected object GetEmptyStorage(int recordCount) { return new Int16[recordCount]; } override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { Int16[] typedStore = (Int16[]) store; typedStore[storeIndex] = values[record]; nullbits.Set(storeIndex, !HasValue(record)); } override protected void SetStorage(object store, BitArray nullbits) { values = (Int16[]) store; SetNullStorage(nullbits); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection.Emit { using System; using System.Reflection; using CultureInfo = System.Globalization.CultureInfo; using System.Collections.Generic; using System.Diagnostics.SymbolStore; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_ConstructorBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder { private readonly MethodBuilder m_methodBuilder; internal bool m_isDefaultConstructor; #region Constructor private ConstructorBuilder() { } [System.Security.SecurityCritical] // auto-generated internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type) { int sigLength; byte[] sigBytes; MethodToken token; m_methodBuilder = new MethodBuilder(name, attributes, callingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers, mod, type, false); type.m_listMethods.Add(m_methodBuilder); sigBytes = m_methodBuilder.GetMethodSignature().InternalGetSignature(out sigLength); token = m_methodBuilder.GetToken(); } [System.Security.SecurityCritical] // auto-generated internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) : this(name, attributes, callingConvention, parameterTypes, null, null, mod, type) { } #endregion #region Internal internal override Type[] GetParameterTypes() { return m_methodBuilder.GetParameterTypes(); } private TypeBuilder GetTypeBuilder() { return m_methodBuilder.GetTypeBuilder(); } internal ModuleBuilder GetModuleBuilder() { return GetTypeBuilder().GetModuleBuilder(); } #endregion #region Object Overrides public override String ToString() { return m_methodBuilder.ToString(); } #endregion #region MemberInfo Overrides internal int MetadataTokenInternal { get { return m_methodBuilder.MetadataTokenInternal; } } public override Module Module { get { return m_methodBuilder.Module; } } public override Type ReflectedType { get { return m_methodBuilder.ReflectedType; } } public override Type DeclaringType { get { return m_methodBuilder.DeclaringType; } } public override String Name { get { return m_methodBuilder.Name; } } #endregion #region MethodBase Overrides public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } [Pure] public override ParameterInfo[] GetParameters() { ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes); return rci.GetParameters(); } public override MethodAttributes Attributes { get { return m_methodBuilder.Attributes; } } public override MethodImplAttributes GetMethodImplementationFlags() { return m_methodBuilder.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { return m_methodBuilder.MethodHandle; } } #endregion #region ConstructorInfo Overrides public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { return m_methodBuilder.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_methodBuilder.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined (Type attributeType, bool inherit) { return m_methodBuilder.IsDefined(attributeType, inherit); } #endregion #region Public Members public MethodToken GetToken() { return m_methodBuilder.GetToken(); } public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, String strParamName) { // Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have // return parameters. But we'll allow it for backward compatibility with V2. The attributes // defined on the return parameters won't be very useful but won't do much harm either. // MD will assert if we try to set the reserved bits explicitly attributes = attributes & ~ParameterAttributes.ReservedMask; return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName); } public void SetSymCustomAttribute(String name, byte[] data) { m_methodBuilder.SetSymCustomAttribute(name, data); } public ILGenerator GetILGenerator() { if (m_isDefaultConstructor) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen")); return m_methodBuilder.GetILGenerator(); } public ILGenerator GetILGenerator(int streamSize) { if (m_isDefaultConstructor) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen")); return m_methodBuilder.GetILGenerator(streamSize); } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups) { if (m_isDefaultConstructor) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorDefineBody")); } m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups); } #if FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) { if (pset == null) throw new ArgumentNullException(nameof(pset)); #pragma warning disable 618 if (!Enum.IsDefined(typeof(SecurityAction), action) || action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) { throw new ArgumentOutOfRangeException(nameof(action)); } #pragma warning restore 618 Contract.EndContractBlock(); // Cannot add declarative security after type is created. if (m_methodBuilder.IsTypeCreated()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated")); // Translate permission set into serialized format (use standard binary serialization). byte[] blob = pset.EncodeXml(); // Write the blob into the metadata. TypeBuilder.AddDeclarativeSecurity(GetModuleBuilder().GetNativeHandle(), GetToken().Token, action, blob, blob.Length); } #endif // FEATURE_CAS_POLICY public override CallingConventions CallingConvention { get { if (DeclaringType.IsGenericType) return CallingConventions.HasThis; return CallingConventions.Standard; } } public Module GetModule() { return m_methodBuilder.GetModule(); } [Obsolete("This property has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] //It always returns null. public Type ReturnType { get { return GetReturnType(); } } // This always returns null. Is that what we want? internal override Type GetReturnType() { return m_methodBuilder.ReturnType; } public String Signature { get { return m_methodBuilder.Signature; } } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_methodBuilder.SetCustomAttribute(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { m_methodBuilder.SetCustomAttribute(customBuilder); } public void SetImplementationFlags(MethodImplAttributes attributes) { m_methodBuilder.SetImplementationFlags(attributes); } public bool InitLocals { get { return m_methodBuilder.InitLocals; } set { m_methodBuilder.InitLocals = value; } } #endregion #if !FEATURE_CORECLR void _ConstructorBuilder.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _ConstructorBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _ConstructorBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _ConstructorBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Buffers { using System; using System.Diagnostics.Contracts; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using DotNetty.Common; using DotNetty.Common.Utilities; /// <summary> /// Abstract base class implementation of a <see cref="IByteBuffer" /> /// </summary> public abstract class AbstractByteBuffer : IByteBuffer { internal static readonly ResourceLeakDetector LeakDetector = ResourceLeakDetector.Create<IByteBuffer>(); int markedReaderIndex; int markedWriterIndex; SwappedByteBuffer swappedByteBuffer; protected AbstractByteBuffer(int maxCapacity) { this.MaxCapacity = maxCapacity; } public abstract int Capacity { get; } public abstract IByteBuffer AdjustCapacity(int newCapacity); public int MaxCapacity { get; protected set; } public abstract IByteBufferAllocator Allocator { get; } public virtual int ReaderIndex { get; protected set; } public virtual int WriterIndex { get; protected set; } public virtual IByteBuffer SetWriterIndex(int writerIndex) { if (writerIndex < this.ReaderIndex || writerIndex > this.Capacity) { throw new IndexOutOfRangeException($"WriterIndex: {writerIndex} (expected: 0 <= readerIndex({this.ReaderIndex}) <= writerIndex <= capacity ({this.Capacity})"); } this.WriterIndex = writerIndex; return this; } public virtual IByteBuffer SetReaderIndex(int readerIndex) { if (readerIndex < 0 || readerIndex > this.WriterIndex) { throw new IndexOutOfRangeException($"ReaderIndex: {readerIndex} (expected: 0 <= readerIndex <= writerIndex({this.WriterIndex})"); } this.ReaderIndex = readerIndex; return this; } public virtual IByteBuffer SetIndex(int readerIndex, int writerIndex) { if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > this.Capacity) { throw new IndexOutOfRangeException($"ReaderIndex: {readerIndex}, WriterIndex: {writerIndex} (expected: 0 <= readerIndex <= writerIndex <= capacity ({this.Capacity})"); } this.ReaderIndex = readerIndex; this.WriterIndex = writerIndex; return this; } public virtual int ReadableBytes => this.WriterIndex - this.ReaderIndex; public virtual int WritableBytes => this.Capacity - this.WriterIndex; public virtual int MaxWritableBytes => this.MaxCapacity - this.WriterIndex; public bool IsReadable() => this.IsReadable(1); public bool IsReadable(int size) => this.ReadableBytes >= size; public bool IsWritable() => this.IsWritable(1); public bool IsWritable(int size) => this.WritableBytes >= size; public virtual IByteBuffer Clear() { this.ReaderIndex = this.WriterIndex = 0; return this; } public virtual IByteBuffer MarkReaderIndex() { this.markedReaderIndex = this.ReaderIndex; return this; } public virtual IByteBuffer ResetReaderIndex() { this.SetReaderIndex(this.markedReaderIndex); return this; } public virtual IByteBuffer MarkWriterIndex() { this.markedWriterIndex = this.WriterIndex; return this; } public virtual IByteBuffer ResetWriterIndex() { this.SetWriterIndex(this.markedWriterIndex); return this; } public virtual IByteBuffer DiscardReadBytes() { this.EnsureAccessible(); if (this.ReaderIndex == 0) { return this; } if (this.ReaderIndex != this.WriterIndex) { this.SetBytes(0, this, this.ReaderIndex, this.WriterIndex - this.ReaderIndex); this.WriterIndex -= this.ReaderIndex; this.AdjustMarkers(this.ReaderIndex); this.ReaderIndex = 0; } else { this.AdjustMarkers(this.ReaderIndex); this.WriterIndex = this.ReaderIndex = 0; } return this; } public virtual IByteBuffer DiscardSomeReadBytes() { this.EnsureAccessible(); if (this.ReaderIndex == 0) { return this; } if (this.ReaderIndex == this.WriterIndex) { this.AdjustMarkers(this.ReaderIndex); this.WriterIndex = this.ReaderIndex = 0; return this; } if (this.ReaderIndex >= this.Capacity.RightUShift(1)) { this.SetBytes(0, this, this.ReaderIndex, this.WriterIndex - this.ReaderIndex); this.WriterIndex -= this.ReaderIndex; this.AdjustMarkers(this.ReaderIndex); this.ReaderIndex = 0; } return this; } public virtual IByteBuffer EnsureWritable(int minWritableBytes) { if (minWritableBytes < 0) { throw new ArgumentOutOfRangeException(nameof(minWritableBytes), "expected minWritableBytes to be greater than zero"); } if (minWritableBytes <= this.WritableBytes) { return this; } if (minWritableBytes > this.MaxCapacity - this.WriterIndex) { throw new IndexOutOfRangeException($"writerIndex({this.WriterIndex}) + minWritableBytes({minWritableBytes}) exceeds maxCapacity({this.MaxCapacity}): {this}"); } //Normalize the current capacity to the power of 2 int newCapacity = this.CalculateNewCapacity(this.WriterIndex + minWritableBytes); //Adjust to the new capacity this.AdjustCapacity(newCapacity); return this; } public int EnsureWritable(int minWritableBytes, bool force) { Contract.Ensures(minWritableBytes >= 0); if (minWritableBytes <= this.WritableBytes) { return 0; } if (minWritableBytes > this.MaxCapacity - this.WriterIndex) { if (force) { if (this.Capacity == this.MaxCapacity) { return 1; } this.AdjustCapacity(this.MaxCapacity); return 3; } } // Normalize the current capacity to the power of 2. int newCapacity = this.CalculateNewCapacity(this.WriterIndex + minWritableBytes); // Adjust to the new capacity. this.AdjustCapacity(newCapacity); return 2; } int CalculateNewCapacity(int minNewCapacity) { int maxCapacity = this.MaxCapacity; const int Threshold = 4 * 1024 * 1024; // 4 MiB page int newCapacity; if (minNewCapacity == Threshold) { return Threshold; } // If over threshold, do not double but just increase by threshold. if (minNewCapacity > Threshold) { newCapacity = minNewCapacity - (minNewCapacity % Threshold); return Math.Min(maxCapacity, newCapacity + Threshold); } // Not over threshold. Double up to 4 MiB, starting from 64. newCapacity = 64; while (newCapacity < minNewCapacity) { newCapacity <<= 1; } return Math.Min(newCapacity, maxCapacity); } public virtual bool GetBoolean(int index) => this.GetByte(index) != 0; public virtual byte GetByte(int index) { this.CheckIndex(index); return this._GetByte(index); } protected abstract byte _GetByte(int index); public virtual short GetShort(int index) { this.CheckIndex(index, 2); return this._GetShort(index); } protected abstract short _GetShort(int index); public virtual ushort GetUnsignedShort(int index) { unchecked { return (ushort)(this.GetShort(index)); } } public virtual int GetInt(int index) { this.CheckIndex(index, 4); return this._GetInt(index); } protected abstract int _GetInt(int index); public virtual uint GetUnsignedInt(int index) { unchecked { return (uint)(this.GetInt(index)); } } public virtual long GetLong(int index) { this.CheckIndex(index, 8); return this._GetLong(index); } protected abstract long _GetLong(int index); public virtual char GetChar(int index) => Convert.ToChar(this.GetShort(index)); public virtual double GetDouble(int index) => BitConverter.Int64BitsToDouble(this.GetLong(index)); public virtual IByteBuffer GetBytes(int index, IByteBuffer destination) { this.GetBytes(index, destination, destination.WritableBytes); return this; } public virtual IByteBuffer GetBytes(int index, IByteBuffer destination, int length) { this.GetBytes(index, destination, destination.WriterIndex, length); destination.SetWriterIndex(destination.WriterIndex + length); return this; } public abstract IByteBuffer GetBytes(int index, IByteBuffer destination, int dstIndex, int length); public virtual IByteBuffer GetBytes(int index, byte[] destination) { this.GetBytes(index, destination, 0, destination.Length); return this; } public abstract IByteBuffer GetBytes(int index, byte[] destination, int dstIndex, int length); public abstract IByteBuffer GetBytes(int index, Stream destination, int length); public virtual IByteBuffer SetBoolean(int index, bool value) { this.SetByte(index, value ? 1 : 0); return this; } public virtual IByteBuffer SetByte(int index, int value) { this.CheckIndex(index); this._SetByte(index, value); return this; } protected abstract void _SetByte(int index, int value); public virtual IByteBuffer SetShort(int index, int value) { this.CheckIndex(index, 2); this._SetShort(index, value); return this; } public IByteBuffer SetUnsignedShort(int index, ushort value) { this.SetShort(index, value); return this; } protected abstract void _SetShort(int index, int value); public virtual IByteBuffer SetInt(int index, int value) { this.CheckIndex(index, 4); this._SetInt(index, value); return this; } public IByteBuffer SetUnsignedInt(int index, uint value) { unchecked { this.SetInt(index, (int)value); } return this; } protected abstract void _SetInt(int index, int value); public virtual IByteBuffer SetLong(int index, long value) { this.CheckIndex(index, 8); this._SetLong(index, value); return this; } protected abstract void _SetLong(int index, long value); public virtual IByteBuffer SetChar(int index, char value) { this.SetShort(index, value); return this; } public virtual IByteBuffer SetDouble(int index, double value) { this.SetLong(index, BitConverter.DoubleToInt64Bits(value)); return this; } public virtual IByteBuffer SetBytes(int index, IByteBuffer src) { this.SetBytes(index, src, src.ReadableBytes); return this; } public virtual IByteBuffer SetBytes(int index, IByteBuffer src, int length) { this.CheckIndex(index, length); if (src == null) { throw new NullReferenceException("src cannot be null"); } if (length > src.ReadableBytes) { throw new IndexOutOfRangeException($"length({length}) exceeds src.readableBytes({src.ReadableBytes}) where src is: {src}"); } this.SetBytes(index, src, src.ReaderIndex, length); src.SetReaderIndex(src.ReaderIndex + length); return this; } public abstract IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length); public virtual IByteBuffer SetBytes(int index, byte[] src) { this.SetBytes(index, src, 0, src.Length); return this; } public abstract IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length); public abstract Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken); public virtual bool ReadBoolean() => this.ReadByte() != 0; public virtual byte ReadByte() { this.CheckReadableBytes(1); int i = this.ReaderIndex; byte b = this.GetByte(i); this.ReaderIndex = i + 1; return b; } public virtual short ReadShort() { this.CheckReadableBytes(2); short v = this._GetShort(this.ReaderIndex); this.ReaderIndex += 2; return v; } public virtual ushort ReadUnsignedShort() { unchecked { return (ushort)(this.ReadShort()); } } public virtual int ReadInt() { this.CheckReadableBytes(4); int v = this._GetInt(this.ReaderIndex); this.ReaderIndex += 4; return v; } public virtual uint ReadUnsignedInt() { unchecked { return (uint)(this.ReadInt()); } } public virtual long ReadLong() { this.CheckReadableBytes(8); long v = this._GetLong(this.ReaderIndex); this.ReaderIndex += 8; return v; } public virtual char ReadChar() => (char)this.ReadShort(); public virtual double ReadDouble() => BitConverter.Int64BitsToDouble(this.ReadLong()); public IByteBuffer ReadBytes(int length) { this.CheckReadableBytes(length); if (length == 0) { return Unpooled.Empty; } IByteBuffer buf = this.Allocator.Buffer(length, this.MaxCapacity); buf.WriteBytes(this, this.ReaderIndex, length); this.ReaderIndex += length; return buf; } public virtual IByteBuffer ReadBytes(IByteBuffer destination) { this.ReadBytes(destination, destination.WritableBytes); return this; } public virtual IByteBuffer ReadBytes(IByteBuffer destination, int length) { if (length > destination.WritableBytes) { throw new IndexOutOfRangeException($"length({length}) exceeds destination.WritableBytes({destination.WritableBytes}) where destination is: {destination}"); } this.ReadBytes(destination, destination.WriterIndex, length); destination.SetWriterIndex(destination.WriterIndex + length); return this; } public virtual IByteBuffer ReadBytes(IByteBuffer destination, int dstIndex, int length) { this.CheckReadableBytes(length); this.GetBytes(this.ReaderIndex, destination, dstIndex, length); this.ReaderIndex += length; return this; } public virtual IByteBuffer ReadBytes(byte[] destination) { this.ReadBytes(destination, 0, destination.Length); return this; } public virtual IByteBuffer ReadBytes(byte[] destination, int dstIndex, int length) { this.CheckReadableBytes(length); this.GetBytes(this.ReaderIndex, destination, dstIndex, length); this.ReaderIndex += length; return this; } public virtual IByteBuffer ReadBytes(Stream destination, int length) { this.CheckReadableBytes(length); this.GetBytes(this.ReaderIndex, destination, length); this.ReaderIndex += length; return this; } public virtual IByteBuffer SkipBytes(int length) { this.CheckReadableBytes(length); this.ReaderIndex += length; return this; } public virtual IByteBuffer WriteBoolean(bool value) { this.WriteByte(value ? 1 : 0); return this; } public virtual IByteBuffer WriteByte(int value) { this.EnsureAccessible(); this.EnsureWritable(1); this.SetByte(this.WriterIndex, value); this.WriterIndex += 1; return this; } public virtual IByteBuffer WriteShort(int value) { this.EnsureAccessible(); this.EnsureWritable(2); this._SetShort(this.WriterIndex, value); this.WriterIndex += 2; return this; } public IByteBuffer WriteUnsignedShort(ushort value) { unchecked { this.WriteShort((short)value); } return this; } public virtual IByteBuffer WriteInt(int value) { this.EnsureAccessible(); this.EnsureWritable(4); this._SetInt(this.WriterIndex, value); this.WriterIndex += 4; return this; } public IByteBuffer WriteUnsignedInt(uint value) { unchecked { this.WriteInt((int)value); } return this; } public virtual IByteBuffer WriteLong(long value) { this.EnsureAccessible(); this.EnsureWritable(8); this._SetLong(this.WriterIndex, value); this.WriterIndex += 8; return this; } public virtual IByteBuffer WriteChar(char value) { this.WriteShort(value); return this; } public virtual IByteBuffer WriteDouble(double value) { this.WriteLong(BitConverter.DoubleToInt64Bits(value)); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src) { this.WriteBytes(src, src.ReadableBytes); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src, int length) { if (length > src.ReadableBytes) { throw new IndexOutOfRangeException($"length({length}) exceeds src.readableBytes({src.ReadableBytes}) where src is: {src}"); } this.WriteBytes(src, src.ReaderIndex, length); src.SetReaderIndex(src.ReaderIndex + length); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src, int srcIndex, int length) { this.EnsureAccessible(); this.EnsureWritable(length); this.SetBytes(this.WriterIndex, src, srcIndex, length); this.WriterIndex += length; return this; } public virtual IByteBuffer WriteBytes(byte[] src) { this.WriteBytes(src, 0, src.Length); return this; } public virtual IByteBuffer WriteBytes(byte[] src, int srcIndex, int length) { this.EnsureAccessible(); this.EnsureWritable(length); this.SetBytes(this.WriterIndex, src, srcIndex, length); this.WriterIndex += length; return this; } public abstract int IoBufferCount { get; } public ArraySegment<byte> GetIoBuffer() => this.GetIoBuffer(this.ReaderIndex, this.ReadableBytes); public abstract ArraySegment<byte> GetIoBuffer(int index, int length); public ArraySegment<byte>[] GetIoBuffers() => this.GetIoBuffers(this.ReaderIndex, this.ReadableBytes); public abstract ArraySegment<byte>[] GetIoBuffers(int index, int length); public async Task WriteBytesAsync(Stream stream, int length, CancellationToken cancellationToken) { this.EnsureAccessible(); this.EnsureWritable(length); if (this.WritableBytes < length) { throw new ArgumentOutOfRangeException(nameof(length)); } int writerIndex = this.WriterIndex; int wrote = await this.SetBytesAsync(writerIndex, stream, length, cancellationToken); Contract.Assert(writerIndex == this.WriterIndex); this.SetWriterIndex(writerIndex + wrote); } public Task WriteBytesAsync(Stream stream, int length) => this.WriteBytesAsync(stream, length, CancellationToken.None); public abstract bool HasArray { get; } public abstract byte[] Array { get; } public abstract int ArrayOffset { get; } public virtual byte[] ToArray() { int readableBytes = this.ReadableBytes; if (readableBytes == 0) { return ArrayExtensions.ZeroBytes; } if (this.HasArray) { return this.Array.Slice(this.ArrayOffset + this.ReaderIndex, readableBytes); } var bytes = new byte[readableBytes]; this.GetBytes(this.ReaderIndex, bytes); return bytes; } public virtual IByteBuffer Duplicate() => new DuplicatedByteBuffer(this); public abstract IByteBuffer Unwrap(); public virtual ByteOrder Order // todo: push to actual implementations for them to decide => ByteOrder.BigEndian; public IByteBuffer WithOrder(ByteOrder order) { if (order == this.Order) { return this; } SwappedByteBuffer swappedBuf = this.swappedByteBuffer; if (swappedBuf == null) { this.swappedByteBuffer = swappedBuf = this.NewSwappedByteBuffer(); } return swappedBuf; } /// <summary> /// Creates a new <see cref="SwappedByteBuffer" /> for this <see cref="IByteBuffer" /> instance. /// </summary> /// <returns>A <see cref="SwappedByteBuffer" /> for this buffer.</returns> protected SwappedByteBuffer NewSwappedByteBuffer() => new SwappedByteBuffer(this); protected void AdjustMarkers(int decrement) { int markedReaderIndex = this.markedReaderIndex; if (markedReaderIndex <= decrement) { this.markedReaderIndex = 0; int markedWriterIndex = this.markedWriterIndex; if (markedWriterIndex <= decrement) { this.markedWriterIndex = 0; } else { this.markedWriterIndex = markedWriterIndex - decrement; } } else { this.markedReaderIndex = markedReaderIndex - decrement; this.markedWriterIndex -= decrement; } } public override int GetHashCode() => ByteBufferUtil.HashCode(this); public override bool Equals(object o) => this.Equals(o as IByteBuffer); public bool Equals(IByteBuffer buffer) { if (ReferenceEquals(this, buffer)) { return true; } if (buffer != null) { return ByteBufferUtil.Equals(this, buffer); } return false; } public int CompareTo(IByteBuffer that) => ByteBufferUtil.Compare(this, that); public override string ToString() { if (this.ReferenceCount == 0) { return StringUtil.SimpleClassName(this) + "(freed)"; } StringBuilder buf = new StringBuilder() .Append(StringUtil.SimpleClassName(this)) .Append("(ridx: ").Append(this.ReaderIndex) .Append(", widx: ").Append(this.WriterIndex) .Append(", cap: ").Append(this.Capacity); if (this.MaxCapacity != int.MaxValue) { buf.Append('/').Append(this.MaxCapacity); } IByteBuffer unwrapped = this.Unwrap(); if (unwrapped != null) { buf.Append(", unwrapped: ").Append(unwrapped); } buf.Append(')'); return buf.ToString(); } protected void CheckIndex(int index) { this.EnsureAccessible(); if (index < 0 || index >= this.Capacity) { throw new IndexOutOfRangeException($"index: {index} (expected: range(0, {this.Capacity})"); } } protected void CheckIndex(int index, int fieldLength) { this.EnsureAccessible(); if (fieldLength < 0) { throw new IndexOutOfRangeException($"length: {fieldLength} (expected: >= 0)"); } if (index < 0 || index > this.Capacity - fieldLength) { throw new IndexOutOfRangeException($"index: {index}, length: {fieldLength} (expected: range(0, {this.Capacity})"); } } protected void CheckSrcIndex(int index, int length, int srcIndex, int srcCapacity) { this.CheckIndex(index, length); if (srcIndex < 0 || srcIndex > srcCapacity - length) { throw new IndexOutOfRangeException($"srcIndex: {srcIndex}, length: {length} (expected: range(0, {srcCapacity}))"); } } protected void CheckDstIndex(int index, int length, int dstIndex, int dstCapacity) { this.CheckIndex(index, length); if (dstIndex < 0 || dstIndex > dstCapacity - length) { throw new IndexOutOfRangeException($"dstIndex: {dstIndex}, length: {length} (expected: range(0, {dstCapacity}))"); } } /// <summary> /// Throws a <see cref="IndexOutOfRangeException" /> if the current <see cref="ReadableBytes" /> of this buffer /// is less than <see cref="minimumReadableBytes" />. /// </summary> protected void CheckReadableBytes(int minimumReadableBytes) { this.EnsureAccessible(); if (minimumReadableBytes < 0) { throw new ArgumentOutOfRangeException(nameof(minimumReadableBytes), $"minimumReadableBytes: {minimumReadableBytes} (expected: >= 0)"); } if (this.ReaderIndex > this.WriterIndex - minimumReadableBytes) { throw new IndexOutOfRangeException($"readerIndex({this.ReaderIndex}) + length({minimumReadableBytes}) exceeds writerIndex({this.WriterIndex}): {this}"); } } protected void EnsureAccessible() { if (this.ReferenceCount == 0) { throw new IllegalReferenceCountException(0); } } public IByteBuffer Copy() => this.Copy(this.ReaderIndex, this.ReadableBytes); public abstract IByteBuffer Copy(int index, int length); public IByteBuffer Slice() => this.Slice(this.ReaderIndex, this.ReadableBytes); public virtual IByteBuffer Slice(int index, int length) => new SlicedByteBuffer(this, index, length); public IByteBuffer ReadSlice(int length) { IByteBuffer slice = this.Slice(this.ReaderIndex, length); this.ReaderIndex += length; return slice; } public abstract int ReferenceCount { get; } public abstract IReferenceCounted Retain(); public abstract IReferenceCounted Retain(int increment); public abstract IReferenceCounted Touch(); public abstract IReferenceCounted Touch(object hint); public abstract bool Release(); public abstract bool Release(int decrement); protected void DiscardMarkers() { this.markedReaderIndex = this.markedWriterIndex = 0; } public string ToString(Encoding encoding) => this.ToString(this.ReaderIndex, this.ReadableBytes, encoding); public string ToString(int index, int length, Encoding encoding) => ByteBufferUtil.DecodeString(this, index, length, encoding); public int ForEachByte(ByteProcessor processor) { int index = this.ReaderIndex; int length = this.WriterIndex - index; this.EnsureAccessible(); return this.ForEachByteAsc0(index, length, processor); } public int ForEachByte(int index, int length, ByteProcessor processor) { this.CheckIndex(index, length); return this.ForEachByteAsc0(index, length, processor); } int ForEachByteAsc0(int index, int length, ByteProcessor processor) { if (processor == null) { throw new ArgumentNullException(nameof(processor)); } if (length == 0) { return -1; } int endIndex = index + length; int i = index; do { if (processor.Process(this._GetByte(i))) { i++; } else { return i; } } while (i < endIndex); return -1; } public int ForEachByteDesc(ByteProcessor processor) { int index = this.ReaderIndex; int length = this.WriterIndex - index; this.EnsureAccessible(); return this.ForEachByteDesc0(index, length, processor); } public int ForEachByteDesc(int index, int length, ByteProcessor processor) { this.CheckIndex(index, length); return this.ForEachByteDesc0(index, length, processor); } int ForEachByteDesc0(int index, int length, ByteProcessor processor) { if (processor == null) { throw new NullReferenceException("processor"); } if (length == 0) { return -1; } int i = index + length - 1; do { if (processor.Process(this._GetByte(i))) { i--; } else { return i; } } while (i >= index); return -1; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; using System.Drawing.Design; using System.Xml; using AxiomCoders.PdfTemplateEditor.Common; namespace AxiomCoders.PdfTemplateEditor.EditorItems { [Serializable] [TypeConverter(typeof(GradientColorConverter))] [Editor(typeof(GradientEditor), typeof(UITypeEditor))] [System.Reflection.Obfuscation(Exclude = true)] public class GradientDefinition { private Color color1; private Color color2; private float angle; public float Angle { get { return angle; } set { angle = value; } } private float blendPosition1; public float BlendPosition1 { get { return blendPosition1; } set { blendPosition1 = value; } } private float blendPosition2; public float BlendPosition2 { get { return blendPosition2; } set { blendPosition2 = value; } } private PointF point1; private PointF point2; private GradientType gradientType; private float startLocationX; private float startLocationY; private bool useCMYK; private float gradientSize; private float factor; private int functionType = 2; public GradientDefinition() { color1 = Color.White; color2 = Color.Black; point1 = new PointF(0.0f, 0.0f); point2 = new PointF(1.0f, 0.0f); blendPosition1 = 0.0f; blendPosition2 = 1.0f; gradientType = GradientType.Linear; } public GradientDefinition(Color c1,Color c2,PointF p1,PointF p2,GradientType type) { color1 = c1; color2 = c2; point1 = p1; point2 = p2; gradientType = type; } public void Save(XmlDocument doc, XmlElement element) { UnitsManager unitMng = new UnitsManager(); XmlElement el = doc.CreateElement("Shading"); XmlAttribute attr = doc.CreateAttribute("Type"); attr.Value = ((int)gradientType).ToString(); el.SetAttributeNode(attr); element.AppendChild(el); el = doc.CreateElement("AxialCoords"); attr = doc.CreateAttribute("FromX"); attr.Value = this.Point1.X.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("FromY"); attr.Value = this.Point1.Y.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("ToX"); attr.Value = this.Point2.X.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("ToY"); attr.Value = this.Point2.Y.ToString(); el.SetAttributeNode(attr); element.AppendChild(el); // function type el = doc.CreateElement("FunctionType"); attr = doc.CreateAttribute("Type"); attr.Value = this.functionType.ToString(); el.SetAttributeNode(attr); element.AppendChild(el); el = doc.CreateElement("Color"); attr = doc.CreateAttribute("FromR"); attr.Value = this.Color1.R.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("FromG"); attr.Value = this.Color1.G.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("FromB"); attr.Value = this.Color1.B.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("ToR"); attr.Value = this.Color2.R.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("ToG"); attr.Value = this.Color2.G.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("ToB"); attr.Value = this.Color2.B.ToString(); el.SetAttributeNode(attr); element.AppendChild(el); el = doc.CreateElement("GradientDefinition"); attr = doc.CreateAttribute("Angle"); attr.Value = this.Angle.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("BlendPosition1"); attr.Value = this.BlendPosition1.ToString(); el.SetAttributeNode(attr); attr = doc.CreateAttribute("BlendPosition2"); attr.Value = this.BlendPosition2.ToString(); el.SetAttributeNode(attr); element.AppendChild(el); } public void Load(RectangleShape shape, XmlNode element) { UnitsManager unitMng = new UnitsManager(); XmlNode node; // Load shading definition node = element.SelectSingleNode("Shading"); if (node != null) { this.gradientType = (GradientType)Convert.ToInt32(node.Attributes["Type"].Value); } // Load axial cords node = element.SelectSingleNode("AxialCoords"); if (node != null) { float x = (float)Convert.ToDouble(node.Attributes["FromX"].Value); float y = (float)Convert.ToDouble(node.Attributes["FromY"].Value); this.Point1 = new PointF(x, y); x = (float)Convert.ToDouble(node.Attributes["ToX"].Value); y = (float)Convert.ToDouble(node.Attributes["ToY"].Value); this.Point2 = new PointF(x, y); } // Load function node = element.SelectSingleNode("Function"); if (node != null) { this.functionType = Convert.ToInt32(node.Attributes["Type"]); } // Load color node = element.SelectSingleNode("Color"); if (node != null) { int r = Convert.ToInt32(node.Attributes["FromR"].Value); int g = Convert.ToInt32(node.Attributes["FromG"].Value); int b = Convert.ToInt32(node.Attributes["FromB"].Value); this.Color1 = Color.FromArgb(r, g, b); r = Convert.ToInt32(node.Attributes["ToR"].Value); g = Convert.ToInt32(node.Attributes["ToG"].Value); b = Convert.ToInt32(node.Attributes["ToB"].Value); this.Color2 = Color.FromArgb(r, g, b); } //Load gradient definition node = element.SelectSingleNode("GradientDefinition"); if(node != null) { this.Angle = (float)Convert.ToDouble(node.Attributes["Angle"].Value); this.BlendPosition1 = (float)Convert.ToDouble(node.Attributes["BlendPosition1"].Value); this.BlendPosition2 = (float)Convert.ToDouble(node.Attributes["BlendPosition2"].Value); } } public Color Color1 { get { return color1; } set { color1 = value; } } public Color Color2 { get { return color2; } set { color2 = value; } } [Browsable(false)] public PointF Point1 { get { return point1; } set { point1 = value; } } [Browsable(false)] public PointF Point2 { get { return point2; } set { point2 = value; } } public GradientType GradientType { get { return gradientType; } set { gradientType = 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.Collections.Generic; using System.Drawing; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices.Tests.Common; using Xunit; #pragma warning disable 618 namespace System.Runtime.InteropServices.Tests { [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "GetNativeVariantForObject() not supported on UWP")] public partial class GetNativeVariantForObjectTests { public static IEnumerable<object[]> GetNativeVariantForObject_RoundtrippingPrimitives_TestData() { yield return new object[] { null, VarEnum.VT_EMPTY, IntPtr.Zero }; yield return new object[] { (sbyte)10, VarEnum.VT_I1, (IntPtr)10 }; yield return new object[] { (short)10, VarEnum.VT_I2, (IntPtr)10 }; yield return new object[] { 10, VarEnum.VT_I4, (IntPtr)10 }; yield return new object[] { (long)10, VarEnum.VT_I8, (IntPtr)10 }; yield return new object[] { (byte)10, VarEnum.VT_UI1, (IntPtr)10 }; yield return new object[] { (ushort)10, VarEnum.VT_UI2, (IntPtr)10 }; yield return new object[] { (uint)10, VarEnum.VT_UI4, (IntPtr)10 }; yield return new object[] { (ulong)10, VarEnum.VT_UI8, (IntPtr)10 }; yield return new object[] { true, VarEnum.VT_BOOL, (IntPtr)ushort.MaxValue }; yield return new object[] { false, VarEnum.VT_BOOL, IntPtr.Zero }; yield return new object[] { 10m, VarEnum.VT_DECIMAL, (IntPtr)10 }; // Well known types. DateTime dateTime = new DateTime(1899, 12, 30).AddDays(20); yield return new object[] { dateTime, VarEnum.VT_DATE, (IntPtr)(-1) }; yield return new object[] { DBNull.Value, VarEnum.VT_NULL, IntPtr.Zero }; yield return new object[] { DBNull.Value, VarEnum.VT_NULL, IntPtr.Zero }; // Arrays. yield return new object[] { new sbyte[] { 10, 11, 12 }, (VarEnum)8208, (IntPtr)(-1) }; yield return new object[] { new short[] { 10, 11, 12 }, (VarEnum)8194, (IntPtr)(-1) }; yield return new object[] { new int[] { 10, 11, 12 }, (VarEnum)8195, (IntPtr)(-1) }; yield return new object[] { new long[] { 10, 11, 12 }, (VarEnum)8212, (IntPtr)(-1) }; yield return new object[] { new byte[] { 10, 11, 12 }, (VarEnum)8209, (IntPtr)(-1) }; yield return new object[] { new ushort[] { 10, 11, 12 }, (VarEnum)8210, (IntPtr)(-1) }; yield return new object[] { new uint[] { 10, 11, 12 }, (VarEnum)8211, (IntPtr)(-1) }; yield return new object[] { new ulong[] { 10, 11, 12 }, (VarEnum)8213, (IntPtr)(-1) }; yield return new object[] { new bool[] { true, false }, (VarEnum)8203, (IntPtr)(-1) }; yield return new object[] { new float[] { 10, 11, 12 }, (VarEnum)8196, (IntPtr)(-1) }; yield return new object[] { new double[] { 10, 11, 12 }, (VarEnum)8197, (IntPtr)(-1) }; yield return new object[] { new decimal[] { 10m, 11m, 12m }, (VarEnum)8206, (IntPtr)(-1) }; yield return new object[] { new object[] { 10, 11, 12 }, (VarEnum)8204, (IntPtr)(-1) }; yield return new object[] { new string[] { "a", "b", "c" }, (VarEnum)8200, (IntPtr)(-1) }; yield return new object[] { new TimeSpan[] { new TimeSpan(10) }, (VarEnum)8228, (IntPtr)(-1) }; yield return new object[] { new int[,] { { 10 }, { 11 }, { 12 } }, (VarEnum)8195, (IntPtr)(-1) }; // Objects. var nonGenericClass = new NonGenericClass(); yield return new object[] { nonGenericClass, VarEnum.VT_DISPATCH, (IntPtr)(-1) }; var valueType = new StructWithValue { Value = 10 }; yield return new object[] { valueType, VarEnum.VT_RECORD, (IntPtr)(-1) }; var genericClass = new GenericClass<string>(); yield return new object[] { new object[] { nonGenericClass, genericClass, null }, (VarEnum)8204, (IntPtr)(-1) }; yield return new object[] { new object[] { valueType, null }, (VarEnum)8204, (IntPtr)(-1) }; // Delegate. MethodInfo method = typeof(GetNativeVariantForObjectTests).GetMethod(nameof(NonGenericMethod)); Delegate d = method.CreateDelegate(typeof(NonGenericDelegate)); yield return new object[] { d, VarEnum.VT_DISPATCH, (IntPtr)(-1) }; } [Theory] [MemberData(nameof(GetNativeVariantForObject_RoundtrippingPrimitives_TestData))] [PlatformSpecific(TestPlatforms.Windows)] [ActiveIssue(31077, ~TargetFrameworkMonikers.NetFramework)] public void GetNativeVariantForObject_RoundtrippingPrimitives_Success(object primitive, VarEnum expectedVarType, IntPtr expectedValue) { GetNativeVariantForObject_ValidObject_Success(primitive, expectedVarType, expectedValue, primitive); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariantForObject_TypeMissing_Success() { // This cannot be in the test data as XUnit uses MethodInfo.Invoke to call test methods and // Type.Missing is handled specially for parameters with default values. GetNativeVariantForObject_RoundtrippingPrimitives_Success(Type.Missing, VarEnum.VT_ERROR, (IntPtr)(-1)); } public static IEnumerable<object[]> GetNativeVariantForObject_NonRoundtrippingPrimitives_TestData() { // GetNativeVariantForObject supports char, but internally recognizes it the same as ushort // because the native variant type uses mscorlib type VarEnum to store what type it contains. // To get back the original char, use GetObjectForNativeVariant<ushort> and cast to char. yield return new object[] { 'a', VarEnum.VT_UI2, (IntPtr)'a', (ushort)97 }; yield return new object[] { new char[] { 'a', 'b', 'c' }, (VarEnum)8210, (IntPtr)(-1), new ushort[] { 'a', 'b', 'c' } }; // IntPtr/UIntPtr objects are converted to int/uint respectively. yield return new object[] { (IntPtr)10, VarEnum.VT_INT, (IntPtr)10, 10 }; yield return new object[] { (UIntPtr)10, VarEnum.VT_UINT, (IntPtr)10, (uint)10 }; yield return new object[] { new IntPtr[] { (IntPtr)10, (IntPtr)11, (IntPtr)12 }, (VarEnum)8212, (IntPtr)(-1), new long[] { 10, 11, 12 } }; yield return new object[] { new UIntPtr[] { (UIntPtr)10, (UIntPtr)11, (UIntPtr)12 }, (VarEnum)8213, (IntPtr)(-1), new ulong[] { 10, 11, 12 } }; // DateTime is converted to VT_DATE which is offset from December 30, 1899. DateTime earlyDateTime = new DateTime(1899, 12, 30); yield return new object[] { earlyDateTime, VarEnum.VT_DATE, IntPtr.Zero, new DateTime(1899, 12, 30) }; // Wrappers. yield return new object[] { new UnknownWrapper(10), VarEnum.VT_UNKNOWN, IntPtr.Zero, null }; if (!PlatformDetection.IsNetCore) { yield return new object[] { new DispatchWrapper(10), VarEnum.VT_DISPATCH, IntPtr.Zero, null }; } else { Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(10)); } yield return new object[] { new ErrorWrapper(10), VarEnum.VT_ERROR, (IntPtr)10, 10 }; yield return new object[] { new CurrencyWrapper(10), VarEnum.VT_CY, (IntPtr)100000, 10m }; yield return new object[] { new BStrWrapper("a"), VarEnum.VT_BSTR, (IntPtr)(-1), "a" }; yield return new object[] { new BStrWrapper(null), VarEnum.VT_BSTR, IntPtr.Zero, null }; yield return new object[] { new UnknownWrapper[] { new UnknownWrapper(null), new UnknownWrapper(10) }, (VarEnum)8205, (IntPtr)(-1), new object[] { null, 10 } }; if (!PlatformDetection.IsNetCore) { yield return new object[] { new DispatchWrapper[] { new DispatchWrapper(null), new DispatchWrapper(10) }, (VarEnum)8201, (IntPtr)(-1), new object[] { null, 10 } }; } else { Assert.Throws<PlatformNotSupportedException>(() => new DispatchWrapper(10)); } yield return new object[] { new ErrorWrapper[] { new ErrorWrapper(10) }, (VarEnum)8202, (IntPtr)(-1), new uint[] { 10 } }; yield return new object[] { new CurrencyWrapper[] { new CurrencyWrapper(10) }, (VarEnum)8198, (IntPtr)(-1), new decimal[] { 10 } }; yield return new object[] { new BStrWrapper[] { new BStrWrapper("a"), new BStrWrapper(null), new BStrWrapper("c") }, (VarEnum)8200, (IntPtr)(-1), new string[] { "a", null, "c" } }; // Objects. var nonGenericClass = new NonGenericClass(); yield return new object[] { new NonGenericClass[] { nonGenericClass, null }, (VarEnum)8201, (IntPtr)(-1), new object[] { nonGenericClass, null } }; var genericClass = new GenericClass<string>(); yield return new object[] { new GenericClass<string>[] { genericClass, null }, (VarEnum)8205, (IntPtr)(-1), new object[] { genericClass, null } }; var nonGenericStruct = new NonGenericStruct(); yield return new object[] { new NonGenericStruct[] { nonGenericStruct }, (VarEnum)8228, (IntPtr)(-1), new NonGenericStruct[] { nonGenericStruct } }; var classWithInterface = new ClassWithInterface(); var structWithInterface = new StructWithInterface(); yield return new object[] { new ClassWithInterface[] { classWithInterface, null }, (VarEnum)8201, (IntPtr)(-1), new object[] { classWithInterface, null } }; yield return new object[] { new StructWithInterface[] { structWithInterface }, (VarEnum)8228, (IntPtr)(-1), new StructWithInterface[] { structWithInterface } }; yield return new object[] { new NonGenericInterface[] { classWithInterface, structWithInterface, null }, (VarEnum)8201, (IntPtr)(-1), new object[] { classWithInterface, structWithInterface, null } }; // Enums. yield return new object[] { SByteEnum.Value2, VarEnum.VT_I1, (IntPtr)1, (sbyte)1 }; yield return new object[] { Int16Enum.Value2, VarEnum.VT_I2, (IntPtr)1, (short)1 }; yield return new object[] { Int32Enum.Value2, VarEnum.VT_I4, (IntPtr)1, 1 }; yield return new object[] { Int64Enum.Value2, VarEnum.VT_I8, (IntPtr)1, (long)1 }; yield return new object[] { ByteEnum.Value2, VarEnum.VT_UI1, (IntPtr)1, (byte)1 }; yield return new object[] { UInt16Enum.Value2, VarEnum.VT_UI2, (IntPtr)1, (ushort)1 }; yield return new object[] { UInt32Enum.Value2, VarEnum.VT_UI4, (IntPtr)1, (uint)1 }; yield return new object[] { UInt64Enum.Value2, VarEnum.VT_UI8, (IntPtr)1, (ulong)1 }; yield return new object[] { new SByteEnum[] { SByteEnum.Value2 }, (VarEnum)8208, (IntPtr)(-1), new sbyte[] { 1 } }; yield return new object[] { new Int16Enum[] { Int16Enum.Value2 }, (VarEnum)8194, (IntPtr)(-1), new short[] { 1 } }; yield return new object[] { new Int32Enum[] { Int32Enum.Value2 }, (VarEnum)8195, (IntPtr)(-1), new int[] { 1 } }; yield return new object[] { new Int64Enum[] { Int64Enum.Value2 }, (VarEnum)8212, (IntPtr)(-1), new long[] { 1 } }; yield return new object[] { new ByteEnum[] { ByteEnum.Value2 }, (VarEnum)8209, (IntPtr)(-1), new byte[] { 1 } }; yield return new object[] { new UInt16Enum[] { UInt16Enum.Value2 }, (VarEnum)8210, (IntPtr)(-1), new ushort[] { 1 } }; yield return new object[] { new UInt32Enum[] { UInt32Enum.Value2 }, (VarEnum)8211, (IntPtr)(-1), new uint[] { 1 } }; yield return new object[] { new UInt64Enum[] { UInt64Enum.Value2 }, (VarEnum)8213, (IntPtr)(-1), new ulong[] { 1 } }; // Color is converted to uint. yield return new object[] { Color.FromArgb(10), VarEnum.VT_UI4, (IntPtr)655360, (uint)655360 }; } [Theory] [MemberData(nameof(GetNativeVariantForObject_NonRoundtrippingPrimitives_TestData))] [PlatformSpecific(TestPlatforms.Windows)] [ActiveIssue(31077, ~TargetFrameworkMonikers.NetFramework)] public void GetNativeVariantForObject_ValidObject_Success(object primitive, VarEnum expectedVarType, IntPtr expectedValue, object expectedRoundtripValue) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject(primitive, pNative); Variant result = Marshal.PtrToStructure<Variant>(pNative); Assert.Equal(expectedVarType, (VarEnum)result.vt); if (expectedValue != (IntPtr)(-1)) { Assert.Equal(expectedValue, result.bstrVal); } else { Assert.NotEqual((IntPtr)(-1), result.bstrVal); Assert.NotEqual(IntPtr.Zero, result.bstrVal); } // Make sure it roundtrips. Assert.Equal(expectedRoundtripValue, Marshal.GetObjectForNativeVariant(pNative)); } finally { Marshal.FreeHGlobal(pNative); } } [Theory] [InlineData("")] [InlineData("99")] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariantForObject_String_Success(string obj) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject(obj, pNative); Variant result = Marshal.PtrToStructure<Variant>(pNative); try { Assert.Equal(VarEnum.VT_BSTR, (VarEnum)result.vt); Assert.Equal(obj, Marshal.PtrToStringBSTR(result.bstrVal)); object o = Marshal.GetObjectForNativeVariant(pNative); Assert.Equal(obj, o); } finally { Marshal.FreeBSTR(result.bstrVal); } } finally { Marshal.FreeHGlobal(pNative); } } [Theory] [InlineData(3.14)] [PlatformSpecific(TestPlatforms.Windows)] public unsafe void GetNativeVariantForObject_Double_Success(double obj) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject(obj, pNative); Variant result = Marshal.PtrToStructure<Variant>(pNative); Assert.Equal(VarEnum.VT_R8, (VarEnum)result.vt); Assert.Equal(*((IntPtr*)&obj), result.bstrVal); object o = Marshal.GetObjectForNativeVariant(pNative); Assert.Equal(obj, o); } finally { Marshal.FreeHGlobal(pNative); } } [Theory] [InlineData(3.14f)] [PlatformSpecific(TestPlatforms.Windows)] public unsafe void GetNativeVariantForObject_Float_Success(float obj) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject(obj, pNative); Variant result = Marshal.PtrToStructure<Variant>(pNative); Assert.Equal(VarEnum.VT_R4, (VarEnum)result.vt); Assert.Equal(*((IntPtr*)&obj), result.bstrVal); object o = Marshal.GetObjectForNativeVariant(pNative); Assert.Equal(obj, o); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void GetNativeVariantForObject_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetNativeVariantForObject(new object(), IntPtr.Zero)); Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetNativeVariantForObject(1, IntPtr.Zero)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariantForObject_ZeroPointer_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("pDstNativeVariant", () => Marshal.GetNativeVariantForObject(new object(), IntPtr.Zero)); AssertExtensions.Throws<ArgumentNullException>("pDstNativeVariant", () => Marshal.GetNativeVariantForObject<int>(1, IntPtr.Zero)); } public static IEnumerable<object[]> GetNativeVariantForObject_GenericObject_TestData() { yield return new object[] { new GenericClass<string>() }; yield return new object[] { new GenericStruct<string>() }; } [Theory] [MemberData(nameof(GetNativeVariantForObject_GenericObject_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariantForObject_GenericObject_ThrowsArgumentException(object obj) { AssertExtensions.Throws<ArgumentException>("obj", () => Marshal.GetNativeVariantForObject(obj, (IntPtr)1)); AssertExtensions.Throws<ArgumentException>("obj", () => Marshal.GetNativeVariantForObject<object>(obj, (IntPtr)1)); } public static IEnumerable<object[]> GetNativeVariant_NotInteropCompatible_TestData() { yield return new object[] { new TimeSpan(10) }; yield return new object[] { new object[] { new GenericStruct<string>() } }; yield return new object[] { new GenericStruct<string>[0]}; yield return new object[] { new GenericStruct<string>[] { new GenericStruct<string>() } }; yield return new object[] { new Color[0] }; yield return new object[] { new Color[] { Color.FromArgb(10) } }; } [Theory] [MemberData(nameof(GetNativeVariant_NotInteropCompatible_TestData))] [PlatformSpecific(TestPlatforms.Windows)] [ActiveIssue(31077, ~TargetFrameworkMonikers.NetFramework)] public void GetNativeVariant_NotInteropCompatible_ThrowsArgumentException(object obj) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject(obj, pNative)); AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject<object>(obj, pNative)); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariant_InvalidArray_ThrowsSafeArrayTypeMismatchException() { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Assert.Throws<SafeArrayTypeMismatchException>(() => Marshal.GetNativeVariantForObject(new int[][] { }, pNative)); Assert.Throws<SafeArrayTypeMismatchException>(() => Marshal.GetNativeVariantForObject<object>(new int[][] { }, pNative)); } finally { Marshal.FreeHGlobal(pNative); } } public static IEnumerable<object[]> GetNativeVariant_VariantWrapper_TestData() { yield return new object[] { new VariantWrapper(null) }; yield return new object[] { new VariantWrapper[] { new VariantWrapper(null) } }; } [Theory] [MemberData(nameof(GetNativeVariant_VariantWrapper_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariant_VariantWrapper_ThrowsArgumentException(object obj) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject(obj, pNative)); AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject<object>(obj, pNative)); } finally { Marshal.FreeHGlobal(pNative); } } public static IEnumerable<object[]> GetNativeVariant_HandleObject_TestData() { yield return new object[] { new FakeSafeHandle() }; yield return new object[] { new FakeCriticalHandle() }; yield return new object[] { new FakeSafeHandle[] { new FakeSafeHandle() } }; yield return new object[] { new FakeCriticalHandle[] { new FakeCriticalHandle() } }; } [Theory] [MemberData(nameof(GetNativeVariant_HandleObject_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariant_HandleObject_ThrowsArgumentException(object obj) { var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject(obj, pNative)); AssertExtensions.Throws<ArgumentException>(null, () => Marshal.GetNativeVariantForObject<object>(obj, pNative)); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void GetNativeVariantForObject_CantCastToObject_ThrowsInvalidCastException() { // While GetNativeVariantForObject supports taking chars, GetObjectForNativeVariant will // never return a char. The internal type is ushort, as mentioned above. This behavior // is the same on ProjectN and Desktop CLR. var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<char>('a', pNative); Assert.Throws<InvalidCastException>(() => Marshal.GetObjectForNativeVariant<char>(pNative)); } finally { Marshal.FreeHGlobal(pNative); } } #if !netstandard // TODO: Enable for netstandard2.1 [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetNative))] [PlatformSpecific(TestPlatforms.Windows)] public void GetNativeVariantForObject_ObjectNotCollectible_ThrowsNotSupportedException() { AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); Type type = typeBuilder.CreateType(); object o = Activator.CreateInstance(type); var v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(Marshal.SizeOf(v)); try { Assert.Throws<NotSupportedException>(() => Marshal.GetNativeVariantForObject(o, pNative)); } finally { Marshal.FreeHGlobal(pNative); } } #endif public struct StructWithValue { public int Value; } public class ClassWithInterface : NonGenericInterface { } public struct StructWithInterface : NonGenericInterface { } public enum SByteEnum : sbyte { Value1, Value2 } public enum Int16Enum : short { Value1, Value2 } public enum Int32Enum : int { Value1, Value2 } public enum Int64Enum : long { Value1, Value2 } public enum ByteEnum : byte { Value1, Value2 } public enum UInt16Enum : ushort { Value1, Value2 } public enum UInt32Enum : uint { Value1, Value2 } public enum UInt64Enum : ulong { Value1, Value2 } public static void NonGenericMethod(int i) { } public delegate void NonGenericDelegate(int i); public class FakeSafeHandle : SafeHandle { public FakeSafeHandle() : base(IntPtr.Zero, false) { } public override bool IsInvalid => throw new NotImplementedException(); protected override bool ReleaseHandle() => throw new NotImplementedException(); protected override void Dispose(bool disposing) { } } public class FakeCriticalHandle : CriticalHandle { public FakeCriticalHandle() : base(IntPtr.Zero) { } public override bool IsInvalid => true; protected override bool ReleaseHandle() => throw new NotImplementedException(); protected override void Dispose(bool disposing) { } } } } #pragma warning restore 618
using System; using System.Collections.Concurrent; using System.Diagnostics; using Orleans.Messaging; namespace Orleans.Runtime { internal class MessagingStatisticsGroup { internal class PerSocketDirectionStats { private readonly AverageValueStatistic averageBatchSize; private readonly HistogramValueStatistic batchSizeBytesHistogram; internal PerSocketDirectionStats(bool sendOrReceive, ConnectionDirection direction) { StatisticNameFormat batchSizeStatName = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_PER_SOCKET_DIRECTION; StatisticNameFormat batchHistogramStatName = sendOrReceive ? StatisticNames.MESSAGING_SENT_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION : StatisticNames.MESSAGING_RECEIVED_BATCH_SIZE_BYTES_HISTOGRAM_PER_SOCKET_DIRECTION; averageBatchSize = AverageValueStatistic.FindOrCreate(new StatisticName(batchSizeStatName, Enum.GetName(typeof(ConnectionDirection), direction))); batchSizeBytesHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram( new StatisticName(batchHistogramStatName, Enum.GetName(typeof(ConnectionDirection), direction)), NUM_MSG_SIZE_HISTOGRAM_CATEGORIES); } internal void OnMessage(int numMsgsInBatch, int totalBytes) { averageBatchSize.AddValue(numMsgsInBatch); batchSizeBytesHistogram.AddData(totalBytes); } } internal static CounterStatistic MessagesSentTotal; internal static CounterStatistic[] MessagesSentPerDirection; internal static CounterStatistic TotalBytesSent; internal static CounterStatistic HeaderBytesSent; internal static CounterStatistic MessagesReceived; internal static CounterStatistic[] MessagesReceivedPerDirection; private static CounterStatistic totalBytesReceived; private static CounterStatistic headerBytesReceived; internal static CounterStatistic LocalMessagesSent; internal static CounterStatistic[] FailedSentMessages; internal static CounterStatistic[] DroppedSentMessages; internal static CounterStatistic[] RejectedMessages; internal static CounterStatistic[] ReroutedMessages; private static CounterStatistic expiredAtSendCounter; private static CounterStatistic expiredAtReceiveCounter; private static CounterStatistic expiredAtDispatchCounter; private static CounterStatistic expiredAtInvokeCounter; private static CounterStatistic expiredAtRespondCounter; internal static CounterStatistic ConnectedClientCount; private static PerSocketDirectionStats[] perSocketDirectionStatsSend; private static PerSocketDirectionStats[] perSocketDirectionStatsReceive; private static ConcurrentDictionary<string, CounterStatistic> perSiloSendCounters; private static ConcurrentDictionary<string, CounterStatistic> perSiloReceiveCounters; private static ConcurrentDictionary<string, CounterStatistic> perSiloPingSendCounters; private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReceiveCounters; private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReplyReceivedCounters; private static ConcurrentDictionary<string, CounterStatistic> perSiloPingReplyMissedCounters; internal enum Phase { Send, Receive, Dispatch, Invoke, Respond, } // Histogram of sent message size, starting from 0 in multiples of 2 // (1=2^0, 2=2^2, ... , 256=2^8, 512=2^9, 1024==2^10, ... , up to ... 2^30=1GB) private static HistogramValueStatistic sentMsgSizeHistogram; private static HistogramValueStatistic receiveMsgSizeHistogram; private const int NUM_MSG_SIZE_HISTOGRAM_CATEGORIES = 31; internal static void Init() { LocalMessagesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_LOCALMESSAGES); ConnectedClientCount = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_CONNECTED_CLIENTS, false); MessagesSentTotal = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_MESSAGES_TOTAL); MessagesSentPerDirection ??= new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length]; foreach (var direction in Enum.GetValues(typeof(Message.Directions))) { MessagesSentPerDirection[(int)direction] = CounterStatistic.FindOrCreate( new StatisticName(StatisticNames.MESSAGING_SENT_MESSAGES_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction))); } MessagesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_MESSAGES_TOTAL); MessagesReceivedPerDirection ??= new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length]; foreach (var direction in Enum.GetValues(typeof(Message.Directions))) { MessagesReceivedPerDirection[(int)direction] = CounterStatistic.FindOrCreate( new StatisticName(StatisticNames.MESSAGING_RECEIVED_MESSAGES_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction))); } TotalBytesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_BYTES_TOTAL); totalBytesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_BYTES_TOTAL); HeaderBytesSent = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_SENT_BYTES_HEADER); headerBytesReceived = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_RECEIVED_BYTES_HEADER); FailedSentMessages ??= new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length]; DroppedSentMessages ??= new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length]; RejectedMessages ??= new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length]; ReroutedMessages ??= new CounterStatistic[Enum.GetValues(typeof(Message.Directions)).Length]; foreach (var direction in Enum.GetValues(typeof(Message.Directions))) { ReroutedMessages[(int)direction] = CounterStatistic.FindOrCreate( new StatisticName(StatisticNames.MESSAGING_REROUTED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction))); } sentMsgSizeHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(StatisticNames.MESSAGING_SENT_MESSAGESIZEHISTOGRAM, NUM_MSG_SIZE_HISTOGRAM_CATEGORIES); receiveMsgSizeHistogram = ExponentialHistogramValueStatistic.Create_ExponentialHistogram(StatisticNames.MESSAGING_RECEIVED_MESSAGESIZEHISTOGRAM, NUM_MSG_SIZE_HISTOGRAM_CATEGORIES); expiredAtSendCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATSENDER); expiredAtReceiveCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATRECEIVER); expiredAtDispatchCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATDISPATCH); expiredAtInvokeCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATINVOKE); expiredAtRespondCounter = CounterStatistic.FindOrCreate(StatisticNames.MESSAGING_EXPIRED_ATRESPOND); perSocketDirectionStatsSend ??= new PerSocketDirectionStats[Enum.GetValues(typeof(ConnectionDirection)).Length]; perSocketDirectionStatsReceive ??= new PerSocketDirectionStats[Enum.GetValues(typeof(ConnectionDirection)).Length]; perSocketDirectionStatsSend[(int)ConnectionDirection.SiloToSilo] = new PerSocketDirectionStats(true, ConnectionDirection.SiloToSilo); perSocketDirectionStatsReceive[(int)ConnectionDirection.SiloToSilo] = new PerSocketDirectionStats(false, ConnectionDirection.SiloToSilo); perSocketDirectionStatsSend[(int)ConnectionDirection.GatewayToClient] = new PerSocketDirectionStats(true, ConnectionDirection.GatewayToClient); perSocketDirectionStatsReceive[(int)ConnectionDirection.GatewayToClient] = new PerSocketDirectionStats(false, ConnectionDirection.GatewayToClient); perSocketDirectionStatsSend[(int)ConnectionDirection.ClientToGateway] = new PerSocketDirectionStats(true, ConnectionDirection.ClientToGateway); perSocketDirectionStatsReceive[(int)ConnectionDirection.ClientToGateway] = new PerSocketDirectionStats(false, ConnectionDirection.ClientToGateway); perSiloSendCounters = new ConcurrentDictionary<string, CounterStatistic>(); perSiloReceiveCounters = new ConcurrentDictionary<string, CounterStatistic>(); perSiloPingSendCounters = new ConcurrentDictionary<string, CounterStatistic>(); perSiloPingReceiveCounters = new ConcurrentDictionary<string, CounterStatistic>(); perSiloPingReplyReceivedCounters = new ConcurrentDictionary<string, CounterStatistic>(); perSiloPingReplyMissedCounters = new ConcurrentDictionary<string, CounterStatistic>(); } internal static CounterStatistic GetMessageSendCounter(SiloAddress remoteSilo) { if (remoteSilo is null) return null; return FindCounter(perSiloSendCounters, new StatisticName(StatisticNames.MESSAGING_SENT_MESSAGES_PER_SILO, (remoteSilo != null ? remoteSilo.ToString() : "Null")), CounterStorage.LogOnly); } internal static void OnMessageSend(CounterStatistic messageSendCounter, Message msg, int numTotalBytes, int headerBytes, ConnectionDirection connectionDirection) { Debug.Assert(numTotalBytes >= 0, $"OnMessageSend(numTotalBytes={numTotalBytes})"); MessagesSentTotal.Increment(); MessagesSentPerDirection[(int)msg.Direction].Increment(); TotalBytesSent.IncrementBy(numTotalBytes); HeaderBytesSent.IncrementBy(headerBytes); sentMsgSizeHistogram.AddData(numTotalBytes); messageSendCounter?.Increment(); perSocketDirectionStatsSend[(int)connectionDirection].OnMessage(1, numTotalBytes); } private static CounterStatistic FindCounter(ConcurrentDictionary<string, CounterStatistic> counters, StatisticName name, CounterStorage storage) { CounterStatistic stat; if (counters.TryGetValue(name.Name, out stat)) { return stat; } stat = CounterStatistic.FindOrCreate(name, storage); counters.TryAdd(name.Name, stat); return stat; } internal static CounterStatistic GetMessageReceivedCounter(SiloAddress remoteSilo) { SiloAddress addr = remoteSilo; return FindCounter(perSiloReceiveCounters, new StatisticName(StatisticNames.MESSAGING_RECEIVED_MESSAGES_PER_SILO, (addr != null ? addr.ToString() : "Null")), CounterStorage.LogOnly); } internal static void OnMessageReceive(CounterStatistic messageReceivedCounter, Message msg, int numTotalBytes, int headerBytes, ConnectionDirection connectionDirection) { MessagesReceived.Increment(); MessagesReceivedPerDirection[(int)msg.Direction].Increment(); totalBytesReceived.IncrementBy(numTotalBytes); headerBytesReceived.IncrementBy(headerBytes); receiveMsgSizeHistogram.AddData(numTotalBytes); messageReceivedCounter?.Increment(); perSocketDirectionStatsReceive[(int)connectionDirection].OnMessage(1, numTotalBytes); } internal static void OnMessageExpired(Phase phase) { switch (phase) { case Phase.Send: expiredAtSendCounter.Increment(); break; case Phase.Receive: expiredAtReceiveCounter.Increment(); break; case Phase.Dispatch: expiredAtDispatchCounter.Increment(); break; case Phase.Invoke: expiredAtInvokeCounter.Increment(); break; case Phase.Respond: expiredAtRespondCounter.Increment(); break; } } internal static void OnPingSend(SiloAddress destination) { FindCounter(perSiloPingSendCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_SENT_PER_SILO, destination.ToString()), CounterStorage.LogOnly).Increment(); } internal static void OnPingReceive(SiloAddress destination) { FindCounter(perSiloPingReceiveCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_RECEIVED_PER_SILO, destination.ToString()), CounterStorage.LogOnly).Increment(); } internal static void OnPingReplyReceived(SiloAddress replier) { FindCounter(perSiloPingReplyReceivedCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_REPLYRECEIVED_PER_SILO, replier.ToString()), CounterStorage.LogOnly).Increment(); } internal static void OnPingReplyMissed(SiloAddress replier) { FindCounter(perSiloPingReplyMissedCounters, new StatisticName(StatisticNames.MESSAGING_PINGS_REPLYMISSED_PER_SILO, replier.ToString()), CounterStorage.LogOnly).Increment(); } internal static void OnFailedSentMessage(Message msg) { if (msg == null || !msg.HasDirection) return; int direction = (int)msg.Direction; if (FailedSentMessages[direction] == null) { FailedSentMessages[direction] = CounterStatistic.FindOrCreate( new StatisticName(StatisticNames.MESSAGING_SENT_FAILED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction))); } FailedSentMessages[direction].Increment(); } internal static void OnDroppedSentMessage(Message msg) { if (msg == null || !msg.HasDirection) return; int direction = (int)msg.Direction; if (DroppedSentMessages[direction] == null) { DroppedSentMessages[direction] = CounterStatistic.FindOrCreate( new StatisticName(StatisticNames.MESSAGING_SENT_DROPPED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction))); } DroppedSentMessages[direction].Increment(); } internal static void OnRejectedMessage(Message msg) { if (msg == null || !msg.HasDirection) return; int direction = (int)msg.Direction; if (RejectedMessages[direction] == null) { RejectedMessages[direction] = CounterStatistic.FindOrCreate( new StatisticName(StatisticNames.MESSAGING_REJECTED_PER_DIRECTION, Enum.GetName(typeof(Message.Directions), direction))); } RejectedMessages[direction].Increment(); } internal static void OnMessageReRoute(Message msg) { ReroutedMessages[(int)msg.Direction].Increment(); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using Encoding = System.Text.Encoding; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Constants and utility functions. /// </summary> internal static class Statics { #region Constants public const byte DefaultLevel = 5; public const byte TraceLoggingChannel = 0xb; public const byte InTypeMask = 31; public const byte InTypeFixedCountFlag = 32; public const byte InTypeVariableCountFlag = 64; public const byte InTypeCustomCountFlag = 96; public const byte InTypeCountMask = 96; public const byte InTypeChainFlag = 128; public const byte OutTypeMask = 127; public const byte OutTypeChainFlag = 128; public const EventTags EventTagsMask = (EventTags)0xfffffff; public static readonly TraceLoggingDataType IntPtrType = IntPtr.Size == 8 ? TraceLoggingDataType.Int64 : TraceLoggingDataType.Int32; public static readonly TraceLoggingDataType UIntPtrType = IntPtr.Size == 8 ? TraceLoggingDataType.UInt64 : TraceLoggingDataType.UInt32; public static readonly TraceLoggingDataType HexIntPtrType = IntPtr.Size == 8 ? TraceLoggingDataType.HexInt64 : TraceLoggingDataType.HexInt32; #endregion #region Metadata helpers /// <summary> /// A complete metadata chunk can be expressed as: /// length16 + prefix + null-terminated-utf8-name + suffix + additionalData. /// We assume that excludedData will be provided by some other means, /// but that its size is known. This function returns a blob containing /// length16 + prefix + name + suffix, with prefix and suffix initialized /// to 0's. The length16 value is initialized to the length of the returned /// blob plus additionalSize, so that the concatenation of the returned blob /// plus a blob of size additionalSize constitutes a valid metadata blob. /// </summary> /// <param name="name"> /// The name to include in the blob. /// </param> /// <param name="prefixSize"> /// Amount of space to reserve before name. For provider or field blobs, this /// should be 0. For event blobs, this is used for the tags field and will vary /// from 1 to 4, depending on how large the tags field needs to be. /// </param> /// <param name="suffixSize"> /// Amount of space to reserve after name. For example, a provider blob with no /// traits would reserve 0 extra bytes, but a provider blob with a single GroupId /// field would reserve 19 extra bytes. /// </param> /// <param name="additionalSize"> /// Amount of additional data in another blob. This value will be counted in the /// blob's length field, but will not be included in the returned byte[] object. /// The complete blob would then be the concatenation of the returned byte[] object /// with another byte[] object of length additionalSize. /// </param> /// <returns> /// A byte[] object with the length and name fields set, with room reserved for /// prefix and suffix. If additionalSize was 0, the byte[] object is a complete /// blob. Otherwise, another byte[] of size additionalSize must be concatenated /// with this one to form a complete blob. /// </returns> public static byte[] MetadataForString( string name, int prefixSize, int suffixSize, int additionalSize) { Statics.CheckName(name); int metadataSize = Encoding.UTF8.GetByteCount(name) + 3 + prefixSize + suffixSize; var metadata = new byte[metadataSize]; ushort totalSize = checked((ushort)(metadataSize + additionalSize)); metadata[0] = unchecked((byte)totalSize); metadata[1] = unchecked((byte)(totalSize >> 8)); Encoding.UTF8.GetBytes(name, 0, name.Length, metadata, 2 + prefixSize); return metadata; } /// <summary> /// Serialize the low 28 bits of the tags value into the metadata stream, /// starting at the index given by pos. Updates pos. Writes 1 to 4 bytes, /// depending on the value of the tags variable. Usable for event tags and /// field tags. /// /// Note that 'metadata' can be null, in which case it only updates 'pos'. /// This is useful for a two pass approach where you figure out how big to /// make the array, and then you fill it in. /// </summary> public static void EncodeTags(int tags, ref int pos, byte[] metadata) { // We transmit the low 28 bits of tags, high bits first, 7 bits at a time. var tagsLeft = tags & 0xfffffff; bool more; do { byte current = (byte)((tagsLeft >> 21) & 0x7f); more = (tagsLeft & 0x1fffff) != 0; current |= (byte)(more ? 0x80 : 0x00); tagsLeft = tagsLeft << 7; if (metadata != null) { metadata[pos] = current; } pos += 1; } while (more); } public static byte Combine( int settingValue, byte defaultValue) { unchecked { return (byte)settingValue == settingValue ? (byte)settingValue : defaultValue; } } public static byte Combine( int settingValue1, int settingValue2, byte defaultValue) { unchecked { return (byte)settingValue1 == settingValue1 ? (byte)settingValue1 : (byte)settingValue2 == settingValue2 ? (byte)settingValue2 : defaultValue; } } public static int Combine( int settingValue1, int settingValue2) { unchecked { return (byte)settingValue1 == settingValue1 ? settingValue1 : settingValue2; } } public static void CheckName(string name) { if (name != null && 0 <= name.IndexOf('\0')) { throw new ArgumentOutOfRangeException("name"); } } public static bool ShouldOverrideFieldName(string fieldName) { return (fieldName.Length <= 2 && fieldName[0] == '_'); } public static TraceLoggingDataType MakeDataType( TraceLoggingDataType baseType, EventFieldFormat format) { return (TraceLoggingDataType)(((int)baseType & 0x1f) | ((int)format << 8)); } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format8( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.String: return TraceLoggingDataType.Char8; case EventFieldFormat.Boolean: return TraceLoggingDataType.Boolean8; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt8; #if false case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int8; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt8; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format16( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.String: return TraceLoggingDataType.Char16; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt16; #if false case EventSourceFieldFormat.Port: return TraceLoggingDataType.Port; case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int16; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt16; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format32( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.Boolean: return TraceLoggingDataType.Boolean32; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt32; #if false case EventSourceFieldFormat.Ipv4Address: return TraceLoggingDataType.Ipv4Address; case EventSourceFieldFormat.ProcessId: return TraceLoggingDataType.ProcessId; case EventSourceFieldFormat.ThreadId: return TraceLoggingDataType.ThreadId; case EventSourceFieldFormat.Win32Error: return TraceLoggingDataType.Win32Error; case EventSourceFieldFormat.NTStatus: return TraceLoggingDataType.NTStatus; #endif case EventFieldFormat.HResult: return TraceLoggingDataType.HResult; #if false case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int32; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt32; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType Format64( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.Hexadecimal: return TraceLoggingDataType.HexInt64; #if false case EventSourceFieldFormat.FileTime: return TraceLoggingDataType.FileTime; case EventSourceFieldFormat.Signed: return TraceLoggingDataType.Int64; case EventSourceFieldFormat.Unsigned: return TraceLoggingDataType.UInt64; #endif default: return MakeDataType(native, format); } } /// <summary> /// Adjusts the native type based on format. /// - If format is default, return native. /// - If format is recognized, return the canonical type for that format. /// - Otherwise remove existing format from native and apply the requested format. /// </summary> public static TraceLoggingDataType FormatPtr( EventFieldFormat format, TraceLoggingDataType native) { switch (format) { case EventFieldFormat.Default: return native; case EventFieldFormat.Hexadecimal: return HexIntPtrType; #if false case EventSourceFieldFormat.Signed: return IntPtrType; case EventSourceFieldFormat.Unsigned: return UIntPtrType; #endif default: return MakeDataType(native, format); } } #endregion #region Reflection helpers /* All TraceLogging use of reflection APIs should go through wrappers here. This helps with portability, and it also makes it easier to audit what kinds of reflection operations are being done. */ public static object CreateInstance(Type type, params object[] parameters) { return Activator.CreateInstance(type, parameters); } public static bool IsValueType(Type type) { bool result; #if ES_BUILD_PCL result = type.GetTypeInfo().IsValueType; #else result = type.IsValueType; #endif return result; } public static bool IsEnum(Type type) { bool result; #if ES_BUILD_PCL result = type.GetTypeInfo().IsEnum; #else result = type.IsEnum; #endif return result; } public static IEnumerable<PropertyInfo> GetProperties(Type type) { IEnumerable<PropertyInfo> result; #if ES_BUILD_PCL result = type.GetRuntimeProperties(); #else result = type.GetProperties(); #endif return result; } public static MethodInfo GetGetMethod(PropertyInfo propInfo) { MethodInfo result; #if ES_BUILD_PCL result = propInfo.GetMethod; #else result = propInfo.GetGetMethod(); #endif return result; } public static MethodInfo GetDeclaredStaticMethod(Type declaringType, string name) { MethodInfo result; #if ES_BUILD_PCL result = declaringType.GetTypeInfo().GetDeclaredMethod(name); #else result = declaringType.GetMethod( name, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic); #endif return result; } public static bool HasCustomAttribute( PropertyInfo propInfo, Type attributeType) { bool result; #if ES_BUILD_PCL result = propInfo.IsDefined(attributeType); #else var attributes = propInfo.GetCustomAttributes( attributeType, false); result = attributes.Length != 0; #endif return result; } public static AttributeType GetCustomAttribute<AttributeType>(PropertyInfo propInfo) where AttributeType : Attribute { AttributeType result = null; #if ES_BUILD_PCL foreach (var attrib in propInfo.GetCustomAttributes<AttributeType>(false)) { result = attrib; break; } #else var attributes = propInfo.GetCustomAttributes(typeof(AttributeType), false); if (attributes.Length != 0) { result = (AttributeType)attributes[0]; } #endif return result; } public static AttributeType GetCustomAttribute<AttributeType>(Type type) where AttributeType : Attribute { AttributeType result = null; #if ES_BUILD_PCL foreach (var attrib in type.GetTypeInfo().GetCustomAttributes<AttributeType>(false)) { result = attrib; break; } #else var attributes = type.GetCustomAttributes(typeof(AttributeType), false); if (attributes.Length != 0) { result = (AttributeType)attributes[0]; } #endif return result; } public static Type[] GetGenericArguments(Type type) { #if ES_BUILD_PCL return type.GenericTypeArguments; #else return type.GetGenericArguments(); #endif } public static Type FindEnumerableElementType(Type type) { Type elementType = null; if (IsGenericMatch(type, typeof(IEnumerable<>))) { elementType = GetGenericArguments(type)[0]; } else { #if ES_BUILD_PCL var ifaceTypes = type.GetTypeInfo().ImplementedInterfaces; #else var ifaceTypes = type.FindInterfaces(IsGenericMatch, typeof(IEnumerable<>)); #endif foreach (var ifaceType in ifaceTypes) { #if ES_BUILD_PCL if (!IsGenericMatch(ifaceType, typeof(IEnumerable<>))) { continue; } #endif if (elementType != null) { // ambiguous match. report no match at all. elementType = null; break; } elementType = GetGenericArguments(ifaceType)[0]; } } return elementType; } public static bool IsGenericMatch(Type type, object openType) { bool isGeneric; #if ES_BUILD_PCL isGeneric = type.IsConstructedGenericType; #else isGeneric = type.IsGenericType; #endif return isGeneric && type.GetGenericTypeDefinition() == (Type)openType; } public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo) { Delegate result; #if ES_BUILD_PCL result = methodInfo.CreateDelegate( delegateType); #else result = Delegate.CreateDelegate( delegateType, methodInfo); #endif return result; } public static TraceLoggingTypeInfo GetTypeInfoInstance(Type dataType, List<Type> recursionCheck) { TraceLoggingTypeInfo result; if (dataType == typeof(Int32)) { result = TraceLoggingTypeInfo<Int32>.Instance; } else if (dataType == typeof(Int64)) { result = TraceLoggingTypeInfo<Int64>.Instance; } else if (dataType == typeof(String)) { result = TraceLoggingTypeInfo<String>.Instance; } else { var getInstanceInfo = Statics.GetDeclaredStaticMethod( typeof(TraceLoggingTypeInfo<>).MakeGenericType(dataType), "GetInstance"); var typeInfoObj = getInstanceInfo.Invoke(null, new object[] { recursionCheck }); result = (TraceLoggingTypeInfo)typeInfoObj; } return result; } public static TraceLoggingTypeInfo<DataType> CreateDefaultTypeInfo<DataType>( List<Type> recursionCheck) { TraceLoggingTypeInfo result; var dataType = typeof(DataType); if (recursionCheck.Contains(dataType)) { throw new NotSupportedException(Environment.GetResourceString("EventSource_RecursiveTypeDefinition")); } recursionCheck.Add(dataType); var eventAttrib = Statics.GetCustomAttribute<EventDataAttribute>(dataType); if (eventAttrib != null || Statics.GetCustomAttribute<CompilerGeneratedAttribute>(dataType) != null) { var analysis = new TypeAnalysis(dataType, eventAttrib, recursionCheck); result = new InvokeTypeInfo<DataType>(analysis); } else if (dataType.IsArray) { var elementType = dataType.GetElementType(); if (elementType == typeof(Boolean)) { result = new BooleanArrayTypeInfo(); } else if (elementType == typeof(Byte)) { result = new ByteArrayTypeInfo(); } else if (elementType == typeof(SByte)) { result = new SByteArrayTypeInfo(); } else if (elementType == typeof(Int16)) { result = new Int16ArrayTypeInfo(); } else if (elementType == typeof(UInt16)) { result = new UInt16ArrayTypeInfo(); } else if (elementType == typeof(Int32)) { result = new Int32ArrayTypeInfo(); } else if (elementType == typeof(UInt32)) { result = new UInt32ArrayTypeInfo(); } else if (elementType == typeof(Int64)) { result = new Int64ArrayTypeInfo(); } else if (elementType == typeof(UInt64)) { result = new UInt64ArrayTypeInfo(); } else if (elementType == typeof(Char)) { result = new CharArrayTypeInfo(); } else if (elementType == typeof(Double)) { result = new DoubleArrayTypeInfo(); } else if (elementType == typeof(Single)) { result = new SingleArrayTypeInfo(); } else if (elementType == typeof(IntPtr)) { result = new IntPtrArrayTypeInfo(); } else if (elementType == typeof(UIntPtr)) { result = new UIntPtrArrayTypeInfo(); } else if (elementType == typeof(Guid)) { result = new GuidArrayTypeInfo(); } else { result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(ArrayTypeInfo<>).MakeGenericType(elementType), GetTypeInfoInstance(elementType, recursionCheck)); } } else if (Statics.IsEnum(dataType)) { var underlyingType = Enum.GetUnderlyingType(dataType); if (underlyingType == typeof(Int32)) { result = new EnumInt32TypeInfo<DataType>(); } else if (underlyingType == typeof(UInt32)) { result = new EnumUInt32TypeInfo<DataType>(); } else if (underlyingType == typeof(Byte)) { result = new EnumByteTypeInfo<DataType>(); } else if (underlyingType == typeof(SByte)) { result = new EnumSByteTypeInfo<DataType>(); } else if (underlyingType == typeof(Int16)) { result = new EnumInt16TypeInfo<DataType>(); } else if (underlyingType == typeof(UInt16)) { result = new EnumUInt16TypeInfo<DataType>(); } else if (underlyingType == typeof(Int64)) { result = new EnumInt64TypeInfo<DataType>(); } else if (underlyingType == typeof(UInt64)) { result = new EnumUInt64TypeInfo<DataType>(); } else { // Unexpected throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedEnumType", dataType.Name, underlyingType.Name)); } } else if (dataType == typeof(String)) { result = new StringTypeInfo(); } else if (dataType == typeof(Boolean)) { result = new BooleanTypeInfo(); } else if (dataType == typeof(Byte)) { result = new ByteTypeInfo(); } else if (dataType == typeof(SByte)) { result = new SByteTypeInfo(); } else if (dataType == typeof(Int16)) { result = new Int16TypeInfo(); } else if (dataType == typeof(UInt16)) { result = new UInt16TypeInfo(); } else if (dataType == typeof(Int32)) { result = new Int32TypeInfo(); } else if (dataType == typeof(UInt32)) { result = new UInt32TypeInfo(); } else if (dataType == typeof(Int64)) { result = new Int64TypeInfo(); } else if (dataType == typeof(UInt64)) { result = new UInt64TypeInfo(); } else if (dataType == typeof(Char)) { result = new CharTypeInfo(); } else if (dataType == typeof(Double)) { result = new DoubleTypeInfo(); } else if (dataType == typeof(Single)) { result = new SingleTypeInfo(); } else if (dataType == typeof(DateTime)) { result = new DateTimeTypeInfo(); } else if (dataType == typeof(Decimal)) { result = new DecimalTypeInfo(); } else if (dataType == typeof(IntPtr)) { result = new IntPtrTypeInfo(); } else if (dataType == typeof(UIntPtr)) { result = new UIntPtrTypeInfo(); } else if (dataType == typeof(Guid)) { result = new GuidTypeInfo(); } else if (dataType == typeof(TimeSpan)) { result = new TimeSpanTypeInfo(); } else if (dataType == typeof(DateTimeOffset)) { result = new DateTimeOffsetTypeInfo(); } else if (dataType == typeof(EmptyStruct)) { result = new NullTypeInfo<EmptyStruct>(); } else if (IsGenericMatch(dataType, typeof(KeyValuePair<,>))) { var args = GetGenericArguments(dataType); result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(KeyValuePairTypeInfo<,>).MakeGenericType(args[0], args[1]), recursionCheck); } else if (IsGenericMatch(dataType, typeof(Nullable<>))) { var args = GetGenericArguments(dataType); result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(NullableTypeInfo<>).MakeGenericType(args[0]), recursionCheck); } else { var elementType = FindEnumerableElementType(dataType); if (elementType != null) { result = (TraceLoggingTypeInfo<DataType>)CreateInstance( typeof(EnumerableTypeInfo<,>).MakeGenericType(dataType, elementType), GetTypeInfoInstance(elementType, recursionCheck)); } else { throw new ArgumentException(Environment.GetResourceString("EventSource_NonCompliantTypeError", dataType.Name)); } } return (TraceLoggingTypeInfo<DataType>)result; } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using System.Xml; using System.Xml.XPath; using Umbraco.Core.Logging; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.Routing; using umbraco; using System.Linq; using umbraco.BusinessLogic; using umbraco.presentation.preview; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class PublishedContentCache : IPublishedContentCache { #region Routes cache private readonly RoutesCache _routesCache = new RoutesCache(!UnitTesting); // for INTERNAL, UNIT TESTS use ONLY internal RoutesCache RoutesCache { get { return _routesCache; } } // for INTERNAL, UNIT TESTS use ONLY internal static bool UnitTesting = false; public virtual IPublishedContent GetByRoute(UmbracoContext umbracoContext, bool preview, string route, bool? hideTopLevelNode = null) { if (route == null) throw new ArgumentNullException("route"); // try to get from cache if not previewing var contentId = preview ? 0 : _routesCache.GetNodeId(route); // if found id in cache then get corresponding content // and clear cache if not found - for whatever reason IPublishedContent content = null; if (contentId > 0) { content = GetById(umbracoContext, preview, contentId); if (content == null) _routesCache.ClearNode(contentId); } // still have nothing? actually determine the id hideTopLevelNode = hideTopLevelNode ?? GlobalSettings.HideTopLevelNodeFromPath; // default = settings content = content ?? DetermineIdByRoute(umbracoContext, preview, route, hideTopLevelNode.Value); // cache if we have a content and not previewing if (content != null && !preview) { var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/'))); var iscanon = !UnitTesting && !DomainHelper.ExistsDomainInPath(DomainHelper.GetAllDomains(false), content.Path, domainRootNodeId); // and only if this is the canonical url (the one GetUrl would return) if (iscanon) _routesCache.Store(contentId, route); } return content; } public virtual string GetRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { // try to get from cache if not previewing var route = preview ? null : _routesCache.GetRoute(contentId); // if found in cache then return if (route != null) return route; // else actually determine the route route = DetermineRouteById(umbracoContext, preview, contentId); // cache if we have a route and not previewing if (route != null && !preview) _routesCache.Store(contentId, route); return route; } IPublishedContent DetermineIdByRoute(UmbracoContext umbracoContext, bool preview, string route, bool hideTopLevelNode) { if (route == null) throw new ArgumentNullException("route"); //the route always needs to be lower case because we only store the urlName attribute in lower case route = route.ToLowerInvariant(); var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos)); IEnumerable<XPathVariable> vars; var xpath = CreateXpathQuery(startNodeId, path, hideTopLevelNode, out vars); //check if we can find the node in our xml cache var content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray()); // if hideTopLevelNodePath is true then for url /foo we looked for /*/foo // but maybe that was the url of a non-default top-level node, so we also // have to look for /foo (see note in ApplyHideTopLevelNodeFromPath). if (content == null && hideTopLevelNode && path.Length > 1 && path.IndexOf('/', 1) < 0) { xpath = CreateXpathQuery(startNodeId, path, false, out vars); content = GetSingleByXPath(umbracoContext, preview, xpath, vars == null ? null : vars.ToArray()); } return content; } string DetermineRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { var node = GetById(umbracoContext, preview, contentId); if (node == null) return null; // walk up from that node until we hit a node with a domain, // or we reach the content root, collecting urls in the way var pathParts = new List<string>(); var n = node; var hasDomains = DomainHelper.NodeHasDomains(n.Id); while (!hasDomains && n != null) // n is null at root { // get the url var urlName = n.UrlName; pathParts.Add(urlName); // move to parent node n = n.Parent; hasDomains = n != null && DomainHelper.NodeHasDomains(n.Id); } // no domain, respect HideTopLevelNodeFromPath for legacy purposes if (!hasDomains && global::umbraco.GlobalSettings.HideTopLevelNodeFromPath) ApplyHideTopLevelNodeFromPath(umbracoContext, node, pathParts); // assemble the route pathParts.Reverse(); var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc var route = (n == null ? "" : n.Id.ToString(CultureInfo.InvariantCulture)) + path; return route; } static void ApplyHideTopLevelNodeFromPath(UmbracoContext umbracoContext, IPublishedContent node, IList<string> pathParts) { // in theory if hideTopLevelNodeFromPath is true, then there should be only once // top-level node, or else domains should be assigned. but for backward compatibility // we add this check - we look for the document matching "/" and if it's not us, then // we do not hide the top level path // it has to be taken care of in GetByRoute too so if // "/foo" fails (looking for "/*/foo") we try also "/foo". // this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but // that's the way it works pre-4.10 and we try to be backward compat for the time being if (node.Parent == null) { var rootNode = umbracoContext.ContentCache.GetByRoute("/", true); if (rootNode == null) throw new Exception("Failed to get node at /."); if (rootNode.Id == node.Id) // remove only if we're the default node pathParts.RemoveAt(pathParts.Count - 1); } else { pathParts.RemoveAt(pathParts.Count - 1); } } #endregion #region XPath Strings class XPathStringsDefinition { public int Version { get; private set; } public static string Root { get { return "/root"; } } public string RootDocuments { get; private set; } public string DescendantDocumentById { get; private set; } public string ChildDocumentByUrlName { get; private set; } public string ChildDocumentByUrlNameVar { get; private set; } public string RootDocumentWithLowestSortOrder { get; private set; } public XPathStringsDefinition(int version) { Version = version; switch (version) { // legacy XML schema case 0: RootDocuments = "/root/node"; DescendantDocumentById = "//node [@id={0}]"; ChildDocumentByUrlName = "/node [@urlName='{0}']"; ChildDocumentByUrlNameVar = "/node [@urlName=${0}]"; RootDocumentWithLowestSortOrder = "/root/node [not(@sortOrder > ../node/@sortOrder)][1]"; break; // default XML schema as of 4.10 case 1: RootDocuments = "/root/* [@isDoc]"; DescendantDocumentById = "//* [@isDoc and @id={0}]"; ChildDocumentByUrlName = "/* [@isDoc and @urlName='{0}']"; ChildDocumentByUrlNameVar = "/* [@isDoc and @urlName=${0}]"; RootDocumentWithLowestSortOrder = "/root/* [@isDoc and not(@sortOrder > ../* [@isDoc]/@sortOrder)][1]"; break; default: throw new Exception(string.Format("Unsupported Xml schema version '{0}').", version)); } } } static XPathStringsDefinition _xPathStringsValue; static XPathStringsDefinition XPathStrings { get { // in theory XPathStrings should be a static variable that // we should initialize in a static ctor - but then test cases // that switch schemas fail - so cache and refresh when needed, // ie never when running the actual site var version = UmbracoSettings.UseLegacyXmlSchema ? 0 : 1; if (_xPathStringsValue == null || _xPathStringsValue.Version != version) _xPathStringsValue = new XPathStringsDefinition(version); return _xPathStringsValue; } } #endregion #region Converters private static IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing) { return xmlNode == null ? null : PublishedContentModelFactory.CreateModel(new XmlPublishedContent(xmlNode, isPreviewing)); } private static IEnumerable<IPublishedContent> ConvertToDocuments(XmlNodeList xmlNodes, bool isPreviewing) { return xmlNodes.Cast<XmlNode>() .Select(xmlNode => PublishedContentModelFactory.CreateModel(new XmlPublishedContent(xmlNode, isPreviewing))); } #endregion #region Getters public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return ConvertToDocument(GetXml(umbracoContext, preview).GetElementById(nodeId.ToString(CultureInfo.InvariantCulture)), preview); } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { return ConvertToDocuments(GetXml(umbracoContext, preview).SelectNodes(XPathStrings.RootDocuments), preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return null; var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return Enumerable.Empty<IPublishedContent>(); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual bool HasContent(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); if (xml == null) return false; var node = xml.SelectSingleNode(XPathStrings.RootDocuments); return node != null; } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); return xml.CreateNavigator(); } public virtual bool XPathNavigatorIsNavigable { get { return false; } } #endregion #region Legacy Xml static readonly ConditionalWeakTable<UmbracoContext, PreviewContent> PreviewContentCache = new ConditionalWeakTable<UmbracoContext, PreviewContent>(); private Func<UmbracoContext, bool, XmlDocument> _xmlDelegate; /// <summary> /// Gets/sets the delegate used to retreive the Xml content, generally the setter is only used for unit tests /// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request /// </summary> /// <remarks> /// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request /// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff /// that when run inside of a unit test fails. /// </remarks> internal Func<UmbracoContext, bool, XmlDocument> GetXmlDelegate { get { return _xmlDelegate ?? (_xmlDelegate = (context, preview) => { if (preview) { var previewContent = PreviewContentCache.GetOrCreateValue(context); // will use the ctor with no parameters previewContent.EnsureInitialized(context.UmbracoUser, StateHelper.Cookies.Preview.GetValue(), true, () => { if (previewContent.ValidPreviewSet) previewContent.LoadPreviewset(); }); if (previewContent.ValidPreviewSet) return previewContent.XmlContent; } return content.Instance.XmlContent; }); } set { _xmlDelegate = value; } } internal XmlDocument GetXml(UmbracoContext umbracoContext, bool preview) { return GetXmlDelegate(umbracoContext, preview); } #endregion #region XPathQuery static readonly char[] SlashChar = new[] { '/' }; protected string CreateXpathQuery(int startNodeId, string path, bool hideTopLevelNodeFromPath, out IEnumerable<XPathVariable> vars) { string xpath; vars = null; if (path == string.Empty || path == "/") { // if url is empty if (startNodeId > 0) { // if in a domain then use the root node of the domain xpath = string.Format(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId); } else { // if not in a domain - what is the default page? // let's say it is the first one in the tree, if any -- order by sortOrder // but! // umbraco does not consistently guarantee that sortOrder starts with 0 // so the one that we want is the one with the smallest sortOrder // read http://stackoverflow.com/questions/1128745/how-can-i-use-xpath-to-find-the-minimum-value-of-an-attribute-in-a-set-of-elemen // so that one does not work, because min(@sortOrder) maybe 1 // xpath = "/root/*[@isDoc and @sortOrder='0']"; // and we can't use min() because that's XPath 2.0 // that one works xpath = XPathStrings.RootDocumentWithLowestSortOrder; } } else { // if url is not empty, then use it to try lookup a matching page var urlParts = path.Split(SlashChar, StringSplitOptions.RemoveEmptyEntries); var xpathBuilder = new StringBuilder(); int partsIndex = 0; List<XPathVariable> varsList = null; if (startNodeId == 0) { if (hideTopLevelNodeFromPath) xpathBuilder.Append(XPathStrings.RootDocuments); // first node is not in the url else xpathBuilder.Append(XPathStringsDefinition.Root); } else { xpathBuilder.AppendFormat(XPathStringsDefinition.Root + XPathStrings.DescendantDocumentById, startNodeId); // always "hide top level" when there's a domain } while (partsIndex < urlParts.Length) { var part = urlParts[partsIndex++]; if (part.Contains('\'') || part.Contains('"')) { // use vars, escaping gets ugly pretty quickly varsList = varsList ?? new List<XPathVariable>(); var varName = string.Format("var{0}", partsIndex); varsList.Add(new XPathVariable(varName, part)); xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlNameVar, varName); } else { xpathBuilder.AppendFormat(XPathStrings.ChildDocumentByUrlName, part); } } xpath = xpathBuilder.ToString(); if (varsList != null) vars = varsList.ToArray(); } return xpath; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace eventsarray.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.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using SIL.IO; using SIL.PlatformUtilities; using SIL.Reporting; using SIL.Windows.Forms.ImageToolbox; namespace SIL.Windows.Forms.Miscellaneous { /// <summary>Uses the GTK classes when accessing the clipboard on Linux</summary> public static class PortableClipboard { public static bool ContainsText() { return Platform.IsWindows ? Clipboard.ContainsText() : GtkContainsText(); } public static string GetText() { return Platform.IsWindows ? Clipboard.GetText() : GtkGetText(); } public static string GetText(TextDataFormat format) { return Platform.IsWindows ? Clipboard.GetText(format) : GtkGetText(); } public static void SetText(string text) { if (Platform.IsWindows) Clipboard.SetText(text); else GtkSetText(text); } public static void SetText(string text, TextDataFormat format) { if (Platform.IsWindows) Clipboard.SetText(text, format); else GtkSetText(text); } public static bool ContainsImage() { return Platform.IsWindows ? Clipboard.ContainsImage() : GtkContainsImage(); } public static Image GetImage() { return Platform.IsWindows ? Clipboard.GetImage() : GtkGetImage(); } public static void CopyImageToClipboard(PalasoImage image) { // N.B.: PalasoImage does not handle .svg files if(image == null) return; if (!Platform.IsWindows) { // Review: Someone who knows how needs to implement this! throw new NotImplementedException( "SIL.Windows.Forms.Miscellaneous.PortableClipboard.CopyImageToClipboard() is not yet implemented for Linux"); } if (image.Image == null) { if (string.IsNullOrEmpty(image.OriginalFilePath)) return; // no image, but a path Clipboard.SetFileDropList(new StringCollection() {image.OriginalFilePath}); } else { if (string.IsNullOrEmpty(image.OriginalFilePath)) Clipboard.SetImage(image.Image); else { IDataObject clips = new DataObject(); clips.SetData(DataFormats.UnicodeText, image.OriginalFilePath); clips.SetData(DataFormats.Bitmap, image.Image); // true here means that the image should remain on the clipboard if the application exits Clipboard.SetDataObject(clips,true); } } } // Get an image from the clipboard, ignoring any errors that occur while we attempt to // convert whatever is on the clipboard into an image. public static PalasoImage GetImageFromClipboard() { try { return GetImageFromClipboardWithExceptions(); } catch (Exception) {} return null; } // Try to get an image from the clipboard. If there simply isn't anything on the clipboard that // can reasonably be interpreted as an image, return null. If there is something that makes sense // as an image, but trying to load it causes an exception, let the exception propagate. public static PalasoImage GetImageFromClipboardWithExceptions() { // N.B.: PalasoImage does not handle .svg files if (!Platform.IsWindows) { if (GtkContainsImage()) return PalasoImage.FromImage(GtkGetImage()); if (GtkContainsText()) { //REVIEW: I can find no documentation on GtkClipboard. If ContainsText means we have a file // path, then it would be better to do PalasoImage.FromFileRobustly(); on the file path return PalasoImage.FromImage(GtkGetImageFromText()); } return null; } var dataObject = Clipboard.GetDataObject(); if (dataObject == null) return null; Exception ex = null; var textData = String.Empty; if (dataObject.GetDataPresent(DataFormats.UnicodeText)) textData = dataObject.GetData(DataFormats.UnicodeText) as String; if (Clipboard.ContainsImage()) { PalasoImage plainImage = null; try { plainImage = PalasoImage.FromImage(Clipboard.GetImage()); // this method won't copy any metadata var haveFileUrl = !String.IsNullOrEmpty(textData) && RobustFile.Exists(textData); // If we have an image on the clipboard, and we also have text that is a valid url to an image file, // use the url to create a PalasoImage (which will pull in any metadata associated with the image too) if (haveFileUrl) { var imageWithPathAndMaybeMetadata = PalasoImage.FromFileRobustly(textData); plainImage.Dispose();//important: don't do this until we've successfully created the imageWithPathAndMaybeMetadata return imageWithPathAndMaybeMetadata; } return plainImage; } catch (Exception e) { Logger.WriteEvent("PortableClipboard.GetImageFromClipboard() failed with message " + e.Message); if (plainImage != null) return plainImage; // at worst, we should return null; if FromFile() failed, we return an image throw; } } // the ContainsImage() returns false when copying an PNG from MS Word // so here we explicitly ask for a PNG and see if we can convert it. if (dataObject.GetDataPresent("PNG")) { var o = dataObject.GetData("PNG") as Stream; try { return PalasoImage.FromImage(Image.FromStream(o)); } catch (Exception e) { // I'm not sure why, but previous versions of this code would continue trying other // options at this point. ex = e; } } //People can do a "copy" from the WIndows Photo Viewer but what it puts on the clipboard is a path, not an image if (dataObject.GetDataPresent(DataFormats.FileDrop)) { //This line gets all the file paths that were selected in explorer string[] files = dataObject.GetData(DataFormats.FileDrop) as string[]; if (files == null) return null; foreach (var file in files.Where(f => RobustFile.Exists(f))) { return PalasoImage.FromFileRobustly(file); } return null; //not an image } if (Clipboard.ContainsText() && RobustFile.Exists(Clipboard.GetText())) return PalasoImage.FromImage( Image.FromStream(new FileStream(Clipboard.GetText(), FileMode.Open))); if (ex != null) { throw ex; } return null; } // The following methods are derived from GtkClipboard.cs from https://github.com/phillip-hopper/GtkUtils. /// <summary>Set the clipboard text</summary> private static void GtkSetText(string text) { using (var cb = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false))) { cb.Text = text; } } /// <summary>Is there text on the clipboard?</summary> private static bool GtkContainsText() { using (var cb = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false))) { return cb.WaitIsTextAvailable(); } } /// <summary>Get the clipboard text</summary> private static string GtkGetText() { using (var cb = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false))) { return cb.WaitForText(); } } /// <summary>Is there an image on the clipboard?</summary> private static bool GtkContainsImage() { using (var cb = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false))) { return cb.WaitIsImageAvailable(); } } /// <summary>Get the image from clipboard</summary> private static Image GtkGetImage() { using (var cb = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false))) { Gdk.Pixbuf buff = cb.WaitForImage(); TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap)); return (Image)tc.ConvertFrom(buff.SaveToBuffer("png")); } } /// <summary>Get the image from a file name on the clipboard</summary> private static Image GtkGetImageFromText() { var stringSeparators = new string[] { Environment.NewLine }; var paths = GetText().Split(stringSeparators, StringSplitOptions.None); foreach (var path in paths) { if (File.Exists(path)) { try { var bytes = File.ReadAllBytes(path); var buff = new Gdk.Pixbuf(bytes); TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap)); return (Image)tc.ConvertFrom(buff.SaveToBuffer("png")); } catch (Exception e) { Console.Out.WriteLine("{0} is not an image file ({1}).", path, e.Message); } } } return null; } // ------------------------------------------------------------------------------------------------------------- // Clipboard operations (copy/cut/paste) in text boxes do not work properly on Linux in some situations, // freezing or crashing the program. See https://issues.bloomlibrary.org/youtrack/issue/BL-5681 for one example. // The following methods were added to allow dialogs to use the PortableClipboard in TextBox and RichTextBox // controls. It's possible that these methods might only be used on Linux, but they compile (and would work) // fine for Windows. // These methods are used by FormUsingPortableClipboard. /// <summary> /// Recursively remove all TextBox menus found owned by the control. /// </summary> /// <remarks>> /// It might be better to hook up the copy/cut/paste commands to use the PortableClipboard instead, but that /// would be a lot trickier to pull off reliably. /// </remarks> public static void RemoveTextboxMenus(Control control) { if (control is TextBoxBase) { (control as TextBoxBase).ContextMenu = null; return; } else if (control == null || control.Controls == null) { return; } foreach (var ctl in control.Controls) RemoveTextboxMenus(ctl as Control); } /// <summary> /// Process the clipboard cmd keys for a dialog. This is called from a ProcessCmdKeys override method. /// </summary> /// <returns><c>true</c>, if a clipboard command key for this dialog was processed, <c>false</c> otherwise.</returns> public static bool ProcessClipboardCmdKeysForDialog(Form form, Message msg, Keys keyData) { switch (keyData) { case Keys.Control|Keys.V: return PortablePasteIntoTextBox(form, msg.HWnd); case Keys.Control|Keys.C: return PortableCopyOrCutFromTextBox(form, msg.HWnd, false); case Keys.Control|Keys.X: return PortableCopyOrCutFromTextBox(form, msg.HWnd, true); } return false; } /// <summary> /// Recursively search for a TextBox or RichTextBox control with the given handle. /// </summary> /// <returns>the matching TextBoxBase control if found, null otherwise.</returns> private static TextBoxBase GetTextBoxFromHWnd(Control control, IntPtr hwnd) { if (control is TextBoxBase && (control as TextBoxBase).Handle == hwnd) return (control as TextBoxBase); else if (control == null || control.Controls == null) return null; foreach (var ctl in control.Controls) { var box = GetTextBoxFromHWnd(ctl as Control, hwnd); if (box != null) return box; } return null; } /// <summary> /// Paste from the PortableClipboard into a textbox in the given form that matches the given hwnd. /// </summary> /// <returns><c>true</c>, if pasting into a textbox was successful, <c>false</c> otherwise.</returns> private static bool PortablePasteIntoTextBox(Form form, IntPtr hwnd) { var box = GetTextBoxFromHWnd(form, hwnd); if (box == null) return false; if (ContainsText()) { var start = box.SelectionStart; var length = box.SelectionLength; var text = box.Text; if (length > 0) { if (start + length > text.Length) // shouldn't happen, but sometimes paranoia pays text = text.Remove(start); else text = text.Remove(start, length); } var clipText = GetText(); box.Text = text.Insert(start, clipText); box.SelectionStart = start + clipText.Length; } return true; } /// <summary> /// Copy (or cut) into the PortableClipboard from a textbox in the given form that matches the given hwnd. /// </summary> /// <returns><c>true</c>, if copying or cutting from a textbox was successful, <c>false</c> otherwise.</returns> private static bool PortableCopyOrCutFromTextBox(Form form, IntPtr hwnd, bool cut) { var box = GetTextBoxFromHWnd(form, hwnd); if (box == null) return false; var length = box.SelectionLength; if (length > 0) { var start = box.SelectionStart; if (start + length > box.Text.Length) length = box.Text.Length - start; // shouldn't happen, but paranoia sometimes pays. if (length <= 0) return true; var text = box.Text.Substring(start, length); SetText(text); if (cut) { box.Text = box.Text.Remove(start, length); box.SelectionStart = start; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Diagnostics; using System.Data.Common; using Res = System.SR; namespace System.Data.SqlTypes { public sealed class SqlChars : System.Data.SqlTypes.INullable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlChars has five possible states // 1) SqlChars is Null // - m_stream must be null, m_lCuLen must be x_lNull // 2) SqlChars contains a valid buffer, // - m_rgchBuf must not be null, and m_stream must be null // 3) SqlChars contains a valid pointer // - m_rgchBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlChars contains a SqlStreamChars // - m_stream must not be null // - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlChars contains a Lazy Materialized Blob (i.e, StorageState.Delayed) // internal char[] m_rgchBuf; // Data buffer private long _lCurLen; // Current data length internal SqlStreamChars m_stream; private SqlBytesCharsState _state; private char[] _rgchWorkBuf; // A 1-char work buffer. // The max data length that we support at this time. private const long x_lMaxLen = (long)System.Int32.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlChars() { SetNull(); } // Create a SqlChars with an in-memory buffer public SqlChars(char[] buffer) { m_rgchBuf = buffer; m_stream = null; if (m_rgchBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = (long)m_rgchBuf.Length; } _rgchWorkBuf = null; AssertValid(); } // Create a SqlChars from a SqlString public SqlChars(SqlString value) : this(value.IsNull ? (char[])null : value.Value.ToCharArray()) { } // Create a SqlChars from a SqlStreamChars internal SqlChars(SqlStreamChars s) { m_rgchBuf = null; _lCurLen = x_lNull; m_stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgchWorkBuf = null; AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlChars // Return Buffer even if SqlChars is Null. public char[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return m_rgchBuf; } } // Property: the actual length of the data public long Length { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return m_stream.Length; default: return _lCurLen; } } } // Property: the max length of the data // Return MaxLength even if SqlChars is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { switch (_state) { case SqlBytesCharsState.Stream: return -1L; default: return (m_rgchBuf == null) ? -1L : (long)m_rgchBuf.Length; } } } // Property: get a copy of the data in a new char[] array. public char[] Value { get { char[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (m_stream.Length > x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); buffer = new char[m_stream.Length]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(buffer, 0, checked((int)m_stream.Length)); break; default: buffer = new char[_lCurLen]; Array.Copy(m_rgchBuf, 0, buffer, 0, (int)_lCurLen); break; } return buffer; } } // class indexer public char this[long offset] { get { if (offset < 0 || offset >= this.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; Read(offset, _rgchWorkBuf, 0, 1); return _rgchWorkBuf[0]; } set { if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); } } internal SqlStreamChars Stream { get { return FStream() ? m_stream : new StreamOnSqlChars(this); } set { _lCurLen = x_lNull; m_stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } public StorageState Storage { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return StorageState.Stream; case SqlBytesCharsState.Buffer: return StorageState.Buffer; default: return StorageState.UnmanagedBuffer; } } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; m_stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlChars is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); if (FStream()) { m_stream.SetLength(value); } else { // If there is a buffer, even the value of SqlChars is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == m_rgchBuf) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (value > (long)m_rgchBuf.Length) throw new ArgumentOutOfRangeException(nameof(value)); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, char[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset > this.Length || offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); // Adjust count based on data length if (count > this.Length - offset) count = (int)(this.Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Read(buffer, offsetInBuffer, count); break; default: // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(m_rgchBuf, checked((int)offset), buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlChars from specified offset public void Write(long offset, char[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (m_rgchBuf == null) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset > m_rgchBuf.Length) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); if (count > m_rgchBuf.Length - offset) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteNonZeroOffsetOnNullMessage)); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteOffsetLargerThanLenMessage)); } if (count != 0) { // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(buffer, offsetInBuffer, m_rgchBuf, checked((int)offset), count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlString ToSqlString() { return IsNull ? SqlString.Null : new String(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlString() public static explicit operator SqlString(SqlChars value) { return value.ToSqlString(); } // Alternative method: constructor SqlChars(SqlString) public static explicit operator SqlChars(SqlString value) { return new SqlChars(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [System.Diagnostics.Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (m_rgchBuf != null && _lCurLen <= m_rgchBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1); } // whether the SqlChars contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } // Copy the data from the Stream to the array buffer. // If the SqlChars doesn't hold a buffer or the buffer // is not big enough, allocate new char array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = m_stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (m_rgchBuf == null || m_rgchBuf.Length < lStreamLen) m_rgchBuf = new char[lStreamLen]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(m_rgchBuf, 0, (int)lStreamLen); m_stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlChars is mutable, have to be property and create a new one each time. public static SqlChars Null { get { return new SqlChars((char[])null); } } } // class SqlChars // StreamOnSqlChars is a stream build on top of SqlChars, and // provides the Stream interface. The purpose is to help users // to read/write SqlChars object. internal sealed class StreamOnSqlChars : SqlStreamChars { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private SqlChars _sqlchars; // the SqlChars object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal StreamOnSqlChars(SqlChars s) { _sqlchars = s; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- public override bool IsNull { get { return _sqlchars == null || _sqlchars.IsNull; } } // Always can read/write/seek, unless sb is null, // which means the stream has been closed. public override bool CanRead { get { return _sqlchars != null && !_sqlchars.IsNull; } } public override bool CanSeek { get { return _sqlchars != null; } } public override bool CanWrite { get { return _sqlchars != null && (!_sqlchars.IsNull || _sqlchars.m_rgchBuf != null); } } public override long Length { get { CheckIfStreamClosed("get_Length"); return _sqlchars.Length; } } public override long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sqlchars.Length) throw new ArgumentOutOfRangeException(nameof(value)); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed("Seek"); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sqlchars.Length + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = lPosition; break; default: throw ADP.ArgumentOutOfRange("offset"); ; } return _lPosition; } // The Read/Write/Readchar/Writechar simply delegates to SqlChars public override int Read(char[] buffer, int offset, int count) { CheckIfStreamClosed("Read"); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count); _lPosition += icharsRead; return icharsRead; } public override void Write(char[] buffer, int offset, int count) { CheckIfStreamClosed("Write"); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); _sqlchars.Write(_lPosition, buffer, offset, count); _lPosition += count; } public override int ReadChar() { CheckIfStreamClosed("ReadChar"); // If at the end of stream, return -1, rather than call SqlChars.Readchar, // which will throw exception. This is the behavior for Stream. // if (_lPosition >= _sqlchars.Length) return -1; int ret = _sqlchars[_lPosition]; _lPosition++; return ret; } public override void WriteChar(char value) { CheckIfStreamClosed("WriteChar"); _sqlchars[_lPosition] = value; _lPosition++; } public override void SetLength(long value) { CheckIfStreamClosed("SetLength"); _sqlchars.SetLength(value); if (_lPosition > value) _lPosition = value; } // Flush is a no-op if underlying SqlChars is not a stream on SqlChars public override void Flush() { if (_sqlchars.FStream()) _sqlchars.m_stream.Flush(); } protected override void Dispose(bool disposing) { // When m_sqlchars is null, it means the stream has been closed, and // any opearation in the future should fail. // This is the only case that m_sqlchars is null. _sqlchars = null; } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sqlchars == null; } private void CheckIfStreamClosed(string methodname) { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class StreamOnSqlChars } // namespace System.Data.SqlTypes
//------------------------------------------------------------------------------ // <copyright file="XmlSiteMapProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * XmlSiteMapProvider class definition * * Copyright (c) 2002 Microsoft Corporation */ namespace System.Web { using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Configuration; using System.Configuration.Provider; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Resources; using System.Security; using System.Security.Permissions; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Hosting; using System.Web.UI; using System.Web.Util; using System.Xml; // XmlMapProvider that generates sitemap tree from xml files public class XmlSiteMapProvider : StaticSiteMapProvider, IDisposable { private string _filename; private VirtualPath _virtualPath; private VirtualPath _normalizedVirtualPath; private SiteMapNode _siteMapNode; private XmlDocument _document; private bool _initialized; private FileChangeEventHandler _handler; private StringCollection _parentSiteMapFileCollection; private const string _providerAttribute = "provider"; private const string _siteMapFileAttribute = "siteMapFile"; private const string _siteMapNodeName = "siteMapNode"; private const string _xmlSiteMapFileExtension = ".sitemap"; private const string _resourcePrefix = "$resources:"; private const int _resourcePrefixLength = 10; private const char _resourceKeySeparator = ','; private static readonly char[] _seperators = new char[] { ';', ',' }; private ArrayList _childProviderList; // table containing mappings from child providers to their root nodes. private Hashtable _childProviderTable; public XmlSiteMapProvider() { } private ArrayList ChildProviderList { get { ArrayList returnList = _childProviderList; if (returnList == null) { lock (_lock) { if (_childProviderList == null) { returnList = ArrayList.ReadOnly(new ArrayList(ChildProviderTable.Keys)); _childProviderList = returnList; } else { returnList = _childProviderList; } } } return returnList; } } private Hashtable ChildProviderTable { get { if (_childProviderTable == null) { lock (_lock) { if (_childProviderTable == null) { _childProviderTable = new Hashtable(); } } } return _childProviderTable; } } public override SiteMapNode RootNode { get { BuildSiteMap(); SiteMapNode node = ReturnNodeIfAccessible(_siteMapNode); return ApplyModifierIfExists(node); } } public override SiteMapNode CurrentNode { get { return ApplyModifierIfExists(base.CurrentNode); } } public override SiteMapNode GetParentNode(SiteMapNode node) { SiteMapNode parentNode = base.GetParentNode(node); return ApplyModifierIfExists(parentNode); } public override SiteMapNodeCollection GetChildNodes(SiteMapNode node) { SiteMapNodeCollection subNodes = base.GetChildNodes(node); HttpContext context = HttpContext.Current; // Do nothing if the modifier doesn't apply if (context == null || !context.Response.UsePathModifier || subNodes.Count == 0) { return subNodes; } // Apply the modifier to the children nodes SiteMapNodeCollection resultNodes = new SiteMapNodeCollection(subNodes.Count); foreach (SiteMapNode n in subNodes) { resultNodes.Add(ApplyModifierIfExists(n)); } return resultNodes; } protected internal override void AddNode(SiteMapNode node, SiteMapNode parentNode) { if (node == null) { throw new ArgumentNullException("node"); } if (parentNode == null) { throw new ArgumentNullException("parentNode"); } SiteMapProvider ownerProvider = node.Provider; SiteMapProvider parentOwnerProvider = parentNode.Provider; if (ownerProvider != this) { throw new ArgumentException(SR.GetString(SR.XmlSiteMapProvider_cannot_add_node, node.ToString()), "node"); } if (parentOwnerProvider != this) { throw new ArgumentException(SR.GetString(SR.XmlSiteMapProvider_cannot_add_node, parentNode.ToString()), "parentNode"); } lock (_lock) { // First remove it from its current location. RemoveNode(node); AddNodeInternal(node, parentNode, null); } } private void AddNodeInternal(SiteMapNode node, SiteMapNode parentNode, XmlNode xmlNode) { lock (_lock) { String url = node.Url; String key = node.Key; bool isValidUrl = false; // Only add the node to the url table if it's a static node. if (!String.IsNullOrEmpty(url)) { if (UrlTable[url] != null) { if (xmlNode != null) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Multiple_Nodes_With_Identical_Url, url), xmlNode); } else { throw new InvalidOperationException(SR.GetString( SR.XmlSiteMapProvider_Multiple_Nodes_With_Identical_Url, url)); } } isValidUrl = true; } if (KeyTable.Contains(key)) { if (xmlNode != null) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Multiple_Nodes_With_Identical_Key, key), xmlNode); } else { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_Multiple_Nodes_With_Identical_Key, key)); } } if (isValidUrl) { UrlTable[url] = node; } KeyTable[key] = node; // Add the new node into parentNode collection if (parentNode != null) { ParentNodeTable[node] = parentNode; if (ChildNodeCollectionTable[parentNode] == null) { ChildNodeCollectionTable[parentNode] = new SiteMapNodeCollection(); } ((SiteMapNodeCollection)ChildNodeCollectionTable[parentNode]).Add(node); } } } protected virtual void AddProvider(string providerName, SiteMapNode parentNode) { if (parentNode == null) { throw new ArgumentNullException("parentNode"); } if (parentNode.Provider != this) { throw new ArgumentException(SR.GetString(SR.XmlSiteMapProvider_cannot_add_node, parentNode.ToString()), "parentNode"); } SiteMapNode node = GetNodeFromProvider(providerName); AddNodeInternal(node, parentNode, null); } [SuppressMessage("Microsoft.Security", "MSEC1205:DoNotAllowDtdOnXmlTextReader", Justification = "Legacy code that trusts our developer-controlled input.")] public override SiteMapNode BuildSiteMap() { SiteMapNode tempNode = _siteMapNode; // If siteMap is already constructed, simply returns it. // Child providers will only be updated when the parent providers need to access them. if (tempNode != null) { return tempNode; } XmlDocument document = GetConfigDocument(); lock (_lock) { if (_siteMapNode != null) { return _siteMapNode; } Clear(); // Need to check if the sitemap file exists before opening it. CheckSiteMapFileExists(); try { using (Stream stream = _normalizedVirtualPath.OpenFile()) { XmlReader reader = new XmlTextReader(stream); document.Load(reader); } } catch (XmlException e) { string sourceFile = _virtualPath.VirtualPathString; string physicalDir = _normalizedVirtualPath.MapPathInternal(); if (physicalDir != null && HttpRuntime.HasPathDiscoveryPermission(physicalDir)) { sourceFile = physicalDir; } throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Error_loading_Config_file, _virtualPath, e.Message), e, sourceFile, e.LineNumber); } catch (Exception e) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Error_loading_Config_file, _virtualPath, e.Message), e); } XmlNode node = null; foreach (XmlNode siteMapMode in document.ChildNodes) { if (String.Equals(siteMapMode.Name, "siteMap", StringComparison.Ordinal)) { node = siteMapMode; break; } } if (node == null) throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Top_Element_Must_Be_SiteMap), document); bool enableLocalization = false; HandlerBase.GetAndRemoveBooleanAttribute(node, "enableLocalization", ref enableLocalization); EnableLocalization = enableLocalization; XmlNode topElement = null; foreach (XmlNode subNode in node.ChildNodes) { if (subNode.NodeType == XmlNodeType.Element) { if (!_siteMapNodeName.Equals(subNode.Name)) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Only_SiteMapNode_Allowed), subNode); } if (topElement != null) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Only_One_SiteMapNode_Required_At_Top), subNode); } topElement = subNode; } } if (topElement == null) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Only_One_SiteMapNode_Required_At_Top), node); } Queue queue = new Queue(50); // The parentnode of the top node does not exist, // simply add a null to satisfy the ConvertFromXmlNode condition. queue.Enqueue(null); queue.Enqueue(topElement); _siteMapNode = ConvertFromXmlNode(queue); return _siteMapNode; } } private void CheckSiteMapFileExists() { if (!System.Web.UI.Util.VirtualFileExistsWithAssert(_normalizedVirtualPath)) { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_FileName_does_not_exist, _virtualPath)); } } protected override void Clear() { lock (_lock) { ChildProviderTable.Clear(); _siteMapNode = null; _childProviderList = null; base.Clear(); } } // helper method to convert an XmlNode to a SiteMapNode private SiteMapNode ConvertFromXmlNode(Queue queue) { SiteMapNode rootNode = null; while (true) { if (queue.Count == 0) { return rootNode; } SiteMapNode parentNode = (SiteMapNode)queue.Dequeue(); XmlNode xmlNode = (XmlNode)queue.Dequeue(); SiteMapNode node = null; if (!_siteMapNodeName.Equals(xmlNode.Name)) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_Only_SiteMapNode_Allowed), xmlNode); } string providerName = null; HandlerBase.GetAndRemoveNonEmptyStringAttribute(xmlNode, _providerAttribute, ref providerName); // If the siteMapNode references another provider if (providerName != null) { node = GetNodeFromProvider(providerName); // No other attributes or child nodes are allowed on a provider node. HandlerBase.CheckForUnrecognizedAttributes(xmlNode); HandlerBase.CheckForNonCommentChildNodes(xmlNode); } else { string siteMapFile = null; HandlerBase.GetAndRemoveNonEmptyStringAttribute(xmlNode, _siteMapFileAttribute, ref siteMapFile); if (siteMapFile != null) { node = GetNodeFromSiteMapFile(xmlNode, VirtualPath.Create(siteMapFile)); } else { node = GetNodeFromXmlNode(xmlNode, queue); } } AddNodeInternal(node, parentNode, xmlNode); if (rootNode == null) { rootNode = node; } } } protected virtual void Dispose(bool disposing) { if (_handler != null) { Debug.Assert(_filename != null); HttpRuntime.FileChangesMonitor.StopMonitoringFile(_filename, _handler); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void EnsureChildSiteMapProviderUpToDate(SiteMapProvider childProvider) { SiteMapNode oldNode = (SiteMapNode)ChildProviderTable[childProvider]; SiteMapNode newNode = childProvider.GetRootNodeCore(); if (newNode == null) { throw new ProviderException(SR.GetString(SR.XmlSiteMapProvider_invalid_sitemapnode_returned, childProvider.Name)); } // child providers have been updated. if (!oldNode.Equals(newNode)) { // If the child provider table has been updated, simply return null. // This will happen when the current provider's sitemap file is changed or Clear() is called; if (oldNode == null) { return; } lock (_lock) { oldNode = (SiteMapNode)ChildProviderTable[childProvider]; // If the child provider table has been updated, simply return null. See above. if (oldNode == null) { return; } newNode = childProvider.GetRootNodeCore(); if (newNode == null) { throw new ProviderException(SR.GetString(SR.XmlSiteMapProvider_invalid_sitemapnode_returned, childProvider.Name)); } if (!oldNode.Equals(newNode)) { // If the current provider does not contain any nodes but one child provider // ie. _siteMapNode == oldNode // the oldNode needs to be removed from Url table and the new node will be added. if (_siteMapNode.Equals(oldNode)) { UrlTable.Remove(oldNode.Url); KeyTable.Remove(oldNode.Key); UrlTable.Add(newNode.Url, newNode); KeyTable.Add(newNode.Key, newNode); _siteMapNode = newNode; } // First find the parent node SiteMapNode parent = (SiteMapNode)ParentNodeTable[oldNode]; // parent is null when the provider does not contain any static nodes, ie. // it only contains definition to include one child provider. if (parent != null) { // Update the child nodes table SiteMapNodeCollection list = (SiteMapNodeCollection)ChildNodeCollectionTable[parent]; // Add the newNode to where the oldNode is within parent node's collection. int index = list.IndexOf(oldNode); if (index != -1) { list.Remove(oldNode); list.Insert(index, newNode); } else { list.Add(newNode); } // Update the parent table ParentNodeTable[newNode] = parent; ParentNodeTable.Remove(oldNode); // Update the Url table UrlTable.Remove(oldNode.Url); KeyTable.Remove(oldNode.Key); UrlTable.Add(newNode.Url, newNode); KeyTable.Add(newNode.Key, newNode); } else { // Notify the parent provider to update its child provider collection. XmlSiteMapProvider provider = ParentProvider as XmlSiteMapProvider; if (provider != null) { provider.EnsureChildSiteMapProviderUpToDate(this); } } // Update provider nodes; ChildProviderTable[childProvider] = newNode; _childProviderList = null; } } } } // Returns sitemap node; Search recursively in child providers if not found. public override SiteMapNode FindSiteMapNode(string rawUrl) { SiteMapNode node = base.FindSiteMapNode(rawUrl); if (node == null) { foreach(SiteMapProvider provider in ChildProviderList) { // First make sure the child provider is up-to-date. EnsureChildSiteMapProviderUpToDate(provider); node = provider.FindSiteMapNode(rawUrl); if (node != null) { return node; } } } return node; } // Returns sitemap node; Search recursively in child providers if not found. public override SiteMapNode FindSiteMapNodeFromKey(string key) { SiteMapNode node = base.FindSiteMapNodeFromKey(key); if (node == null) { foreach (SiteMapProvider provider in ChildProviderList) { // First make sure the child provider is up-to-date. EnsureChildSiteMapProviderUpToDate(provider); node = provider.FindSiteMapNodeFromKey(key); if (node != null) { return node; } } } return node; } private XmlDocument GetConfigDocument() { if (_document != null) return _document; if (!_initialized) { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_Not_Initialized)); } // Do the error checking here if (_virtualPath == null) { throw new ArgumentException( SR.GetString(SR.XmlSiteMapProvider_missing_siteMapFile, _siteMapFileAttribute)); } if (!_virtualPath.Extension.Equals(_xmlSiteMapFileExtension, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_Invalid_Extension, _virtualPath)); } _normalizedVirtualPath = _virtualPath.CombineWithAppRoot(); _normalizedVirtualPath.FailIfNotWithinAppRoot(); // Make sure the file exists CheckSiteMapFileExists(); _parentSiteMapFileCollection = new StringCollection(); XmlSiteMapProvider xmlParentProvider = ParentProvider as XmlSiteMapProvider; if (xmlParentProvider != null && xmlParentProvider._parentSiteMapFileCollection != null) { if (xmlParentProvider._parentSiteMapFileCollection.Contains(_normalizedVirtualPath.VirtualPathString)) { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_FileName_already_in_use, _virtualPath)); } // Copy the sitemapfiles in used from parent provider to current provider. foreach (string filename in xmlParentProvider._parentSiteMapFileCollection) { _parentSiteMapFileCollection.Add(filename); } } // Add current sitemap file to the collection _parentSiteMapFileCollection.Add(_normalizedVirtualPath.VirtualPathString); _filename = HostingEnvironment.MapPathInternal(_normalizedVirtualPath); if (!String.IsNullOrEmpty(_filename)) { _handler = new FileChangeEventHandler(this.OnConfigFileChange); HttpRuntime.FileChangesMonitor.StartMonitoringFile(_filename, _handler); ResourceKey = (new FileInfo(_filename)).Name; } _document = new ConfigXmlDocument(); return _document; } private SiteMapNode GetNodeFromProvider(string providerName) { SiteMapProvider provider = GetProviderFromName(providerName); SiteMapNode node = null; // Check infinite recursive sitemap files if (provider is XmlSiteMapProvider) { XmlSiteMapProvider xmlProvider = (XmlSiteMapProvider)provider; StringCollection parentSiteMapFileCollection = new StringCollection(); if (_parentSiteMapFileCollection != null) { foreach (string filename in _parentSiteMapFileCollection) { parentSiteMapFileCollection.Add(filename); } } // Make sure the provider is initialized before adding to the collection. xmlProvider.BuildSiteMap(); parentSiteMapFileCollection.Add(_normalizedVirtualPath.VirtualPathString); if (parentSiteMapFileCollection.Contains(VirtualPath.GetVirtualPathString(xmlProvider._normalizedVirtualPath))) { throw new InvalidOperationException(SR.GetString(SR.XmlSiteMapProvider_FileName_already_in_use, xmlProvider._virtualPath)); } xmlProvider._parentSiteMapFileCollection = parentSiteMapFileCollection; } node = provider.GetRootNodeCore(); if (node == null) { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_invalid_GetRootNodeCore, ((ProviderBase)provider).Name)); } ChildProviderTable.Add(provider, node); _childProviderList = null; provider.ParentProvider = this; return node; } private SiteMapNode GetNodeFromSiteMapFile(XmlNode xmlNode, VirtualPath siteMapFile) { SiteMapNode node = null; // For external sitemap files, its secuity setting is inherited from parent provider bool secuityTrimmingEnabled = SecurityTrimmingEnabled; HandlerBase.GetAndRemoveBooleanAttribute(xmlNode, _securityTrimmingEnabledAttrName, ref secuityTrimmingEnabled); // No other attributes or non-comment nodes are allowed on a siteMapFile node HandlerBase.CheckForUnrecognizedAttributes(xmlNode); HandlerBase.CheckForNonCommentChildNodes(xmlNode); XmlSiteMapProvider childProvider = new XmlSiteMapProvider(); // siteMapFile was relative to the sitemap file where this xmlnode is defined, make it an application path. siteMapFile = _normalizedVirtualPath.Parent.Combine(siteMapFile); childProvider.ParentProvider = this; childProvider.Initialize(siteMapFile, secuityTrimmingEnabled); childProvider.BuildSiteMap(); node = childProvider._siteMapNode; ChildProviderTable.Add(childProvider, node); _childProviderList = null; return node; } private void HandleResourceAttribute(XmlNode xmlNode, ref NameValueCollection collection, string attrName, ref string text, bool allowImplicitResource) { if (String.IsNullOrEmpty(text)) { return; } string resourceKey = null; string temp = text.TrimStart(new char[] { ' ' }); if (temp != null && temp.Length > _resourcePrefixLength) { if (temp.ToLower(CultureInfo.InvariantCulture).StartsWith(_resourcePrefix, StringComparison.Ordinal)) { if (!allowImplicitResource) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_multiple_resource_definition, attrName), xmlNode); } resourceKey = temp.Substring(_resourcePrefixLength + 1); if (resourceKey.Length == 0) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_resourceKey_cannot_be_empty), xmlNode); } // Retrieve className from attribute string className = null; string key = null; int index = resourceKey.IndexOf(_resourceKeySeparator); if (index == -1) { throw new ConfigurationErrorsException( SR.GetString(SR.XmlSiteMapProvider_invalid_resource_key, resourceKey), xmlNode); } className = resourceKey.Substring(0, index); key = resourceKey.Substring(index + 1); // Retrieve resource key and default value from attribute int defaultIndex = key.IndexOf(_resourceKeySeparator); if (defaultIndex != -1) { text = key.Substring(defaultIndex + 1); key = key.Substring(0, defaultIndex); } else { text = null; } if (collection == null) { collection = new NameValueCollection(); } collection.Add(attrName, className.Trim()); collection.Add(attrName, key.Trim()); } } } private SiteMapNode GetNodeFromXmlNode(XmlNode xmlNode, Queue queue) { SiteMapNode node = null; // static nodes string title = null, url = null, description = null, roles = null, resourceKey = null; // Url attribute is NOT required for a xml node. HandlerBase.GetAndRemoveStringAttribute(xmlNode, "url", ref url); HandlerBase.GetAndRemoveStringAttribute(xmlNode, "title", ref title); HandlerBase.GetAndRemoveStringAttribute(xmlNode, "description", ref description); HandlerBase.GetAndRemoveStringAttribute(xmlNode, "roles", ref roles); HandlerBase.GetAndRemoveStringAttribute(xmlNode, "resourceKey", ref resourceKey); // Do not add the resourceKey if the resource is not valid. if (!String.IsNullOrEmpty(resourceKey) && !ValidateResource(ResourceKey, resourceKey + ".title")) { resourceKey = null; } HandlerBase.CheckForbiddenAttribute(xmlNode, _securityTrimmingEnabledAttrName); NameValueCollection resourceKeyCollection = null; bool allowImplicitResourceAttribute = String.IsNullOrEmpty(resourceKey); HandleResourceAttribute(xmlNode, ref resourceKeyCollection, "title", ref title, allowImplicitResourceAttribute); HandleResourceAttribute(xmlNode, ref resourceKeyCollection, "description", ref description, allowImplicitResourceAttribute); ArrayList roleList = new ArrayList(); if (roles != null) { int foundIndex = roles.IndexOf('?'); if (foundIndex != -1) { throw new ConfigurationErrorsException( SR.GetString(SR.Auth_rule_names_cant_contain_char, roles[foundIndex].ToString(CultureInfo.InvariantCulture)), xmlNode); } foreach (string role in roles.Split(_seperators)) { string trimmedRole = role.Trim(); if (trimmedRole.Length > 0) { roleList.Add(trimmedRole); } } } roleList = ArrayList.ReadOnly(roleList); String key = null; // Make urls absolute. if (!String.IsNullOrEmpty(url)) { // URL needs to be trimmed. VSWhidbey 411041 url = url.Trim(); if (!UrlPath.IsAbsolutePhysicalPath(url)) { if (UrlPath.IsRelativeUrl(url)) { url = UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, url); } } // VSWhidbey 418056, Reject any suspicious or mal-formed Urls. string decodedUrl = HttpUtility.UrlDecode(url); if (!String.Equals(url, decodedUrl, StringComparison.Ordinal)) { throw new ConfigurationErrorsException( SR.GetString(SR.Property_Had_Malformed_Url, "url", url), xmlNode); } key = url.ToLowerInvariant(); } else { key = Guid.NewGuid().ToString(); } // attribute collection does not contain pre-defined properties like title, url, etc. ReadOnlyNameValueCollection attributeCollection = new ReadOnlyNameValueCollection(); attributeCollection.SetReadOnly(false); foreach (XmlAttribute attribute in xmlNode.Attributes) { string value = attribute.Value; HandleResourceAttribute(xmlNode, ref resourceKeyCollection, attribute.Name, ref value, allowImplicitResourceAttribute); attributeCollection[attribute.Name] = value; } attributeCollection.SetReadOnly(true); node = new SiteMapNode(this, key, url, title, description, roleList, attributeCollection, resourceKeyCollection, resourceKey); node.ReadOnly = true; foreach (XmlNode subNode in xmlNode.ChildNodes) { if (subNode.NodeType != XmlNodeType.Element) continue; queue.Enqueue(node); queue.Enqueue(subNode); } return node; } private SiteMapProvider GetProviderFromName(string providerName) { Debug.Assert(providerName != null); SiteMapProvider provider = SiteMap.Providers[providerName]; if (provider == null) { throw new ProviderException(SR.GetString(SR.Provider_Not_Found, providerName)); } return provider; } protected internal override SiteMapNode GetRootNodeCore() { BuildSiteMap(); return _siteMapNode; } public override void Initialize(string name, NameValueCollection attributes) { if (_initialized) { throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_Cannot_Be_Inited_Twice)); } if (attributes != null) { if (string.IsNullOrEmpty(attributes["description"])) { attributes.Remove("description"); attributes.Add("description", SR.GetString(SR.XmlSiteMapProvider_Description)); } string siteMapFile = null; ProviderUtil.GetAndRemoveStringAttribute(attributes, _siteMapFileAttribute, name, ref siteMapFile); _virtualPath = VirtualPath.CreateAllowNull(siteMapFile); } base.Initialize(name, attributes); if (attributes != null) { ProviderUtil.CheckUnrecognizedAttributes(attributes, name); } _initialized = true; } private void Initialize(VirtualPath virtualPath, bool secuityTrimmingEnabled) { NameValueCollection coll = new NameValueCollection(); coll.Add(_siteMapFileAttribute, virtualPath.VirtualPathString); coll.Add(_securityTrimmingEnabledAttrName, System.Web.UI.Util.GetStringFromBool(secuityTrimmingEnabled)); // Use the siteMapFile virtual path as the provider name Initialize(virtualPath.VirtualPathString, coll); } private void OnConfigFileChange(Object sender, FileChangeEvent e) { // Notifiy the parent for the change. XmlSiteMapProvider parentProvider = ParentProvider as XmlSiteMapProvider; if (parentProvider != null) { parentProvider.OnConfigFileChange(sender, e); } Clear(); } protected internal override void RemoveNode(SiteMapNode node) { if (node == null) { throw new ArgumentNullException("node"); } SiteMapProvider ownerProvider = node.Provider; if (ownerProvider != this) { // Only nodes defined in this provider tree can be removed. SiteMapProvider parentProvider = ownerProvider.ParentProvider; while (parentProvider != this) { if (parentProvider == null) { // Cannot remove nodes defined in other providers throw new InvalidOperationException( SR.GetString(SR.XmlSiteMapProvider_cannot_remove_node, node.ToString(), this.Name, ownerProvider.Name)); } parentProvider = parentProvider.ParentProvider; } } if (node.Equals(ownerProvider.GetRootNodeCore())) { throw new InvalidOperationException(SR.GetString(SR.SiteMapProvider_cannot_remove_root_node)); } if (ownerProvider != this) { // Remove node from the owner provider. ownerProvider.RemoveNode(node); } base.RemoveNode(node); } protected virtual void RemoveProvider(string providerName) { if (providerName == null) { throw new ArgumentNullException("providerName"); } lock (_lock) { SiteMapProvider provider = GetProviderFromName(providerName); SiteMapNode rootNode = (SiteMapNode)ChildProviderTable[provider]; if (rootNode == null) { throw new InvalidOperationException(SR.GetString(SR.XmlSiteMapProvider_cannot_find_provider, provider.Name, this.Name)); } provider.ParentProvider = null; ChildProviderTable.Remove(provider); _childProviderList = null; base.RemoveNode(rootNode); } } // VSWhidbey: 493981 Helper method to check if the valid resource type exists. // Note that this only returns false if the classKey cannot be found, regardless of resourceKey. private bool ValidateResource(string classKey, string resourceKey) { try { HttpContext.GetGlobalResourceObject(classKey, resourceKey); } catch (MissingManifestResourceException) { return false; } return true; } // Dev10# 923217 - SiteMapProvider URL Table Invalid Using Cookieless // Don't keep the modifier inside the links table. Apply the modifier as approriate on demand private static SiteMapNode ApplyModifierIfExists(SiteMapNode node) { HttpContext context = HttpContext.Current; // Do nothing if the modifier doesn't apply if (node == null || context == null || !context.Response.UsePathModifier) { return node; } // Set Url with the modifier applied SiteMapNode resultNode = node.Clone(); resultNode.Url = context.Response.ApplyAppPathModifier(node.Url); return resultNode; } private class ReadOnlyNameValueCollection : NameValueCollection { public ReadOnlyNameValueCollection() { IsReadOnly = true; } internal void SetReadOnly(bool isReadonly) { IsReadOnly = isReadonly; } } } }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using GameKit.Log; using GameKit.Publish; using GameKit.Resource; using Medusa.CoreProto; using Microsoft.Win32; using ProtoBuf; namespace GameKit.Analyzer { public class StringTableConfigAnalyzer : IAnalyzer { public const string TableName = "StringTable"; //name,order-value public static Dictionary<PublishInfo, Dictionary<string, Dictionary<uint, KeyValuePair<string,bool>>>> StringTables = new Dictionary<PublishInfo, Dictionary<string, Dictionary<uint, KeyValuePair<string, bool>>>>(); public static Dictionary<string,bool> mNameGroups=new Dictionary<string, bool>(); public Dictionary<string, Dictionary<uint, KeyValuePair<string, bool>>> GetOrCreateStringTable(PublishInfo packageInfo) { if (StringTables.ContainsKey(packageInfo)) { return StringTables[packageInfo]; } var result = new Dictionary<string, Dictionary<uint, KeyValuePair<string, bool>>>(); StringTables.Add(packageInfo, result); return result; } public void PrevProcess() { } public void PostCheck() { foreach (var stringTable in StringTables) { if (stringTable.Key.IsPublish(PublishTarget.Current)) { foreach (var dict in stringTable.Value) { if (mNameGroups.ContainsKey(dict.Key)) { foreach (var strPair in dict.Value) { if (!strPair.Value.Value) { Logger.LogAllLine("StringTable {0}:{1}-{2} Not used!", stringTable.Key, dict.Key, strPair.Key); } } } } } } } public void Analyze() { StringTables.Clear(); mNameGroups.Clear(); Logger.LogAllLine("Analyze StringTable================>"); var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Jet\4.0\Engines\Excel", true); reg.SetValue("TypeGuessRows", 0); var validNames = Enum.GetNames(typeof(PublishLanguages)); var tabelNames = ExcelHelper.GetExcelTableNames(PathManager.InputConfigStringTablePath.FullName); foreach (string tableName in tabelNames) { string pureTableName = tableName.Replace("$", String.Empty).Replace("'", String.Empty).Replace(TableName, String.Empty); bool isValidTable = validNames.Any(pureTableName.Contains); if (!isValidTable || !tableName.Contains(TableName)) { continue; } var table = ExcelHelper.LoadDataFromExcel(PathManager.InputConfigStringTablePath.FullName, tableName); string resourceName = tableName.Replace("$", String.Empty); var packageInfo = PublishInfo.GetPublishInfo(resourceName); var stringTable = GetOrCreateStringTable(packageInfo); foreach (DataRow row in table.Rows) { bool isValid = true; bool isAllNull = true; for (int i = 0; i < row.ItemArray.Length; i++) { if (row.IsNull(i)) { isValid = false; } else { isAllNull = false; } } if (isValid) { try { string name = Convert.ToString(row["name"]); uint order = Convert.ToUInt32(row["order"]); string str = Convert.ToString(row["value"]); string resultStr = ExcelHelper.ConvertToUTF8(str); Add(stringTable, name, order, resultStr); } catch (Exception ex) { Logger.LogErrorLine(ex.Message); ExcelHelper.PrintRow(row); } } else if (!isAllNull) { Logger.LogErrorLine("Invalid string table line:"); ExcelHelper.PrintRow(row); } } //print var stringTableResult = Parse(stringTable); if ((PublishTarget.Current.PublishInfo.Language & packageInfo.Language) == packageInfo.Language) { string tempPath = PathManager.OutputConfigPath + "/" + TableName + pureTableName + ".bin"; using (var file = File.Open(tempPath, FileMode.Create, FileAccess.ReadWrite)) { Serializer.Serialize(file, stringTableResult); Logger.LogAllLine("Generate:{0}", tempPath); } var resourceFile = new FileListFile(new FileInfo(tempPath), true, true); FileSystemGenerator.AddFileAndTag(resourceFile); } else { Logger.LogAllLine("Ignore:\t{0}", pureTableName); } } } public void Add(Dictionary<string, Dictionary<uint, KeyValuePair<string, bool>>> stringTable, string name, uint order, string str) { Dictionary<uint, KeyValuePair<string, bool>> orderItems = null; if (stringTable.ContainsKey(name)) { orderItems = stringTable[name]; } else { orderItems = new Dictionary<uint, KeyValuePair<string, bool>>(); stringTable.Add(name, orderItems); } if (orderItems.ContainsKey(order)) { Logger.LogAllLine("Duplicate String order:\t[{0}:{1}:{2}] VS [{3}:{4}:{5}]", name, order, str, name, order, orderItems[order]); } else { orderItems.Add(order, new KeyValuePair<string, bool>(str,false)); } } public StringTable Parse(Dictionary<string, Dictionary<uint, KeyValuePair<string, bool>>> stringMap) { var stringTable = new StringTable(); foreach (var nameItemMap in stringMap) { var nameItem = new StringNameItem { name = nameItemMap.Key }; //Logger.LogInfoLine("\t{0}:", nameItemMap.Key); foreach (var orderItemPair in nameItemMap.Value) { var orderItem = new StringOrderItem { order = orderItemPair.Key, value = orderItemPair.Value.Key }; nameItem.orderItems.Add(orderItem); //Logger.LogInfoLine("\t\t{0}:\t{1}", orderItem.order, orderItem.value); } stringTable.nameItems.Add(nameItem); } return stringTable; } public static void AssertHasName(string name, uint order) { if (!mNameGroups.ContainsKey(name)) { mNameGroups.Add(name,false); } foreach (var stringTable in StringTables) { if (stringTable.Key.IsPublish(PublishTarget.Current)) { Dictionary<uint, KeyValuePair<string, bool>> outDictionary; if (stringTable.Value.TryGetValue(name, out outDictionary)) { KeyValuePair<string, bool> outStr; if (outDictionary.TryGetValue(order, out outStr)) { if (!string.IsNullOrEmpty(outStr.Key)) { outDictionary[order]=new KeyValuePair<string, bool>(outStr.Key,true); continue; } } } Logger.LogAllLine("StringTable {0}:Cannot find {1}-{2}", stringTable.Key, name, order); } } } } }
using System.Collections.Generic; using System.Linq; using GraphQL.Validation.Errors; using GraphQL.Validation.Rules; using Xunit; namespace GraphQL.Tests.Validation { public class FieldsOnCorrectTypeTests : ValidationTestBase<FieldsOnCorrectType, ValidationSchema> { [Fact] public void object_field_selection() { ShouldPassRule(@" fragment objectFieldSelection on Dog { __typename name } "); } [Fact] public void aliased_object_field_selection() { ShouldPassRule(@" fragment aliasedObjectFieldSelection on Dog { tn : __typename otherName : name } "); } [Fact] public void interface_field_selection() { ShouldPassRule(@" fragment interfaceFieldSelection on Pet { __typename name } "); } [Fact] public void aliased_interface_field_selection() { ShouldPassRule(@" fragment interfaceFieldSelection on Pet { otherName : name } "); } [Fact] public void lying_alias_selection() { ShouldPassRule(@" fragment lyingAliasSelection on Dog { name : nickname } "); } [Fact] public void ignores_fields_on_unknown_type() { ShouldPassRule(@" fragment unknownSelection on UnknownType { unknownField } "); } [Fact] public void reports_errors_when_type_is_known_again() { ShouldFailRule(_ => { _.Query = @" fragment typeKnownAgain on Pet { unknown_pet_field { ... on Cat { unknown_cat_field } } } "; undefinedField(_, "unknown_pet_field", "Pet", line: 3, column: 21); undefinedField(_, "unknown_cat_field", "Cat", line: 5, column: 25); }); } [Fact] public void field_not_defined_on_fragment() { ShouldFailRule(_ => { _.Query = @" fragment fieldNotDefined on Dog { meowVolume } "; undefinedField(_, "meowVolume", "Dog", suggestedFields: new[] { "barkVolume" }, line: 3, column: 21); }); } [Fact] public void ignores_deeply_unknown_field() { ShouldFailRule(_ => { _.Query = @" fragment deepFieldNotDefined on Dog { unknown_field { deeper_unknown_field } } "; undefinedField(_, "unknown_field", "Dog", line: 3, column: 21); }); } [Fact] public void subfield_not_defined() { ShouldFailRule(_ => { _.Query = @" fragment subFieldNotDefined on Human { pets { unknown_field } } "; undefinedField(_, "unknown_field", "Pet", line: 4, column: 23); }); } [Fact] public void field_not_defined_on_inline_fragment() { ShouldFailRule(_ => { _.Query = @" fragment fieldNotDefined on Pet { ... on Dog { meowVolume } } "; undefinedField(_, "meowVolume", "Dog", suggestedFields: new[] { "barkVolume" }, line: 4, column: 23); }); } [Fact] public void aliased_field_target_not_defined() { ShouldFailRule(_ => { _.Query = @" fragment aliasedFieldTargetNotDefined on Dog { volume : mooVolume } "; undefinedField(_, "mooVolume", "Dog", suggestedFields: new[] { "barkVolume" }, line: 3, column: 21); }); } [Fact] public void aliased_lying_field_target_not_defined() { ShouldFailRule(_ => { _.Query = @" fragment aliasedLyingFieldTargetNotDefined on Dog { barkVolume : kawVolume } "; undefinedField(_, "kawVolume", "Dog", suggestedFields: new[] { "barkVolume" }, line: 3, column: 21); }); } [Fact] public void not_defined_on_interface() { ShouldFailRule(_ => { _.Query = @" fragment notDefinedOnInterface on Pet { tailLength } "; undefinedField(_, "tailLength", "Pet", line: 3, column: 21); }); } [Fact] public void defined_on_implementors_but_not_on_interface() { ShouldFailRule(_ => { _.Query = @" fragment definedOnImplementorsButNotInterface on Pet { nickname } "; undefinedField(_, "nickname", "Pet", suggestedTypes: new[] { "Dog", "Cat" }, line: 3, column: 21); }); } [Fact] public void meta_field_selection_on_union() { ShouldPassRule(@" fragment directFieldSelectionOnUnion on CatOrDog { __typename } "); } [Fact] public void direct_field_selection_on_union() { ShouldFailRule(_ => { _.Query = @" fragment directFieldSelectionOnUnion on CatOrDog { directField } "; undefinedField(_, "directField", "CatOrDog", line: 3, column: 21); }); } [Fact] public void defined_on_implementors_queried_on_union() { ShouldFailRule(_ => { _.Query = @" fragment definedOnImplementorsQueriedOnUnion on CatOrDog { name } "; undefinedField(_, "name", "CatOrDog", suggestedTypes: new[] { "Canine", "Being", "Pet", "Cat", "Dog" }, line: 3, column: 21); }); } [Fact] public void valid_field_in_inline_fragment() { ShouldPassRule(@" fragment objectFieldSelection on Pet { ... on Dog { name } ... { name } } "); } private void undefinedField( ValidationTestConfig _, string field, string type, IEnumerable<string> suggestedTypes = null, IEnumerable<string> suggestedFields = null, int line = 0, int column = 0) { suggestedTypes ??= Enumerable.Empty<string>(); suggestedFields ??= Enumerable.Empty<string>(); _.Error(FieldsOnCorrectTypeError.UndefinedFieldMessage(field, type, suggestedTypes, suggestedFields), line, column); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { /// <summary> /// Base class for all Roslyn light bulb menu items. /// </summary> internal partial class SuggestedAction : ForegroundThreadAffinitizedObject, ISuggestedAction, IEquatable<ISuggestedAction> { protected readonly Workspace Workspace; protected readonly ITextBuffer SubjectBuffer; protected readonly ICodeActionEditHandlerService EditHandler; protected readonly object Provider; protected readonly CodeAction CodeAction; protected SuggestedAction( Workspace workspace, ITextBuffer subjectBuffer, ICodeActionEditHandlerService editHandler, CodeAction codeAction, object provider) { Contract.ThrowIfTrue(provider == null); this.Workspace = workspace; this.SubjectBuffer = subjectBuffer; this.CodeAction = codeAction; this.EditHandler = editHandler; this.Provider = provider; } public bool TryGetTelemetryId(out Guid telemetryId) { // TODO: this is temporary. Diagnostic team needs to figure out how to provide unique id per a fix. // for now, we will use type of CodeAction, but there are some predefined code actions that are used by multiple fixes // and this will not distinguish those // AssemblyQualifiedName will change across version numbers, FullName won't var type = CodeAction.GetType(); type = type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type; telemetryId = new Guid(type.FullName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); return true; } // NOTE: We want to avoid computing the operations on the UI thread. So we use Task.Run() to do this work on the background thread. protected Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync(CancellationToken cancellationToken) { return Task.Run( async () => await CodeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false), cancellationToken); } protected Task<IEnumerable<CodeActionOperation>> GetOperationsAsync(CodeActionWithOptions actionWithOptions, object options, CancellationToken cancellationToken) { return Task.Run( async () => await actionWithOptions.GetOperationsAsync(options, cancellationToken).ConfigureAwait(false), cancellationToken); } protected Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken) { return Task.Run( async () => await CodeAction.GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(false), cancellationToken); } public virtual void Invoke(CancellationToken cancellationToken) { var snapshot = this.SubjectBuffer.CurrentSnapshot; using (new CaretPositionRestorer(this.SubjectBuffer, this.EditHandler.AssociatedViewService)) { var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); extensionManager.PerformAction(Provider, () => { IEnumerable<CodeActionOperation> operations = null; // NOTE: As mentoned above, we want to avoid computing the operations on the UI thread. // However, for CodeActionWithOptions, GetOptions() might involve spinning up a dialog // to compute the options and must be done on the UI thread. var actionWithOptions = this.CodeAction as CodeActionWithOptions; if (actionWithOptions != null) { var options = actionWithOptions.GetOptions(cancellationToken); if (options != null) { operations = GetOperationsAsync(actionWithOptions, options, cancellationToken).WaitAndGetResult(cancellationToken); } } else { operations = GetOperationsAsync(cancellationToken).WaitAndGetResult(cancellationToken); } if (operations != null) { var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); EditHandler.Apply(Workspace, document, operations, CodeAction.Title, cancellationToken); } }); } } public string DisplayText { get { // Underscores will become an accelerator in the VS smart tag. So we double all // underscores so they actually get represented as an underscore in the UI. var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); var text = extensionManager.PerformFunction(Provider, () => CodeAction.Title, defaultValue: string.Empty); return text.Replace("_", "__"); } } protected async Task<SolutionPreviewResult> GetPreviewResultAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // We will always invoke this from the UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. var operations = await GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(true); return EditHandler.GetPreviews(Workspace, operations, cancellationToken); } public virtual bool HasPreview { get { // HasPreview is called synchronously on the UI thread. In order to avoid blocking the UI thread, // we need to provide a 'quick' answer here as opposed to the 'right' answer. Providing the 'right' // answer is expensive (because we will need to call CodeAction.GetPreivewOperationsAsync() for this // and this will involve computing the changed solution for the ApplyChangesOperation for the fix / // refactoring). So we always return 'true' here (so that platform will call GetActionSetsAsync() // below). Platform guarantees that nothing bad will happen if we return 'true' here and later return // 'null' / empty collection from within GetPreviewAsync(). return true; } } public virtual async Task<object> GetPreviewAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Light bulb will always invoke this function on the UI thread. AssertIsForeground(); var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); var previewContent = await extensionManager.PerformFunctionAsync(Provider, async () => { // We need to stay on UI thread after GetPreviewResultAsync() so that TakeNextPreviewAsync() // below can execute on UI thread. We use ConfigureAwait(true) to stay on the UI thread. var previewResult = await GetPreviewResultAsync(cancellationToken).ConfigureAwait(true); if (previewResult == null) { return null; } else { var preferredDocumentId = Workspace.GetDocumentIdInCurrentContext(SubjectBuffer.AsTextContainer()); var preferredProjectid = preferredDocumentId == null ? null : preferredDocumentId.ProjectId; // TakeNextPreviewAsync() needs to run on UI thread. AssertIsForeground(); return await previewResult.TakeNextPreviewAsync(preferredDocumentId, preferredProjectid, cancellationToken).ConfigureAwait(true); } // GetPreviewPane() below needs to run on UI thread. We use ConfigureAwait(true) to stay on the UI thread. }, defaultValue: null).ConfigureAwait(true); var previewPaneService = Workspace.Services.GetService<IPreviewPaneService>(); if (previewPaneService == null) { return null; } cancellationToken.ThrowIfCancellationRequested(); // GetPreviewPane() needs to run on the UI thread. AssertIsForeground(); return previewPaneService.GetPreviewPane(GetDiagnostic(), previewContent); } protected virtual Diagnostic GetDiagnostic() { return null; } #region not supported void IDisposable.Dispose() { // do nothing } public virtual bool HasActionSets { get { return false; } } public virtual Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken) { return SpecializedTasks.Default<IEnumerable<SuggestedActionSet>>(); } string ISuggestedAction.IconAutomationText { get { // same as display text return DisplayText; } } ImageMoniker ISuggestedAction.IconMoniker { get { // no icon support return default(ImageMoniker); } } string ISuggestedAction.InputGestureText { get { // no shortcut support return null; } } #endregion #region IEquatable<ISuggestedAction> public bool Equals(ISuggestedAction other) { return Equals(other as SuggestedAction); } public override bool Equals(object obj) { return Equals(obj as SuggestedAction); } public bool Equals(SuggestedAction otherSuggestedAction) { if (otherSuggestedAction == null) { return false; } if (ReferenceEquals(this, otherSuggestedAction)) { return true; } if (!ReferenceEquals(Provider, otherSuggestedAction.Provider)) { return false; } var otherCodeAction = otherSuggestedAction.CodeAction; if (CodeAction.EquivalenceKey == null || otherCodeAction.EquivalenceKey == null) { return false; } return CodeAction.EquivalenceKey == otherCodeAction.EquivalenceKey; } public override int GetHashCode() { if (CodeAction.EquivalenceKey == null) { return base.GetHashCode(); } return Hash.Combine(Provider.GetHashCode(), CodeAction.EquivalenceKey.GetHashCode()); } #endregion } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.Threading; using MindTouch.Extensions.Time; using log4net; using MindTouch.Collections; using MindTouch.Tasking; namespace MindTouch.Threading { /// <summary> /// ElasticThreadPool provides a thread pool that can have a variable number of threads going from a minimum number of reserved threads /// to a maximum number of parallel threads. /// </summary> /// <remarks> /// The threads are obtained from the DispatchThreadScheduler and shared across all other clients of the DispatchThreadScheduler. /// Obtained threads are released automatically if the thread pool is idle for long enough. Reserved threads are never released. /// </remarks> public class ElasticThreadPool : IDispatchHost, IDispatchQueue, IDisposable { //--- Constants --- /// <summary> /// Maximum number of threads that can be reserved by a single instance. /// </summary> public const int MAX_RESERVED_THREADS = 1000; //--- Class Fields --- private static int _instanceCounter; private static readonly ILog _log = LogUtils.CreateLog(); //--- Fields --- private readonly object _syncRoot = new object(); private readonly int _id = Interlocked.Increment(ref _instanceCounter); private readonly IThreadsafeQueue<Action> _inbox = new LockFreeQueue<Action>(); private readonly IThreadsafeStack<KeyValuePair<DispatchThread, Result<DispatchWorkItem>>> _reservedThreads = new LockFreeStack<KeyValuePair<DispatchThread, Result<DispatchWorkItem>>>(); private readonly int _minReservedThreads; private readonly int _maxParallelThreads; private int _threadCount; private int _threadVelocity; private DispatchThread[] _activeThreads; private bool _disposed; //--- Constructors --- /// <summary> /// Creates a new ElasticThreadPool instance. /// </summary> /// <param name="minReservedThreads">Minium number of threads to reserve for the thread pool.</param> /// <param name="maxParallelThreads">Maximum number of parallel threads used by the thread pool.</param> /// <exception cref="InsufficientResourcesException">The ElasticThreadPool instance was unable to obtain the minimum reserved threads.</exception> public ElasticThreadPool(int minReservedThreads, int maxParallelThreads) { _minReservedThreads = Math.Max(0, Math.Min(minReservedThreads, MAX_RESERVED_THREADS)); _maxParallelThreads = Math.Max(Math.Max(1, minReservedThreads), Math.Min(maxParallelThreads, int.MaxValue)); // initialize reserved threads _activeThreads = new DispatchThread[Math.Min(_maxParallelThreads, Math.Max(_minReservedThreads, Math.Min(16, _maxParallelThreads)))]; if(_minReservedThreads > 0) { DispatchThreadScheduler.RequestThread(_minReservedThreads, AddThread); } DispatchThreadScheduler.RegisterHost(this); _log.DebugFormat("Create @{0}", this); } //--- Properties --- /// <summary> /// Number of minimum reserved threads. /// </summary> public int MinReservedThreads { get { return _disposed ? 0 : _minReservedThreads; } } /// <summary> /// Number of maxium parallel threads. /// </summary> public int MaxParallelThreads { get { return _maxParallelThreads; } } /// <summary> /// Number of threads currently used. /// </summary> public int ThreadCount { get { return _threadCount; } } /// <summary> /// Number of items pending for execution. /// </summary> public int WorkItemCount { get { int result = _inbox.Count; DispatchThread[] threads = _activeThreads; foreach(DispatchThread thread in threads) { if(thread != null) { result += thread.PendingWorkItemCount; } } return result; } } //--- Methods --- /// <summary> /// Adds an item to the thread pool. /// </summary> /// <param name="callback">Item to add to the thread pool.</param> public void QueueWorkItem(Action callback) { if(!TryQueueWorkItem(callback)) { throw new NotSupportedException("TryQueueWorkItem failed"); } } /// <summary> /// Adds an item to the thread pool. /// </summary> /// <param name="callback">Item to add to the thread pool.</param> /// <returns>Always returns true.</returns> public bool TryQueueWorkItem(Action callback) { if(_disposed) { throw new ObjectDisposedException("ElasticThreadPool has already been disposed"); } // check if we can enqueue work-item into current dispatch thread if(DispatchThread.TryQueueWorkItem(this, callback)) { return true; } // check if there are available threads to which the work-item can be given to KeyValuePair<DispatchThread, Result<DispatchWorkItem>> entry; if(_reservedThreads.TryPop(out entry)) { lock(_syncRoot) { RegisterThread("new item", entry.Key); } // found an available thread, let's resume it with the work-item entry.Value.Return(new DispatchWorkItem(callback, this)); return true; } // no threads available, keep work-item for later if(!_inbox.TryEnqueue(callback)) { return false; } // check if we need to request a thread to kick things off if(ThreadCount == 0) { ((IDispatchHost)this).IncreaseThreadCount("request first thread"); } return true; } /// <summary> /// Shutdown the ElasticThreadPool instance. This method blocks until all pending items have finished processing. /// </summary> public void Dispose() { if(!_disposed) { _disposed = true; _log.DebugFormat("Dispose @{0}", this); // TODO (steveb): make dispose more reliable // 1) we can't wait indefinitively! // 2) we should progressively sleep longer and longer to avoid unnecessary overhead // 3) this pattern feels useful enough to be captured into a helper method // wait until all threads have been decommissioned while(ThreadCount > 0) { AsyncUtil.Sleep(100.Milliseconds()); } // discard all reserved threads KeyValuePair<DispatchThread, Result<DispatchWorkItem>> reserved; while(_reservedThreads.TryPop(out reserved)) { DispatchThreadScheduler.ReleaseThread(reserved.Key, reserved.Value); } DispatchThreadScheduler.UnregisterHost(this); } } /// <summary> /// Convert the dispatch queue into a string. /// </summary> /// <returns>String.</returns> public override string ToString() { return string.Format("ElasticThreadPool @{0} (current: {1}, reserve: {5}, velocity: {2}, min: {3}, max: {4}, items: {6})", _id, _threadCount, _threadVelocity, _minReservedThreads, _maxParallelThreads, _reservedThreads.Count, WorkItemCount); } private void AddThread(KeyValuePair<DispatchThread, Result<DispatchWorkItem>> keyvalue) { DispatchThread thread = keyvalue.Key; Result<DispatchWorkItem> result = keyvalue.Value; if(_threadVelocity >= 0) { lock(_syncRoot) { _threadVelocity = 0; // check if an item is available for dispatch Action callback; if(TryRequestItem(null, out callback)) { RegisterThread("new thread", thread); // dispatch work-item result.Return(new DispatchWorkItem(callback, this)); return; } } } // we have no need for this thread RemoveThread("insufficient work for new thread", thread, result); } private void RemoveThread(string reason, DispatchThread thread, Result<DispatchWorkItem> result) { if(thread == null) { throw new ArgumentNullException("thread"); } if(result == null) { throw new ArgumentNullException("result"); } if(thread.PendingWorkItemCount != 0) { throw new ArgumentException(string.Format("thread #{1} still has work-items in queue (items: {0})", thread.PendingWorkItemCount, thread.Id), "thread"); } // remove thread from list of allocated threads lock(_syncRoot) { _threadVelocity = 0; UnregisterThread(reason, thread); } // check if we can put thread into the reserved list if(_reservedThreads.Count < MinReservedThreads) { if(!_reservedThreads.TryPush(new KeyValuePair<DispatchThread, Result<DispatchWorkItem>>(thread, result))) { throw new NotSupportedException("TryPush failed"); } } else { // return thread to resource manager DispatchThreadScheduler.ReleaseThread(thread, result); } } private bool TryRequestItem(DispatchThread thread, out Action callback) { // check if we can find a work-item in the shared queue if(_inbox.TryDequeue(out callback)) { return true; } // try to steal a work-item from another thread; take a snapshot of all allocated threads (needed in case the array is copied for resizing) DispatchThread[] threads = _activeThreads; foreach(DispatchThread entry in threads) { // check if we can steal a work-item from this thread if((entry != null) && !ReferenceEquals(entry, thread) && entry.TryStealWorkItem(out callback)) { return true; } } // check again if we can find a work-item in the shared queue since trying to steal may have overlapped with the arrival of a new item if(_inbox.TryDequeue(out callback)) { return true; } return false; } private void RegisterThread(string reason, DispatchThread thread) { ++_threadCount; thread.Host = this; // find an empty slot in the array of all threads int index; for(index = 0; index < _activeThreads.Length; ++index) { // check if we found an empty slot if(_activeThreads[index] == null) { // assign it to the found slot and stop iterating _activeThreads[index] = thread; break; } } // check if we need to grow the array if(index == _activeThreads.Length) { // make room to add a new thread by doubling the array size and copying over the existing entries DispatchThread[] newArray = new DispatchThread[2 * _activeThreads.Length]; Array.Copy(_activeThreads, newArray, _activeThreads.Length); // assign new thread newArray[index] = thread; // update instance field _activeThreads = newArray; } #if EXTRA_DEBUG _log.DebugFormat("AddThread: {1} - {0}", this, reason); #endif } private void UnregisterThread(string reason, DispatchThread thread) { thread.Host = null; // find thread and remove it for(int i = 0; i < _activeThreads.Length; ++i) { if(ReferenceEquals(_activeThreads[i], thread)) { --_threadCount; _activeThreads[i] = null; #if EXTRA_DEBUG _log.DebugFormat("RemoveThread: {1} - {0}", this, reason); #endif break; } } } //--- IDispatchHost Members --- long IDispatchHost.PendingWorkItemCount { get { return WorkItemCount; } } int IDispatchHost.MinThreadCount { get { return MinReservedThreads; } } int IDispatchHost.MaxThreadCount { get { return _maxParallelThreads; } } void IDispatchHost.RequestWorkItem(DispatchThread thread, Result<DispatchWorkItem> result) { if(thread == null) { throw new ArgumentNullException("thread"); } if(thread.PendingWorkItemCount > 0) { throw new ArgumentException(string.Format("thread #{1} still has work-items in queue (items: {0})", thread.PendingWorkItemCount, thread.Id), "thread"); } if(!ReferenceEquals(thread.Host, this)) { throw new InvalidOperationException(string.Format("thread is allocated to another queue: received {0}, expected: {1}", thread.Host, this)); } if(result == null) { throw new ArgumentNullException("result"); } Action callback; // check if we need to decommission threads without causing starvation if(_threadVelocity < 0) { RemoveThread("system saturation", thread, result); return; } // check if we found a work-item if(TryRequestItem(thread, out callback)) { // dispatch work-item result.Return(new DispatchWorkItem(callback, this)); } else { // relinquich thread; it's not required anymore RemoveThread("insufficient work", thread, result); } } void IDispatchHost.IncreaseThreadCount(string reason) { // check if thread pool is already awaiting another thread if(_threadVelocity > 0) { return; } lock(_syncRoot) { _threadVelocity = 1; // check if thread pool has enough threads if(_threadCount >= _maxParallelThreads) { _threadVelocity = 0; return; } #if EXTRA_DEBUG _log.DebugFormat("IncreaseThreadCount: {1} - {0}", this, reason); #endif } // check if there are threads in the reserve KeyValuePair<DispatchThread, Result<DispatchWorkItem>> reservedThread; if(_reservedThreads.TryPop(out reservedThread)) { AddThread(reservedThread); } else { DispatchThreadScheduler.RequestThread(0, AddThread); } } void IDispatchHost.MaintainThreadCount(string reason) { // check if thread pool is already trying to steady if(_threadVelocity == 0) { return; } lock(_syncRoot) { _threadVelocity = 0; #if EXTRA_DEBUG _log.DebugFormat("MaintainThreadCount: {1} - {0}", this, reason); #endif } } void IDispatchHost.DecreaseThreadCount(string reason) { // check if thread pool is already trying to discard thread if(_threadVelocity < 0) { return; } lock(_syncRoot) { _threadVelocity = -1; #if EXTRA_DEBUG _log.DebugFormat("DecreaseThreadCount: {1} - {0}", this, reason); #endif } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq.Expressions; using System.Reflection; namespace System.Linq { internal class EnumerableRewriter : OldExpressionVisitor { internal EnumerableRewriter() { } internal override Expression VisitMethodCall(MethodCallExpression m) { Expression obj = this.Visit(m.Object); ReadOnlyCollection<Expression> args = this.VisitExpressionList(m.Arguments); // check for args changed if (obj != m.Object || args != m.Arguments) { Type[] typeArgs = (m.Method.IsGenericMethod) ? m.Method.GetGenericArguments() : null; if ((m.Method.IsStatic || m.Method.DeclaringType.IsAssignableFrom(obj.Type)) && ArgsMatch(m.Method, args, typeArgs)) { // current method is still valid return Expression.Call(obj, m.Method, args); } else if (m.Method.DeclaringType == typeof(Queryable)) { // convert Queryable method to Enumerable method MethodInfo seqMethod = FindEnumerableMethod(m.Method.Name, args, typeArgs); args = this.FixupQuotedArgs(seqMethod, args); return Expression.Call(obj, seqMethod, args); } else { // rebind to new method MethodInfo method = FindMethod(m.Method.DeclaringType, m.Method.Name, args, typeArgs); args = this.FixupQuotedArgs(method, args); return Expression.Call(obj, method, args); } } return m; } private ReadOnlyCollection<Expression> FixupQuotedArgs(MethodInfo mi, ReadOnlyCollection<Expression> argList) { ParameterInfo[] pis = mi.GetParameters(); if (pis.Length > 0) { List<Expression> newArgs = null; for (int i = 0, n = pis.Length; i < n; i++) { Expression arg = argList[i]; ParameterInfo pi = pis[i]; arg = FixupQuotedExpression(pi.ParameterType, arg); if (newArgs == null && arg != argList[i]) { newArgs = new List<Expression>(argList.Count); for (int j = 0; j < i; j++) { newArgs.Add(argList[j]); } } if (newArgs != null) { newArgs.Add(arg); } } if (newArgs != null) argList = newArgs.ToReadOnlyCollection(); } return argList; } private Expression FixupQuotedExpression(Type type, Expression expression) { Expression expr = expression; while (true) { if (type.IsAssignableFrom(expr.Type)) return expr; if (expr.NodeType != ExpressionType.Quote) break; expr = ((UnaryExpression)expr).Operand; } if (!type.IsAssignableFrom(expr.Type) && type.IsArray && expr.NodeType == ExpressionType.NewArrayInit) { Type strippedType = StripExpression(expr.Type); if (type.IsAssignableFrom(strippedType)) { Type elementType = type.GetElementType(); NewArrayExpression na = (NewArrayExpression)expr; List<Expression> exprs = new List<Expression>(na.Expressions.Count); for (int i = 0, n = na.Expressions.Count; i < n; i++) { exprs.Add(this.FixupQuotedExpression(elementType, na.Expressions[i])); } expression = Expression.NewArrayInit(elementType, exprs); } } return expression; } internal override Expression VisitLambda(LambdaExpression lambda) { return lambda; } private static Type GetPublicType(Type t) { // If we create a constant explicitly typed to be a private nested type, // such as Lookup<,>.Grouping or a compiler-generated iterator class, then // we cannot use the expression tree in a context which has only execution // permissions. We should endeavour to translate constants into // new constants which have public types. if (t.GetTypeInfo().IsGenericType && t.GetTypeInfo().GetGenericTypeDefinition().GetTypeInfo().ImplementedInterfaces.Contains(typeof(IGrouping<,>))) return typeof(IGrouping<,>).MakeGenericType(t.GetGenericArguments()); if (!t.GetTypeInfo().IsNestedPrivate) return t; foreach (Type iType in t.GetTypeInfo().ImplementedInterfaces) { if (iType.GetTypeInfo().IsGenericType && iType.GetTypeInfo().GetGenericTypeDefinition() == typeof(IEnumerable<>)) return iType; } if (typeof(IEnumerable).IsAssignableFrom(t)) return typeof(IEnumerable); return t; } internal override Expression VisitConstant(ConstantExpression c) { EnumerableQuery sq = c.Value as EnumerableQuery; if (sq != null) { if (sq.Enumerable != null) { Type t = GetPublicType(sq.Enumerable.GetType()); return Expression.Constant(sq.Enumerable, t); } return this.Visit(sq.Expression); } return c; } internal override Expression VisitParameter(ParameterExpression p) { return p; } private static volatile ILookup<string, MethodInfo> s_seqMethods; private static MethodInfo FindEnumerableMethod(string name, ReadOnlyCollection<Expression> args, params Type[] typeArgs) { if (s_seqMethods == null) { s_seqMethods = typeof(Enumerable).GetStaticMethods().ToLookup(m => m.Name); } MethodInfo mi = s_seqMethods[name].FirstOrDefault(m => ArgsMatch(m, args, typeArgs)); if (mi == null) throw Error.NoMethodOnTypeMatchingArguments(name, typeof(Enumerable)); if (typeArgs != null) return mi.MakeGenericMethod(typeArgs); return mi; } internal static MethodInfo FindMethod(Type type, string name, ReadOnlyCollection<Expression> args, Type[] typeArgs) { MethodInfo[] methods = type.GetStaticMethods().Where(m => m.Name == name).ToArray(); if (methods.Length == 0) throw Error.NoMethodOnType(name, type); MethodInfo mi = methods.FirstOrDefault(m => ArgsMatch(m, args, typeArgs)); if (mi == null) throw Error.NoMethodOnTypeMatchingArguments(name, type); if (typeArgs != null) return mi.MakeGenericMethod(typeArgs); return mi; } private static bool ArgsMatch(MethodInfo m, ReadOnlyCollection<Expression> args, Type[] typeArgs) { ParameterInfo[] mParams = m.GetParameters(); if (mParams.Length != args.Count) return false; if (!m.IsGenericMethod && typeArgs != null && typeArgs.Length > 0) { return false; } if (!m.IsGenericMethodDefinition && m.IsGenericMethod && m.ContainsGenericParameters) { m = m.GetGenericMethodDefinition(); } if (m.IsGenericMethodDefinition) { if (typeArgs == null || typeArgs.Length == 0) return false; if (m.GetGenericArguments().Length != typeArgs.Length) return false; m = m.MakeGenericMethod(typeArgs); mParams = m.GetParameters(); } for (int i = 0, n = args.Count; i < n; i++) { Type parameterType = mParams[i].ParameterType; if (parameterType == null) return false; if (parameterType.IsByRef) parameterType = parameterType.GetElementType(); Expression arg = args[i]; if (!parameterType.IsAssignableFrom(arg.Type)) { if (arg.NodeType == ExpressionType.Quote) { arg = ((UnaryExpression)arg).Operand; } if (!parameterType.IsAssignableFrom(arg.Type) && !parameterType.IsAssignableFrom(StripExpression(arg.Type))) { return false; } } } return true; } private static Type StripExpression(Type type) { bool isArray = type.IsArray; Type tmp = isArray ? type.GetElementType() : type; Type eType = TypeHelper.FindGenericType(typeof(Expression<>), tmp); if (eType != null) tmp = eType.GetGenericArguments()[0]; if (isArray) { int rank = type.GetArrayRank(); return (rank == 1) ? tmp.MakeArrayType() : tmp.MakeArrayType(rank); } return type; } } }
// 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.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.Serialization.Json; using System.Text; using JsonPair = System.Collections.Generic.KeyValuePair<string, System.Json.JsonValue>; namespace System.Json { public abstract class JsonValue : IEnumerable { public static JsonValue Load(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } return Load(new StreamReader(stream, true)); } public static JsonValue Load(TextReader textReader) { if (textReader == null) { throw new ArgumentNullException(nameof(textReader)); } return ToJsonValue(new JavaScriptReader(textReader, true).Read()); } private static IEnumerable<KeyValuePair<string, JsonValue>> ToJsonPairEnumerable(IEnumerable<KeyValuePair<string, object>> kvpc) { foreach (KeyValuePair<string, object> kvp in kvpc) { yield return new KeyValuePair<string, JsonValue>(kvp.Key, ToJsonValue(kvp.Value)); } } private static IEnumerable<JsonValue> ToJsonValueEnumerable(IEnumerable<object> arr) { foreach (object obj in arr) { yield return ToJsonValue(obj); } } private static JsonValue ToJsonValue(object ret) { if (ret == null) { return null; } var kvpc = ret as IEnumerable<KeyValuePair<string, object>>; if (kvpc != null) { return new JsonObject(ToJsonPairEnumerable(kvpc)); } var arr = ret as IEnumerable<object>; if (arr != null) { return new JsonArray(ToJsonValueEnumerable(arr)); } if (ret is bool) return new JsonPrimitive((bool)ret); if (ret is byte) return new JsonPrimitive((byte)ret); if (ret is char) return new JsonPrimitive((char)ret); if (ret is decimal) return new JsonPrimitive((decimal)ret); if (ret is double) return new JsonPrimitive((double)ret); if (ret is float) return new JsonPrimitive((float)ret); if (ret is int) return new JsonPrimitive((int)ret); if (ret is long) return new JsonPrimitive((long)ret); if (ret is sbyte) return new JsonPrimitive((sbyte)ret); if (ret is short) return new JsonPrimitive((short)ret); if (ret is string) return new JsonPrimitive((string)ret); if (ret is uint) return new JsonPrimitive((uint)ret); if (ret is ulong) return new JsonPrimitive((ulong)ret); if (ret is ushort) return new JsonPrimitive((ushort)ret); if (ret is DateTime) return new JsonPrimitive((DateTime)ret); if (ret is DateTimeOffset) return new JsonPrimitive((DateTimeOffset)ret); if (ret is Guid) return new JsonPrimitive((Guid)ret); if (ret is TimeSpan) return new JsonPrimitive((TimeSpan)ret); if (ret is Uri) return new JsonPrimitive((Uri)ret); throw new NotSupportedException(SR.Format(SR.NotSupported_UnexpectedParserType, ret.GetType())); } public static JsonValue Parse(string jsonString) { if (jsonString == null) { throw new ArgumentNullException(nameof(jsonString)); } return Load(new StringReader(jsonString)); } public virtual int Count { get { throw new InvalidOperationException(); } } public abstract JsonType JsonType { get; } public virtual JsonValue this[int index] { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public virtual JsonValue this[string key] { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public virtual bool ContainsKey(string key) { throw new InvalidOperationException(); } public virtual void Save(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } Save(new StreamWriter(stream)); } public virtual void Save(TextWriter textWriter) { if (textWriter == null) { throw new ArgumentNullException(nameof(textWriter)); } SaveInternal(textWriter); } private void SaveInternal(TextWriter w) { switch (JsonType) { case JsonType.Object: w.Write('{'); bool following = false; foreach (JsonPair pair in ((JsonObject)this)) { if (following) { w.Write(", "); } w.Write('\"'); w.Write(EscapeString(pair.Key)); w.Write("\": "); if (pair.Value == null) { w.Write("null"); } else { pair.Value.SaveInternal(w); } following = true; } w.Write('}'); break; case JsonType.Array: w.Write('['); following = false; foreach (JsonValue v in ((JsonArray)this)) { if (following) { w.Write(", "); } if (v != null) { v.SaveInternal(w); } else { w.Write("null"); } following = true; } w.Write(']'); break; case JsonType.Boolean: w.Write(this ? "true" : "false"); break; case JsonType.String: w.Write('"'); w.Write(EscapeString(((JsonPrimitive)this).GetFormattedString())); w.Write('"'); break; default: w.Write(((JsonPrimitive)this).GetFormattedString()); break; } } public override string ToString() { var sw = new StringWriter(); Save(sw); return sw.ToString(); } IEnumerator IEnumerable.GetEnumerator() { throw new InvalidOperationException(); } // Characters which have to be escaped: // - Required by JSON Spec: Control characters, '"' and '\\' // - Broken surrogates to make sure the JSON string is valid Unicode // (and can be encoded as UTF8) // - JSON does not require U+2028 and U+2029 to be escaped, but // JavaScript does require this: // http://stackoverflow.com/questions/2965293/javascript-parse-error-on-u2028-unicode-character/9168133#9168133 // - '/' also does not have to be escaped, but escaping it when // preceeded by a '<' avoids problems with JSON in HTML <script> tags private static bool NeedEscape(string src, int i) { char c = src[i]; return c < 32 || c == '"' || c == '\\' // Broken lead surrogate || (c >= '\uD800' && c <= '\uDBFF' && (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF')) // Broken tail surrogate || (c >= '\uDC00' && c <= '\uDFFF' && (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF')) // To produce valid JavaScript || c == '\u2028' || c == '\u2029' // Escape "</" for <script> tags || (c == '/' && i > 0 && src[i - 1] == '<'); } internal static string EscapeString(string src) { if (src != null) { for (int i = 0; i < src.Length; i++) { if (NeedEscape(src, i)) { var sb = new StringBuilder(); if (i > 0) { sb.Append(src, 0, i); } return DoEscapeString(sb, src, i); } } } return src; } private static string DoEscapeString(StringBuilder sb, string src, int cur) { int start = cur; for (int i = cur; i < src.Length; i++) if (NeedEscape(src, i)) { sb.Append(src, start, i - start); switch (src[i]) { case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '/': sb.Append("\\/"); break; default: sb.Append("\\u"); sb.Append(((int)src[i]).ToString("x04")); break; } start = i + 1; } sb.Append(src, start, src.Length - start); return sb.ToString(); } // CLI -> JsonValue public static implicit operator JsonValue(bool value) => new JsonPrimitive(value); public static implicit operator JsonValue(byte value) => new JsonPrimitive(value); public static implicit operator JsonValue(char value) => new JsonPrimitive(value); public static implicit operator JsonValue(decimal value) => new JsonPrimitive(value); public static implicit operator JsonValue(double value) => new JsonPrimitive(value); public static implicit operator JsonValue(float value) => new JsonPrimitive(value); public static implicit operator JsonValue(int value) => new JsonPrimitive(value); public static implicit operator JsonValue(long value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(sbyte value) => new JsonPrimitive(value); public static implicit operator JsonValue(short value) => new JsonPrimitive(value); public static implicit operator JsonValue(string value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(uint value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(ulong value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(ushort value) => new JsonPrimitive(value); public static implicit operator JsonValue(DateTime value) => new JsonPrimitive(value); public static implicit operator JsonValue(DateTimeOffset value) => new JsonPrimitive(value); public static implicit operator JsonValue(Guid value) => new JsonPrimitive(value); public static implicit operator JsonValue(TimeSpan value) => new JsonPrimitive(value); public static implicit operator JsonValue(Uri value) => new JsonPrimitive(value); // JsonValue -> CLI public static implicit operator bool (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToBoolean(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator byte (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToByte(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator char (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToChar(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator decimal (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToDecimal(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator double (JsonValue value) { if (value == null) throw new ArgumentNullException(nameof(value)); return Convert.ToDouble(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator float (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToSingle(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator int (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToInt32(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator long (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToInt64(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static implicit operator sbyte (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToSByte(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator short (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToInt16(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator string (JsonValue value) { return value != null ? (string)((JsonPrimitive)value).Value : null; } [CLSCompliant(false)] public static implicit operator uint (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToUInt32(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static implicit operator ulong (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToUInt64(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static implicit operator ushort (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToUInt16(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator DateTime(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (DateTime)((JsonPrimitive)value).Value; } public static implicit operator DateTimeOffset(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (DateTimeOffset)((JsonPrimitive)value).Value; } public static implicit operator TimeSpan(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (TimeSpan)((JsonPrimitive)value).Value; } public static implicit operator Guid(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (Guid)((JsonPrimitive)value).Value; } public static implicit operator Uri(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (Uri)((JsonPrimitive)value).Value; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalUserAccountServicesConnector")] public class LocalUserAccountServicesConnector : ISharedRegionModule, IUserAccountService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This is not on the IUserAccountService. It's only being used so that standalone scenes can punch through /// to a local UserAccountService when setting up an estate manager. /// </summary> public IUserAccountService UserAccountService { get; private set; } private UserAccountCache m_Cache; private bool m_Enabled = false; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalUserAccountServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("UserAccountServices", ""); if (name == Name) { IConfig userConfig = source.Configs["UserAccountService"]; if (userConfig == null) { m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: UserAccountService missing from OpenSim.ini"); return; } string serviceDll = userConfig.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: No LocalServiceModule named in section UserService"); return; } Object[] args = new Object[] { source }; UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(serviceDll, args); if (UserAccountService == null) { m_log.ErrorFormat( "[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Cannot load user account service specified as {0}", serviceDll); return; } m_Enabled = true; m_Cache = new UserAccountCache(); m_log.Info("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Local user connector enabled"); } } } public void PostInitialise() { if (!m_Enabled) return; } public void Close() { if (!m_Enabled) return; } public void AddRegion(Scene scene) { if (!m_Enabled) return; // FIXME: Why do we bother setting this module and caching up if we just end up registering the inner // user account service?! scene.RegisterModuleInterface<IUserAccountService>(UserAccountService); scene.RegisterModuleInterface<IUserAccountCacheModule>(m_Cache); } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; m_log.InfoFormat("[LOCAL USER ACCOUNT SERVICE CONNECTOR]: Enabled local user accounts for region {0}", scene.RegionInfo.RegionName); } #endregion #region IUserAccountService public UserAccount GetUserAccount(UUID scopeID, UUID userID) { bool inCache = false; UserAccount account = m_Cache.Get(userID, out inCache); if (inCache) return account; account = UserAccountService.GetUserAccount(scopeID, userID); m_Cache.Cache(userID, account); return account; } public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { bool inCache = false; UserAccount account = m_Cache.Get(firstName + " " + lastName, out inCache); if (inCache) return account; account = UserAccountService.GetUserAccount(scopeID, firstName, lastName); if (account != null) m_Cache.Cache(account.PrincipalID, account); return account; } public UserAccount GetUserAccount(UUID scopeID, string Email) { return UserAccountService.GetUserAccount(scopeID, Email); } public List<UserAccount> GetUserAccountsWhere(UUID scopeID, string query) { return null; } public List<UserAccount> GetUserAccounts(UUID scopeID, string query) { return UserAccountService.GetUserAccounts(scopeID, query); } // Update all updatable fields // public bool StoreUserAccount(UserAccount data) { bool ret = UserAccountService.StoreUserAccount(data); if (ret) m_Cache.Cache(data.PrincipalID, data); return ret; } public void InvalidateCache(UUID userID) { m_Cache.Invalidate(userID); } #endregion } }
using Orleans; using Orleans.Runtime; using Orleans.TestingHost; using System; using System.Diagnostics; using System.Threading.Tasks; using Orleans.TestingHost.Utils; using Tester; using UnitTests.GrainInterfaces; using UnitTests.Tester; using Xunit; using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace UnitTests.General { /// <summary> /// Summary description for ObserverTests /// </summary> public class ObserverTests : HostedTestClusterEnsureDefaultStarted { private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10); private int callbackCounter; private readonly bool[] callbacksRecieved = new bool[2]; // we keep the observer objects as instance variables to prevent them from // being garbage collected permaturely (the runtime stores them as weak references). private SimpleGrainObserver observer1; private SimpleGrainObserver observer2; public void TestInitialize() { callbackCounter = 0; callbacksRecieved[0] = false; callbacksRecieved[1] = false; observer1 = null; observer2 = null; } private ISimpleObserverableGrain GetGrain() { return GrainFactory.GetGrain<ISimpleObserverableGrain>(GetRandomGrainId()); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_SimpleNotification() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result); ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(this.observer1); await grain.Subscribe(reference); await grain.SetA(3); await grain.SetB(2); Assert.IsTrue(await result.WaitForFinished(timeout), "Should not timeout waiting {0} for {1}", timeout, "SetB"); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_SimpleNotification_GeneratedFactory() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result); ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(3); await grain.SetB(2); Assert.IsTrue(await result.WaitForFinished(timeout), "Should not timeout waiting {0} for {1}", timeout, "SetB"); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); if (a == 3 && b == 0) callbacksRecieved[0] = true; else if (a == 3 && b == 2) callbacksRecieved[1] = true; else throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b); if (callbackCounter == 1) { // Allow for callbacks occurring in any order Assert.IsTrue(callbacksRecieved[0] || callbacksRecieved[1], "Received one callback ok"); } else if (callbackCounter == 2) { Assert.IsTrue(callbacksRecieved[0] && callbacksRecieved[1], "Received two callbacks ok"); result.Done = true; } else { Assert.Fail("Callback has been called more times than was expected."); } } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_DoubleSubscriptionSameReference() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionSameReference_Callback, result); ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(1); // Use grain try { await grain.Subscribe(reference); } catch (TimeoutException) { throw; } catch (Exception exc) { Exception baseException = exc.GetBaseException(); logger.Info("Received exception: {0}", baseException); Assert.IsInstanceOfType(baseException, typeof(OrleansException)); if (!baseException.Message.StartsWith("Cannot subscribe already subscribed observer")) { Assert.Fail("Unexpected exception message: " + baseException); } } await grain.SetA(2); // Use grain Assert.IsFalse(await result.WaitForFinished(timeout), "Should timeout waiting {0} for {1}", timeout, "SetA(2)"); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } void ObserverTest_DoubleSubscriptionSameReference_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_DoubleSubscriptionSameReference_Callback for {0} time with a={1} and b={2}", callbackCounter, a, b); Assert.IsTrue(callbackCounter <= 2, "Callback has been called more times than was expected {0}", callbackCounter); if (callbackCounter == 2) { result.Continue = true; } } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_SubscribeUnsubscribe() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SubscribeUnsubscribe_Callback, result); ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(5); Assert.IsTrue(await result.WaitForContinue(timeout), "Should not timeout waiting {0} for {1}", timeout, "SetA"); await grain.Unsubscribe(reference); await grain.SetB(3); Assert.IsFalse(await result.WaitForFinished(timeout), "Should timeout waiting {0} for {1}", timeout, "SetB"); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } void ObserverTest_SubscribeUnsubscribe_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_SubscribeUnsubscribe_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); Assert.IsTrue(callbackCounter < 2, "Callback has been called more times than was expected."); Assert.AreEqual(5, a); Assert.AreEqual(0, b); result.Continue = true; } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_Unsubscribe() { TestInitialize(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(null, null); ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); try { await grain.Unsubscribe(reference); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); } catch (TimeoutException) { throw; } catch (Exception exc) { Exception baseException = exc.GetBaseException(); if (!(baseException is OrleansException)) Assert.Fail("Unexpected exception type {0}", baseException); } } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_DoubleSubscriptionDifferentReferences() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result); ISimpleGrainObserver reference1 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); observer2 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result); ISimpleGrainObserver reference2 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer2); await grain.Subscribe(reference1); await grain.Subscribe(reference2); grain.SetA(6).Ignore(); Assert.IsTrue(await result.WaitForFinished(timeout), "Should not timeout waiting {0} for {1}", timeout, "SetA"); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference1); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference2); } void ObserverTest_DoubleSubscriptionDifferentReferences_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_DoubleSubscriptionDifferentReferences_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); Assert.IsTrue(callbackCounter < 3, "Callback has been called more times than was expected."); Assert.AreEqual(6, a); Assert.AreEqual(0, b); if (callbackCounter == 2) result.Done = true; } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_DeleteObject() { TestInitialize(); var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_DeleteObject_Callback, result); ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1); await grain.Subscribe(reference); await grain.SetA(5); Assert.IsTrue(await result.WaitForContinue(timeout), "Should not timeout waiting {0} for {1}", timeout, "SetA"); await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference); await grain.SetB(3); Assert.IsFalse(await result.WaitForFinished(timeout), "Should timeout waiting {0} for {1}", timeout, "SetB"); } void ObserverTest_DeleteObject_Callback(int a, int b, AsyncResultHandle result) { callbackCounter++; logger.Info("Invoking ObserverTest_DeleteObject_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b); Assert.IsTrue(callbackCounter < 2, "Callback has been called more times than was expected."); Assert.AreEqual(5, a); Assert.AreEqual(0, b); result.Continue = true; } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ObserverTest_SubscriberMustBeGrainReference() { TestInitialize(); await Xunit.Assert.ThrowsAsync(typeof(NotSupportedException), async () => { var result = new AsyncResultHandle(); ISimpleObserverableGrain grain = GetGrain(); observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result); ISimpleGrainObserver reference = observer1; // Should be: GrainFactory.CreateObjectReference<ISimpleGrainObserver>(obj); await grain.Subscribe(reference); // Not reached }); } internal class SimpleGrainObserver : ISimpleGrainObserver { readonly Action<int, int, AsyncResultHandle> action; readonly AsyncResultHandle result; public SimpleGrainObserver(Action<int, int, AsyncResultHandle> action, AsyncResultHandle result) { this.action = action; this.result = result; } #region ISimpleGrainObserver Members public void StateChanged(int a, int b) { GrainClient.Logger.Verbose("SimpleGrainObserver.StateChanged a={0} b={1}", a, b); if (action != null) { action(a, b, result); } } #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.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using Internal.Reflection.Tracing; using Internal.Reflection.Core.Execution; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // TypeInfos that represent constructed generic types. // // internal sealed partial class RuntimeConstructedGenericTypeInfo : RuntimeTypeInfo, IKeyedItem<RuntimeConstructedGenericTypeInfo.UnificationKey> { private RuntimeConstructedGenericTypeInfo(UnificationKey key) { _key = key; } public sealed override bool IsTypeDefinition => false; public sealed override bool IsGenericTypeDefinition => false; protected sealed override bool HasElementTypeImpl() => false; protected sealed override bool IsArrayImpl() => false; public sealed override bool IsSZArray => false; public sealed override bool IsVariableBoundArray => false; protected sealed override bool IsByRefImpl() => false; protected sealed override bool IsPointerImpl() => false; public sealed override bool IsConstructedGenericType => true; public sealed override bool IsGenericParameter => false; public sealed override bool IsByRefLike => GenericTypeDefinitionTypeInfo.IsByRefLike; // // Implements IKeyedItem.PrepareKey. // // This method is the keyed item's chance to do any lazy evaluation needed to produce the key quickly. // Concurrent unifiers are guaranteed to invoke this method at least once and wait for it // to complete before invoking the Key property. The unifier lock is NOT held across the call. // // PrepareKey() must be idempodent and thread-safe. It may be invoked multiple times and concurrently. // public void PrepareKey() { } // // Implements IKeyedItem.Key. // // Produce the key. This is a high-traffic property and is called while the hash table's lock is held. Thus, it should // return a precomputed stored value and refrain from invoking other methods. If the keyed item wishes to // do lazy evaluation of the key, it should do so in the PrepareKey() method. // public UnificationKey Key { get { return _key; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_CustomAttributes(this); #endif return GenericTypeDefinitionTypeInfo.CustomAttributes; } } public sealed override string FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_FullName(this); #endif // Desktop quirk: open constructions don't have "fullNames". if (ContainsGenericParameters) return null; StringBuilder fullName = new StringBuilder(); fullName.Append(GenericTypeDefinitionTypeInfo.FullName); fullName.Append('['); RuntimeTypeInfo[] genericTypeArguments = _key.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) { if (i != 0) fullName.Append(','); fullName.Append('['); fullName.Append(genericTypeArguments[i].AssemblyQualifiedName); fullName.Append(']'); } fullName.Append(']'); return fullName.ToString(); } } public sealed override Type GetGenericTypeDefinition() { return GenericTypeDefinitionTypeInfo; } public sealed override Guid GUID { get { return GenericTypeDefinitionTypeInfo.GUID; } } public sealed override Assembly Assembly { get { return GenericTypeDefinitionTypeInfo.Assembly; } } public sealed override bool ContainsGenericParameters { get { foreach (RuntimeTypeInfo typeArgument in _key.GenericTypeArguments) { if (typeArgument.ContainsGenericParameters) return true; } return false; } } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { return GenericTypeDefinitionTypeInfo.HasSameMetadataDefinitionAs(other); } public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif return GenericTypeDefinitionTypeInfo.Namespace; } } public sealed override StructLayoutAttribute StructLayoutAttribute { get { return GenericTypeDefinitionTypeInfo.StructLayoutAttribute; } } public sealed override int MetadataToken { get { return GenericTypeDefinitionTypeInfo.MetadataToken; } } public sealed override string ToString() { // Get the FullName of the generic type definition in a pay-for-play safe way. RuntimeTypeInfo genericTypeDefinition = GenericTypeDefinitionTypeInfo; string genericTypeDefinitionString = null; if (genericTypeDefinition.InternalNameIfAvailable != null) // Want to avoid "cry-wolf" exceptions: if we can't even get the simple name, don't bother getting the FullName. { // Given our current pay for play policy, it should now be safe to attempt getting the FullName. (But guard with a try-catch in case this assumption is wrong.) try { genericTypeDefinitionString = genericTypeDefinition.FullName; } catch (Exception) { } } // If all else fails, use the ToString() - it won't match the legacy CLR but with no metadata, we can't match it anyway. if (genericTypeDefinitionString == null) genericTypeDefinitionString = genericTypeDefinition.ToString(); // Now, append the generic type arguments. StringBuilder sb = new StringBuilder(); sb.Append(genericTypeDefinitionString); sb.Append('['); RuntimeTypeInfo[] genericTypeArguments = _key.GenericTypeArguments; for (int i = 0; i < genericTypeArguments.Length; i++) { if (i != 0) sb.Append(','); sb.Append(genericTypeArguments[i].ToString()); } sb.Append(']'); return sb.ToString(); } protected sealed override TypeAttributes GetAttributeFlagsImpl() { return GenericTypeDefinitionTypeInfo.Attributes; } protected sealed override int InternalGetHashCode() { return _key.GetHashCode(); } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // baseclass and interfaces based on its constraints. // internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { RuntimeTypeInfo genericTypeDefinition = this.GenericTypeDefinitionTypeInfo; RuntimeNamedTypeInfo genericTypeDefinitionNamedTypeInfo = genericTypeDefinition as RuntimeNamedTypeInfo; if (genericTypeDefinitionNamedTypeInfo == null) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(genericTypeDefinition); return genericTypeDefinitionNamedTypeInfo; } } internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => GenericTypeDefinitionTypeInfo.CanBrowseWithoutMissingMetadataExceptions; internal sealed override Type InternalDeclaringType { get { RuntimeTypeHandle typeHandle = InternalTypeHandleIfAvailable; if ((!typeHandle.IsNull()) && ReflectionCoreExecution.ExecutionEnvironment.IsReflectionBlocked(typeHandle)) return null; return GenericTypeDefinitionTypeInfo.InternalDeclaringType; } } internal sealed override string InternalFullNameOfAssembly { get { return GenericTypeDefinitionTypeInfo.InternalFullNameOfAssembly; } } public sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { return GenericTypeDefinitionTypeInfo.InternalGetNameIfAvailable(ref rootCauseForFailure); } internal sealed override RuntimeTypeInfo[] InternalRuntimeGenericTypeArguments { get { return _key.GenericTypeArguments; } } internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable { get { return _key.TypeHandle; } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { return this.GenericTypeDefinitionTypeInfo.TypeRefDefOrSpecForBaseType; } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { return this.GenericTypeDefinitionTypeInfo.TypeRefDefOrSpecsForDirectlyImplementedInterfaces; } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { return new TypeContext(this.InternalRuntimeGenericTypeArguments, null); } } private RuntimeTypeInfo GenericTypeDefinitionTypeInfo { get { return _key.GenericTypeDefinition; } } private readonly UnificationKey _key; } }
/////////////////////////////////////////////////////////////////////////////// //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. /////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Collections; using System.Collections.Generic; using System; #if UNITY_EDITOR using UnityEditor; #endif namespace daydreamrenderer { using LightModes = TypeExtensions.LightModes; [ExecuteInEditMode] [RequireComponent(typeof(Light))] public class DaydreamLight : MonoBehaviour { // sort the direction lights to the top of the list public class LightSort : IComparer<DaydreamLight> { public int Compare(DaydreamLight x, DaydreamLight y) { if (x.m_light.type == LightType.Directional && y.m_light.type != LightType.Directional) { return -1; } else if (x.m_light.type != LightType.Directional && y.m_light.type == LightType.Directional) { return 1; } return 0; } } public static bool s_resortLights = false; // Daydream light manages a list lights in the scene public static DaydreamLight[] s_masterLightArray = new DaydreamLight[0]; [HideInInspector] // this field serializes the last light mode public int m_lightMode = LightModes.REALTIME; // dist from light to object [System.NonSerialized] public float m_dist = 0f; // light data wraps a light [System.NonSerialized] public Light m_light; // cache the world pos for fast access [System.NonSerialized] public Vector4 m_worlPos; // cache the world dir for fast access [System.NonSerialized] public Vector4 m_worldDir; // flagged if any tracked property change (eg range, angle, intensity) [System.NonSerialized] public bool m_propertiesChanged = true; // flagged if light transform has change (ie the light moved) [System.NonSerialized] public bool m_transformChanged = true; // cache the type [System.NonSerialized] public LightType m_type; // track frame updates [System.NonSerialized] public static int s_viewSpaceId; // cache the view matrix [System.NonSerialized] static Matrix4x4 s_toViewSpace; // light mode (real time, mixed, etc) [System.NonSerialized] public int m_curMode = LightModes.REALTIME; // cache the light culling layer [System.NonSerialized] public int m_cullingMask = 0; // track the last range [System.NonSerialized] public float m_lastRange = 0f; // track last intensity [System.NonSerialized] public float m_lastIntensity = 0f; // internal list of lights to accomodate sorting static List<DaydreamLight> s_masterLightList = new List<DaydreamLight>(); // always update on init bool m_didInit = false; // calculated values that are passed to a shader float m_attenW; float m_attenX; float m_attenY; float m_attenZ; Vector4 m_viewSpacePos; Vector4 m_viewSpaceDir; Vector4 m_color; // these fields track changes to minimize recalculations as much as possible float m_lastAngle = float.MaxValue; Color m_lastColor = Color.clear; // ensure properties are updated bool m_invalidatedProps = true; public static void StartFrame(Camera camera) { s_toViewSpace = camera.worldToCameraMatrix; // update frame s_viewSpaceId = ++s_viewSpaceId % int.MaxValue; } // Called when property has changed public void UpdateFrame() { float spotAngle = m_light.spotAngle; float range = m_light.range; if (m_invalidatedProps || m_lastAngle != spotAngle) { m_attenX = Mathf.Cos(spotAngle * Mathf.Deg2Rad * 0.5f); m_attenY = 1f / Mathf.Cos(spotAngle * Mathf.Deg2Rad * 0.25f); } if (m_invalidatedProps || m_lastRange != range) { m_attenZ = ComputeLightAttenuation(m_light); m_attenW = range * range; } m_cullingMask = m_light.cullingMask; // updates to track changes m_type = m_light.type; Color color = m_color = m_light.color; float intensity = m_light.intensity; if (m_type == LightType.Spot) { m_color = color * intensity * intensity; } else { m_color = color * intensity; } m_lastColor = color; m_lastRange = range; m_lastAngle = spotAngle; m_lastIntensity = intensity; m_invalidatedProps = false; } // called when light transform has changed public void UpdateViewSpace() { Transform t = m_light.transform; m_worlPos = t.position; m_worlPos.w = 1f; m_worldDir = -t.forward; m_worldDir.w = 0f; // create view space position m_viewSpacePos = s_toViewSpace*m_worlPos; m_viewSpacePos.w = 1f; if(m_type != LightType.Point) { m_viewSpaceDir = s_toViewSpace*m_worldDir; m_viewSpaceDir.w = 0f; } } public float GetAttenX() { return m_attenX; } public float GetAttenY() { return m_attenY; } public float GetAttenZ() { return m_attenZ; } public float GetAttenW() { return m_attenW; } public void GetViewSpacePos(ref Vector4 viewSpacePos) { viewSpacePos = m_viewSpacePos; } public void GetViewSpaceDir(ref Vector4 viewSpaceDir) { viewSpaceDir = m_viewSpaceDir; } public void GetColor(ref Vector4 color) { color = m_color; } // test for changes and set flags public bool CheckForChange() { Color color = m_light.color; if ( !m_didInit || m_lastAngle != m_light.spotAngle || color.r != m_lastColor.r || color.g != m_lastColor.g || color.b != m_lastColor.b || color.a != m_lastColor.a || m_lastIntensity != m_light.intensity || m_lastRange != m_light.range) { m_didInit = true; m_propertiesChanged = true; } else { m_propertiesChanged = false; } if (m_light.type != m_type) { m_propertiesChanged = true; // make sure calculation that depend on properties get updated m_invalidatedProps = true; // sort may be different now DaydreamLight.s_resortLights = true; } // check transform for changes if (m_light.transform.hasChanged) { m_light.transform.hasChanged = false; m_transformChanged = true; } else { m_transformChanged = false; } // return true if anything changed return m_transformChanged || m_propertiesChanged; } public void InEditorUpdate() { #if UNITY_EDITOR // Monitor for editor property change 'Light Mode' if (!Application.isPlaying) { if (Selection.activeGameObject == gameObject) { Light l = gameObject.GetComponent<Light>(); int newMode = l.LightMode(); if (newMode != m_lightMode) { // update the light mode if (m_lightMode == LightModes.BAKED) { // if it was baked and is no longer add it to master list RemoveFromEditorUpdateList(); AddToMasterList(); } else if (newMode == LightModes.BAKED) { // if it is now a baked a light remove it from the master list RemoveFromMasterList(); AddToEditorUpdateList(); } m_curMode = newMode; m_lightMode = newMode; } } } #endif } public static int GetLightCount() { return s_masterLightArray.Length; } public static void ResortLights() { s_masterLightList.Sort(new LightSort()); s_masterLightArray = s_masterLightList.ToArray(); } public static void ClearList(ref int[] list) { for(int i = 0, k = list.Length; i < k; ++i) { list[i] = -1; } } public static bool AnyLightChanged() { for (int i = 0, k = s_masterLightArray.Length; i < k; ++i) { if (s_masterLightArray[i].m_propertiesChanged || s_masterLightList[i].m_transformChanged || !s_masterLightArray[i].m_didInit) { return true; } } return false; } public static void GetSortedLights(int updateKey, int layer, bool isStatic, Vector3 objPosition, Bounds bounds, ref int[] outLightList, ref int usedSlots) { ClearList(ref outLightList); float dist2 = 0f; DaydreamLight dl = null; usedSlots = 0; // number of directional lights int dirCount = 0; // insert sort lights - Note: directional lights are always sorted to the top of the master list // this allows for some assumptions for (int i = 0, k = s_masterLightArray.Length; i < k; ++i) { // i'th light data dl = s_masterLightArray[i]; int ithLight = i; if((dl.m_cullingMask & (1 << layer)) == 0 || (isStatic && dl.m_curMode != LightModes.REALTIME)) { continue; } if (dl.m_type != LightType.Directional) { // from cam to light objPosition = bounds.center; // only update if needed float range2 = dl.m_lastRange * dl.m_lastRange; float x = (dl.m_worlPos.x - objPosition.x)*(dl.m_worlPos.x - objPosition.x); float y = (dl.m_worlPos.y - objPosition.y)*(dl.m_worlPos.y - objPosition.y); float z = (dl.m_worlPos.z - objPosition.z)*(dl.m_worlPos.z - objPosition.z); dl.m_dist = (x + y + z) - range2; dist2 = dl.m_dist; for (int j = dirCount; j < outLightList.Length; ++j) { if(outLightList[j] == -1) { // insert the i'th light outLightList[j] = ithLight; usedSlots++; break; } // if the i'th light is closer than the j'th light else if (dist2 < s_masterLightArray[outLightList[j]].m_dist) { // butterfly swap ithLight ^= outLightList[j]; outLightList[j] ^= ithLight; ithLight ^= outLightList[j]; // update distance to the i'th light dist2= s_masterLightArray[ithLight].m_dist; } } } else { dirCount = i; outLightList[i] = ithLight; usedSlots++; } } } void OnEnable() { DaydreamLightingManager.Init(); #if UNITY_EDITOR if (!Application.isPlaying) { Light l = gameObject.GetComponent<Light>(); m_lightMode = l.LightMode(); } #endif // add lights to the master list if(m_lightMode != LightModes.BAKED) { AddToMasterList(); } #if UNITY_EDITOR else { AddToEditorUpdateList(); } #endif } void OnDisable() { // remove light from the master list #if UNITY_EDITOR if(m_lightMode == LightModes.BAKED) { RemoveFromEditorUpdateList(); } else #endif { RemoveFromMasterList(); } } void AddToMasterList() { m_light = gameObject.GetComponent<Light>(); m_curMode = m_lightMode; m_didInit = false; s_masterLightList.Add(this); s_masterLightList.Sort(new LightSort()); s_masterLightArray = s_masterLightList.ToArray(); } void RemoveFromMasterList() { s_masterLightList.Remove(this); s_masterLightArray = s_masterLightList.ToArray(); } #if UNITY_EDITOR void AddToEditorUpdateList() { m_light = gameObject.GetComponent<Light>(); m_curMode = m_lightMode; m_didInit = false; DaydreamLightingManager.s_inEditorUpdateList.Add(this); } void RemoveFromEditorUpdateList() { DaydreamLightingManager.s_inEditorUpdateList.Remove(this); } #endif static float ComputeLightAttenuation(Light light) { float lightRange = light.range; LightType lightType = light.type; // point light attenuation float atten = 0f; float lightRange2 = lightRange*lightRange; const float kl = 1.0f; const float kq = 25.0f; if (lightType == LightType.Point || lightType == LightType.Area) { if (lightType == LightType.Point) { atten = kq / lightRange2; } else if (lightType == LightType.Area) { atten = kl / lightRange2; } } else if (lightType == LightType.Directional) { atten = 0.0f; } else if (lightType == LightType.Spot) { atten = kq / lightRange2; } return atten; } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections; using System.Collections.Specialized; using System.Text; using gov.va.medora.mdo.dao; using gov.va.medora.mdo.exceptions; namespace gov.va.medora.mdo { public class HospitalLocation { string id; string name; string abbr; string type; KeyValuePair<string, string> typeExtension; KeyValuePair<string, string> institution; KeyValuePair<string, string> division; KeyValuePair<string, string> module; string dispositionAction; string visitLocation; KeyValuePair<string, string> stopCode; KeyValuePair<string, string> department; KeyValuePair<string, string> service; KeyValuePair<string, string> specialty; string physicalLocation; KeyValuePair<string, string> wardLocation; KeyValuePair<string, string> principalClinic; Site facility; string building; string floor; string room; string bed; string status; string phone; string appointmentTimestamp; bool _askForCheckIn; // file 44 field 24 string _appointmentLength; // file 44 field 1912 string _clinicDisplayStartTime; // file 44, field 1914 string _displayIncrements; // file 44, field 1917 IList<TimeSlot> _availability; const string DAO_NAME = "ILocationDao"; public IList<TimeSlot> Availability { get { return _availability; } set { _availability = value; } } public string ClinicDisplayStartTime { get { return _clinicDisplayStartTime; } set { _clinicDisplayStartTime = value; } } public string DisplayIncrements { get { return _displayIncrements; } set { _displayIncrements = value; } } public string AppointmentLength { get { return _appointmentLength; } set { _appointmentLength = value; } } public bool AskForCheckIn { get { return _askForCheckIn; } set { _askForCheckIn = value; } } public HospitalLocation(string id, string name) { Id = id; Name = name; } public HospitalLocation() {} public string Id { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public string Abbr { get { return abbr; } set { abbr = value; } } public string Type { get { return type; } set { type = value; } } public KeyValuePair<string, string> TypeExtension { get { return typeExtension; } set { typeExtension = value; } } public KeyValuePair<string, string> Institution { get { return institution; } set { institution = value; } } public KeyValuePair<string, string> Division { get { return division; } set { division = value; } } public KeyValuePair<string, string> Module { get { return module; } set { module = value; } } public string DispositionAction { get { return dispositionAction; } set { dispositionAction = value; } } public string VisitLocation { get { return visitLocation; } set { visitLocation = value; } } public KeyValuePair<string, string> StopCode { get { return stopCode; } set { stopCode = value; } } public KeyValuePair<string, string> Department { get { return department; } set { department = value; } } public KeyValuePair<string, string> Service { get { return service; } set { service = value; } } public KeyValuePair<string, string> Specialty { get { return specialty; } set { specialty = value; } } public string PhysicalLocation { get { return physicalLocation; } set { physicalLocation = value; } } public KeyValuePair<string, string> WardLocation { get { return wardLocation; } set { wardLocation = value; } } public KeyValuePair<string, string> PrincipalClinic { get { return principalClinic; } set { principalClinic = value; } } public Site Facility { get { return facility; } set { facility = value; } } public string Building { get { return building; } set { building = value; } } public string Floor { get { return floor; } set { floor = value; } } public string Room { get { return room; } set { room = value; } } public string Bed { get { return bed; } set { bed = value; } } public string Status { get { return status; } set { status = value; } } public string Phone { get { return phone; } set { phone = value; } } public string AppointmentTimestamp { get { return appointmentTimestamp; } set { appointmentTimestamp = value; } } internal static ILocationDao getDao(AbstractConnection cxn) { if (!cxn.IsConnected) { throw new MdoException(MdoExceptionCode.USAGE_NO_CONNECTION, "Unable to instantiate DAO: unconnected"); } AbstractDaoFactory f = AbstractDaoFactory.getDaoFactory(AbstractDaoFactory.getConstant(cxn.DataSource.Protocol)); return f.getLocationDao(cxn); } public static List<SiteId> getSitesForStation(AbstractConnection cxn) { return getDao(cxn).getSitesForStation(); } public static OrderedDictionary getClinicsByName(AbstractConnection cxn, string name) { return getDao(cxn).getClinicsByName(name); } } }
// *********************************************************************** // Assembly : ACBr.Net.Sat // Author : RFTD // Created : 03-30-2016 // // Last Modified By : RFTD // Last Modified On : 02-20-2018 // *********************************************************************** // <copyright file="SatIntegradorMFe.cs" company="ACBr.Net"> // The MIT License (MIT) // Copyright (c) 2016 Grupo ACBr.Net // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // </copyright> // <summary></summary> // *********************************************************************** using System.Text; namespace ACBr.Net.Sat { internal sealed class SatIntegradorMFe : ISatLibrary { #region Fields private const string MFe = "MF-e"; #endregion Fields #region Constructors public SatIntegradorMFe(SatConfig config, string pathDll, Encoding encoding) { ModeloStr = "SatIntegradorMFe"; PathDll = pathDll; Encoding = encoding; Config = config; } #endregion Constructors #region Propriedades public Encoding Encoding { get; private set; } public string PathDll { get; private set; } public string ModeloStr { get; } public SatConfig Config { get; private set; } #endregion Propriedades #region Methods public string AssociarAssinatura(int numeroSessao, string codigoDeAtivacao, string cnpjValue, string assinaturacnpj) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "AssociarAssinatura"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("cnpjValue", cnpjValue); parametros.AddParametro("assinaturaCNPJs", assinaturacnpj); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string AtivarSAT(int numeroSessao, int subComando, string codigoDeAtivacao, string cnpj, int cUF) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "AtivarMFe"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("subComando", subComando.ToString()); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("CNPJ", cnpj); parametros.AddParametro("cUF", cUF.ToString()); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string AtualizarSoftwareSAT(int numeroSessao, string codigoDeAtivacao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "AtualizarSoftwareMFe"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string BloquearSAT(int numeroSessao, string codigoDeAtivacao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "BloquearMFe"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string CancelarUltimaVenda(int numeroSessao, string codigoDeAtivacao, string chave, string dadosCancelamento) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "CancelarUltimaVenda"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("chave", chave); parametros.AddParametro("dadosCancelamento", $"<![CDATA[{dadosCancelamento}]]>"); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string ComunicarCertificadoIcpBrasil(int numeroSessao, string codigoDeAtivacao, string certificado) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "ComunicarCertificadoICPBRASIL"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("certificado", certificado); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string ConfigurarInterfaceDeRede(int numeroSessao, string codigoDeAtivacao, string dadosConfiguracao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "ConfigurarInterfaceDeRede"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("dadosConfiguracao", dadosConfiguracao); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string ConsultarNumeroSessao(int numeroSessao, string codigoDeAtivacao, int cNumeroDeSessao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "ConsultarNumeroSessao"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("cNumeroDeSessao", cNumeroDeSessao.ToString()); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string ConsultarUltimaSessaoFiscal(int numeroSessao, string codigoDeAtivacao) { throw new System.NotImplementedException(); } public string ConsultarSAT(int numeroSessao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "ConsultarMFe"; var parametros = integrador.Parametros; parametros.Clear(); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string ConsultarStatusOperacional(int numeroSessao, string codigoDeAtivacao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "ConsultarStatusOperacional"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string DesbloquearSAT(int numeroSessao, string codigoDeAtivacao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "DesbloquearMFe"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string EnviarDadosVenda(int numeroSessao, string codigoDeAtivacao, string dadosVenda) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "EnviarDadosVenda"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("dadosVenda", $"<![CDATA[{dadosVenda}]]>"); parametros.AddParametro("nrDocumento", numeroSessao.ToString()); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string ExtrairLogs(int numeroSessao, string codigoDeAtivacao) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "ExtrairLogs"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string TesteFimAFim(int numeroSessao, string codigoDeAtivacao, string dadosVenda) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "TesteFimAFim"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("dadosVenda", $"<![CDATA[{dadosVenda}]]>"); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public string TrocarCodigoDeAtivacao(int numeroSessao, string codigoDeAtivacao, int opcao, string novoCodigo, string confNovoCodigo) { var integrador = Config.Parent.IntegradorFiscal; integrador.NomeComponente = MFe; integrador.NomeMetodo = "TrocarCodigoDeAtivacao"; var parametros = integrador.Parametros; parametros.Clear(); parametros.AddParametro("codigoDeAtivacao", codigoDeAtivacao); parametros.AddParametro("opcao", opcao.ToString()); parametros.AddParametro("novoCodigo", novoCodigo); parametros.AddParametro("confNovoCodigo", confNovoCodigo); var resposta = integrador.Enviar(); return resposta.Resposta.Retorno; } public void Dispose() { } #endregion Methods } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Domains.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDomainsClientTest { [xunit::FactAttribute] public void SearchDomainsRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomains(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse response = client.SearchDomains(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchDomainsRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomainsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchDomainsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse responseCallSettings = await client.SearchDomainsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchDomainsResponse responseCancellationToken = await client.SearchDomainsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchDomains() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomains(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse response = client.SearchDomains(request.Location, request.Query); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchDomainsAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomainsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchDomainsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse responseCallSettings = await client.SearchDomainsAsync(request.Location, request.Query, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchDomainsResponse responseCancellationToken = await client.SearchDomainsAsync(request.Location, request.Query, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SearchDomainsResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomains(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse response = client.SearchDomains(request.LocationAsLocationName, request.Query); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SearchDomainsResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SearchDomainsRequest request = new SearchDomainsRequest { Query = "queryf0c71c1b", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; SearchDomainsResponse expectedResponse = new SearchDomainsResponse { RegisterParameters = { new RegisterParameters(), }, }; mockGrpcClient.Setup(x => x.SearchDomainsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SearchDomainsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); SearchDomainsResponse responseCallSettings = await client.SearchDomainsAsync(request.LocationAsLocationName, request.Query, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SearchDomainsResponse responseCancellationToken = await client.SearchDomainsAsync(request.LocationAsLocationName, request.Query, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveRegisterParametersRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse response = client.RetrieveRegisterParameters(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveRegisterParametersRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveRegisterParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse responseCallSettings = await client.RetrieveRegisterParametersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveRegisterParametersResponse responseCancellationToken = await client.RetrieveRegisterParametersAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveRegisterParameters() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse response = client.RetrieveRegisterParameters(request.Location, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveRegisterParametersAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveRegisterParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse responseCallSettings = await client.RetrieveRegisterParametersAsync(request.Location, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveRegisterParametersResponse responseCancellationToken = await client.RetrieveRegisterParametersAsync(request.Location, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveRegisterParametersResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse response = client.RetrieveRegisterParameters(request.LocationAsLocationName, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveRegisterParametersResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveRegisterParametersRequest request = new RetrieveRegisterParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveRegisterParametersResponse expectedResponse = new RetrieveRegisterParametersResponse { RegisterParameters = new RegisterParameters(), }; mockGrpcClient.Setup(x => x.RetrieveRegisterParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveRegisterParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveRegisterParametersResponse responseCallSettings = await client.RetrieveRegisterParametersAsync(request.LocationAsLocationName, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveRegisterParametersResponse responseCancellationToken = await client.RetrieveRegisterParametersAsync(request.LocationAsLocationName, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveTransferParametersRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse response = client.RetrieveTransferParameters(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveTransferParametersRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveTransferParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse responseCallSettings = await client.RetrieveTransferParametersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveTransferParametersResponse responseCancellationToken = await client.RetrieveTransferParametersAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveTransferParameters() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse response = client.RetrieveTransferParameters(request.Location, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveTransferParametersAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveTransferParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse responseCallSettings = await client.RetrieveTransferParametersAsync(request.Location, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveTransferParametersResponse responseCancellationToken = await client.RetrieveTransferParametersAsync(request.Location, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveTransferParametersResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParameters(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse response = client.RetrieveTransferParameters(request.LocationAsLocationName, request.DomainName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveTransferParametersResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveTransferParametersRequest request = new RetrieveTransferParametersRequest { DomainName = "domain_nameea17a44f", LocationAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; RetrieveTransferParametersResponse expectedResponse = new RetrieveTransferParametersResponse { TransferParameters = new TransferParameters(), }; mockGrpcClient.Setup(x => x.RetrieveTransferParametersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<RetrieveTransferParametersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); RetrieveTransferParametersResponse responseCallSettings = await client.RetrieveTransferParametersAsync(request.LocationAsLocationName, request.DomainName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); RetrieveTransferParametersResponse responseCancellationToken = await client.RetrieveTransferParametersAsync(request.LocationAsLocationName, request.DomainName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRegistrationRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration response = client.GetRegistration(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRegistrationRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Registration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration responseCallSettings = await client.GetRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Registration responseCancellationToken = await client.GetRegistrationAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRegistration() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration response = client.GetRegistration(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRegistrationAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Registration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration responseCallSettings = await client.GetRegistrationAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Registration responseCancellationToken = await client.GetRegistrationAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRegistrationResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistration(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration response = client.GetRegistration(request.RegistrationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRegistrationResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegistrationRequest request = new GetRegistrationRequest { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; Registration expectedResponse = new Registration { RegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), DomainName = "domain_nameea17a44f", CreateTime = new wkt::Timestamp(), ExpireTime = new wkt::Timestamp(), State = Registration.Types.State.Suspended, Issues = { Registration.Types.Issue.UnverifiedEmail, }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, ManagementSettings = new ManagementSettings(), DnsSettings = new DnsSettings(), ContactSettings = new ContactSettings(), PendingContactSettings = new ContactSettings(), SupportedPrivacy = { ContactPrivacy.PublicContactData, }, }; mockGrpcClient.Setup(x => x.GetRegistrationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Registration>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); Registration responseCallSettings = await client.GetRegistrationAsync(request.RegistrationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Registration responseCancellationToken = await client.GetRegistrationAsync(request.RegistrationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveAuthorizationCodeRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.RetrieveAuthorizationCode(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveAuthorizationCodeRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.RetrieveAuthorizationCodeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.RetrieveAuthorizationCodeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveAuthorizationCode() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.RetrieveAuthorizationCode(request.Registration); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveAuthorizationCodeAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.RetrieveAuthorizationCodeAsync(request.Registration, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.RetrieveAuthorizationCodeAsync(request.Registration, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void RetrieveAuthorizationCodeResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.RetrieveAuthorizationCode(request.RegistrationAsRegistrationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task RetrieveAuthorizationCodeResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); RetrieveAuthorizationCodeRequest request = new RetrieveAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.RetrieveAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.RetrieveAuthorizationCodeAsync(request.RegistrationAsRegistrationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.RetrieveAuthorizationCodeAsync(request.RegistrationAsRegistrationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResetAuthorizationCodeRequestObject() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.ResetAuthorizationCode(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResetAuthorizationCodeRequestObjectAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.ResetAuthorizationCodeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.ResetAuthorizationCodeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResetAuthorizationCode() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.ResetAuthorizationCode(request.Registration); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResetAuthorizationCodeAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.ResetAuthorizationCodeAsync(request.Registration, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.ResetAuthorizationCodeAsync(request.Registration, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResetAuthorizationCodeResourceNames() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCode(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode response = client.ResetAuthorizationCode(request.RegistrationAsRegistrationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResetAuthorizationCodeResourceNamesAsync() { moq::Mock<Domains.DomainsClient> mockGrpcClient = new moq::Mock<Domains.DomainsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResetAuthorizationCodeRequest request = new ResetAuthorizationCodeRequest { RegistrationAsRegistrationName = RegistrationName.FromProjectLocationRegistration("[PROJECT]", "[LOCATION]", "[REGISTRATION]"), }; AuthorizationCode expectedResponse = new AuthorizationCode { Code = "code946733c1", }; mockGrpcClient.Setup(x => x.ResetAuthorizationCodeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AuthorizationCode>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DomainsClient client = new DomainsClientImpl(mockGrpcClient.Object, null); AuthorizationCode responseCallSettings = await client.ResetAuthorizationCodeAsync(request.RegistrationAsRegistrationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); AuthorizationCode responseCancellationToken = await client.ResetAuthorizationCodeAsync(request.RegistrationAsRegistrationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using ModestTree.Util; namespace Zenject { public interface ITrigger { } public interface ISignal { } // Zero Parameters public abstract class Signal : ISignal { public event Action Event = delegate {}; public abstract class TriggerBase : ITrigger { [Inject] Signal _signal = null; public event Action Event { add { _signal.Event += value; } remove { _signal.Event -= value; } } public void Fire() { _signal.Event(); } } } // One Parameter public abstract class Signal<TParam1> : ISignal { public event Action<TParam1> Event = delegate {}; public abstract class TriggerBase : ITrigger { [Inject] Signal<TParam1> _signal = null; public event Action<TParam1> Event { add { _signal.Event += value; } remove { _signal.Event -= value; } } public void Fire(TParam1 arg1) { _signal.Event(arg1); } } } // Two Parameters public abstract class Signal<TParam1, TParam2> : ISignal { public event Action<TParam1, TParam2> Event = delegate {}; public abstract class TriggerBase : ITrigger { [Inject] Signal<TParam1, TParam2> _signal = null; public event Action<TParam1, TParam2> Event { add { _signal.Event += value; } remove { _signal.Event -= value; } } public void Fire(TParam1 arg1, TParam2 arg2) { _signal.Event(arg1, arg2); } } } // Three Parameters public abstract class Signal<TParam1, TParam2, TParam3> : ISignal { public event Action<TParam1, TParam2, TParam3> Event = delegate {}; public abstract class TriggerBase : ITrigger { [Inject] Signal<TParam1, TParam2, TParam3> _signal = null; public event Action<TParam1, TParam2, TParam3> Event { add { _signal.Event += value; } remove { _signal.Event -= value; } } public void Fire(TParam1 arg1, TParam2 arg2, TParam3 arg3) { _signal.Event(arg1, arg2, arg3); } } } // Four Parameters public abstract class Signal<TParam1, TParam2, TParam3, TParam4> : ISignal { public event Action<TParam1, TParam2, TParam3, TParam4> Event = delegate {}; public abstract class TriggerBase : ITrigger { [Inject] Signal<TParam1, TParam2, TParam3, TParam4> _signal = null; public event Action<TParam1, TParam2, TParam3, TParam4> Event { add { _signal.Event += value; } remove { _signal.Event -= value; } } public void Fire(TParam1 arg1, TParam2 arg2, TParam3 arg3, TParam4 arg4) { _signal.Event(arg1, arg2, arg3, arg4); } } } // Five Parameters public abstract class Signal<TParam1, TParam2, TParam3, TParam4, TParam5> : ISignal { public event ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5> Event = delegate {}; public abstract class TriggerBase : ITrigger { [Inject] Signal<TParam1, TParam2, TParam3, TParam4, TParam5> _signal = null; public event ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5> Event { add { _signal.Event += value; } remove { _signal.Event -= value; } } public void Fire(TParam1 arg1, TParam2 arg2, TParam3 arg3, TParam4 arg4, TParam5 arg5) { _signal.Event(arg1, arg2, arg3, arg4, arg5); } } } // Six Parameters public abstract class Signal<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> : ISignal { public event ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> Event = delegate {}; public abstract class TriggerBase : ITrigger { [Inject] Signal<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> _signal = null; public event ModestTree.Util.Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> Event { add { _signal.Event += value; } remove { _signal.Event -= value; } } public void Fire(TParam1 arg1, TParam2 arg2, TParam3 arg3, TParam4 arg4, TParam5 arg5, TParam6 arg6) { _signal.Event(arg1, arg2, arg3, arg4, arg5, arg6); } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Globalization; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _token; private object _value; private Type _valueType; private char _quoteChar; private State _currentState; private JTokenType _currentTypeContext; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } private int _top; private readonly List<JTokenType> _stack; /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Gets the type of the current Json token. /// </summary> public virtual JsonToken TokenType { get { return _token; } } /// <summary> /// Gets the text value of the current Json token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current Json token. /// </summary> public virtual Type ValueType { get { return _valueType; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = _top - 1; if (IsStartToken(TokenType)) return depth - 1; else return depth; } } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _stack = new List<JTokenType>(); Push(JTokenType.None); } private void Push(JTokenType value) { _stack.Add(value); _top++; _currentTypeContext = value; } private JTokenType Pop() { JTokenType value = Peek(); _stack.RemoveAt(_stack.Count - 1); _top--; _currentTypeContext = _stack[_top - 1]; return value; } private JTokenType Peek() { return _currentTypeContext; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns>A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null.</returns> public abstract byte[] ReadAsBytes(); /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected virtual void SetToken(JsonToken newToken, object value) { _token = newToken; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JTokenType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JTokenType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JTokenType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); _currentState = State.PostValue; break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); _currentState = State.PostValue; break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); _currentState = State.PostValue; break; case JsonToken.PropertyName: _currentState = State.Property; Push(JTokenType.Property); break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: _currentState = State.PostValue; break; } JTokenType current = Peek(); if (current == JTokenType.Property && _currentState == State.PostValue) Pop(); if (value != null) { _value = value; _valueType = value.GetType(); } else { _value = null; _valueType = null; } } private void ValidateEnd(JsonToken endToken) { JTokenType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) throw new JsonReaderException("JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JTokenType currentObject = Peek(); switch (currentObject) { case JTokenType.Object: _currentState = State.Object; break; case JTokenType.Array: _currentState = State.Array; break; case JTokenType.Constructor: _currentState = State.Constructor; break; case JTokenType.None: _currentState = State.Finished; break; default: throw new JsonReaderException("While setting the reader state back to current object an unexpected JsonType was encountered: " + currentObject); } } internal static bool IsPrimitiveToken(JsonToken token) { switch (token) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Undefined: case JsonToken.Null: case JsonToken.Date: case JsonToken.Bytes: return true; default: return false; } } internal static bool IsStartToken(JsonToken token) { switch (token) { case JsonToken.StartObject: case JsonToken.StartArray: case JsonToken.StartConstructor: case JsonToken.PropertyName: return true; case JsonToken.None: case JsonToken.Comment: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.EndObject: case JsonToken.EndArray: case JsonToken.EndConstructor: case JsonToken.Date: case JsonToken.Raw: case JsonToken.Bytes: return false; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("token", token, "Unexpected JsonToken value."); } } private JTokenType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JTokenType.Object; case JsonToken.EndArray: return JTokenType.Array; case JsonToken.EndConstructor: return JTokenType.Constructor; default: throw new JsonReaderException("Not a valid close JsonToken: " + token); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) Close(); } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _token = JsonToken.None; _value = null; _valueType = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; namespace Orleans.Streams { [Serializable] internal class PubSubGrainState { public HashSet<PubSubPublisherState> Producers { get; set; } public HashSet<PubSubSubscriptionState> Consumers { get; set; } } [Providers.StorageProvider(ProviderName = "PubSubStore")] internal class PubSubRendezvousGrain : Grain<PubSubGrainState>, IPubSubRendezvousGrain { private Logger logger; private const bool DEBUG_PUB_SUB = false; private static readonly CounterStatistic counterProducersAdded; private static readonly CounterStatistic counterProducersRemoved; private static readonly CounterStatistic counterProducersTotal; private static readonly CounterStatistic counterConsumersAdded; private static readonly CounterStatistic counterConsumersRemoved; private static readonly CounterStatistic counterConsumersTotal; static PubSubRendezvousGrain() { counterProducersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_ADDED); counterProducersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_REMOVED); counterProducersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_PRODUCERS_TOTAL); counterConsumersAdded = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_ADDED); counterConsumersRemoved = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_REMOVED); counterConsumersTotal = CounterStatistic.FindOrCreate(StatisticNames.STREAMS_PUBSUB_CONSUMERS_TOTAL); } public override async Task OnActivateAsync() { logger = GetLogger(GetType().Name + "-" + RuntimeIdentity + "-" + IdentityString); LogPubSubCounts("OnActivateAsync"); if (State.Consumers == null) State.Consumers = new HashSet<PubSubSubscriptionState>(); if (State.Producers == null) State.Producers = new HashSet<PubSubPublisherState>(); int numRemoved = RemoveDeadProducers(); if (numRemoved > 0) { if (State.Producers.Count > 0 || State.Consumers.Count > 0) await WriteStateAsync(); else await ClearStateAsync(); //State contains no producers or consumers, remove it from storage } logger.Verbose("OnActivateAsync-Done"); } public override Task OnDeactivateAsync() { LogPubSubCounts("OnDeactivateAsync"); return TaskDone.Done; } private int RemoveDeadProducers() { // Remove only those we know for sure are Dead. int numRemoved = 0; if (State.Producers != null && State.Producers.Count > 0) numRemoved = State.Producers.RemoveWhere(producerState => IsDeadProducer(producerState.Producer)); if (numRemoved > 0) { LogPubSubCounts("RemoveDeadProducers: removed {0} outdated producers", numRemoved); } return numRemoved; } /// accept and notify only Active producers. private static bool IsActiveProducer(IStreamProducerExtension producer) { var grainRef = producer as GrainReference; if (grainRef !=null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget) return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Active); return true; } private static bool IsDeadProducer(IStreamProducerExtension producer) { var grainRef = producer as GrainReference; if (grainRef != null && grainRef.GrainId.IsSystemTarget && grainRef.IsInitializedSystemTarget) return RuntimeClient.Current.GetSiloStatus(grainRef.SystemTargetSilo).Equals(SiloStatus.Dead); return false; } public async Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersAdded.Increment(); if (!IsActiveProducer(streamProducer)) throw new ArgumentException($"Trying to register non active IStreamProducerExtension: {streamProducer}", "streamProducer"); try { int producersRemoved = RemoveDeadProducers(); var publisherState = new PubSubPublisherState(streamId, streamProducer); State.Producers.Add(publisherState); LogPubSubCounts("RegisterProducer {0}", streamProducer); await WriteStateAsync(); counterProducersTotal.DecrementBy(producersRemoved); counterProducersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterProducerFailed, $"Failed to register a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } return State.Consumers.Where(c => !c.IsFaulted).ToSet(); } public async Task UnregisterProducer(StreamId streamId, IStreamProducerExtension streamProducer) { counterProducersRemoved.Increment(); try { int numRemoved = State.Producers.RemoveWhere(s => s.Equals(streamId, streamProducer)); LogPubSubCounts("UnregisterProducer {0} NumRemoved={1}", streamProducer, numRemoved); if (numRemoved > 0) { Task updateStorageTask = State.Producers.Count == 0 && State.Consumers.Count == 0 ? ClearStateAsync() //State contains no producers or consumers, remove it from storage : WriteStateAsync(); await updateStorageTask; } counterProducersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnegisterProducerFailed, $"Failed to unregister a stream producer. Stream: {streamId}, Producer: {streamProducer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } if (State.Producers.Count == 0 && State.Consumers.Count == 0) { DeactivateOnIdle(); // No producers or consumers left now, so flag ourselves to expedite Deactivation } } public async Task RegisterConsumer( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { counterConsumersAdded.Increment(); PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState != null && pubSubState.IsFaulted) throw new FaultedSubscriptionException(subscriptionId, streamId); try { if (pubSubState == null) { pubSubState = new PubSubSubscriptionState(subscriptionId, streamId, streamConsumer); State.Consumers.Add(pubSubState); } if (filter != null) pubSubState.AddFilter(filter); LogPubSubCounts("RegisterConsumer {0}", streamConsumer); await WriteStateAsync(); counterConsumersTotal.Increment(); } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } int numProducers = State.Producers.Count; if (numProducers <= 0) return; if (logger.IsVerbose) logger.Info("Notifying {0} existing producer(s) about new consumer {1}. Producers={2}", numProducers, streamConsumer, Utils.EnumerableToString(State.Producers)); // Notify producers about a new streamConsumer. var tasks = new List<Task>(); var producers = State.Producers.ToList(); int initialProducerCount = producers.Count; try { foreach (var producerState in producers) { PubSubPublisherState producer = producerState; // Capture loop variable if (!IsActiveProducer(producer.Producer)) { // Producer is not active (could be stopping / shutting down) so skip if (logger.IsVerbose) logger.Verbose("Producer {0} on stream {1} is not active - skipping.", producer, streamId); continue; } tasks.Add(NotifyProducer(producer, subscriptionId, streamId, streamConsumer, filter)); } Exception exception = null; try { await Task.WhenAll(tasks); } catch (Exception exc) { exception = exc; } // if the number of producers has been changed, resave state. if (State.Producers.Count != initialProducerCount) { await WriteStateAsync(); counterConsumersTotal.DecrementBy(initialProducerCount - State.Producers.Count); } if (exception != null) { throw exception; } } catch (Exception exc) { logger.Error(ErrorCode.Stream_RegisterConsumerFailed, $"Failed to update producers while register a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}, Consumer: {streamConsumer}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private async Task NotifyProducer(PubSubPublisherState producer, GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { try { await producer.Producer.AddSubscriber(subscriptionId, streamId, streamConsumer, filter); } catch (GrainExtensionNotInstalledException) { RemoveProducer(producer); } catch (ClientNotAvailableException) { RemoveProducer(producer); } } private void RemoveProducer(PubSubPublisherState producer) { logger.Warn(ErrorCode.Stream_ProducerIsDead, "Producer {0} on stream {1} is no longer active - permanently removing producer.", producer, producer.Stream); State.Producers.Remove(producer); } public async Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId) { counterConsumersRemoved.Increment(); if (State.Consumers.Any(c => c.IsFaulted && c.Equals(subscriptionId))) throw new FaultedSubscriptionException(subscriptionId, streamId); try { int numRemoved = State.Consumers.RemoveWhere(c => c.Equals(subscriptionId)); LogPubSubCounts("UnregisterSubscription {0} NumRemoved={1}", subscriptionId, numRemoved); if (await TryClearState()) { // If state was cleared expedite Deactivation DeactivateOnIdle(); } else { if (numRemoved != 0) { await WriteStateAsync(); } await NotifyProducersOfRemovedSubscription(subscriptionId, streamId); } counterConsumersTotal.DecrementBy(numRemoved); } catch (Exception exc) { logger.Error(ErrorCode.Stream_UnregisterConsumerFailed, $"Failed to unregister a stream consumer. Stream: {streamId}, SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } public Task<int> ProducerCount(StreamId streamId) { return Task.FromResult(State.Producers.Count); } public Task<int> ConsumerCount(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId).Length); } public Task<PubSubSubscriptionState[]> DiagGetConsumers(StreamId streamId) { return Task.FromResult(GetConsumersForStream(streamId)); } private PubSubSubscriptionState[] GetConsumersForStream(StreamId streamId) { return State.Consumers.Where(c => !c.IsFaulted && c.Stream.Equals(streamId)).ToArray(); } private void LogPubSubCounts(string fmt, params object[] args) { if (logger.IsVerbose || DEBUG_PUB_SUB) { int numProducers = 0; int numConsumers = 0; if (State?.Producers != null) numProducers = State.Producers.Count; if (State?.Consumers != null) numConsumers = State.Consumers.Count; string when = args != null && args.Length != 0 ? String.Format(fmt, args) : fmt; logger.Info("{0}. Now have total of {1} producers and {2} consumers. All Consumers = {3}, All Producers = {4}", when, numProducers, numConsumers, Utils.EnumerableToString(State.Consumers), Utils.EnumerableToString(State.Producers)); } } // Check that what we have cached locally matches what is in the persistent table. public async Task Validate() { var captureProducers = State.Producers; var captureConsumers = State.Consumers; await ReadStateAsync(); if (captureProducers.Count != State.Producers.Count) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers.Count={captureProducers.Count}, State.Producers.Count={State.Producers.Count}"); } if (captureProducers.Any(producer => !State.Producers.Contains(producer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureProducers={Utils.EnumerableToString(captureProducers)}, State.Producers={Utils.EnumerableToString(State.Producers)}"); } if (captureConsumers.Count != State.Consumers.Count) { LogPubSubCounts("Validate: Consumer count mismatch"); throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers.Count={captureConsumers.Count}, State.Consumers.Count={State.Consumers.Count}"); } if (captureConsumers.Any(consumer => !State.Consumers.Contains(consumer))) { throw new OrleansException( $"State mismatch between PubSubRendezvousGrain and its persistent state. captureConsumers={Utils.EnumerableToString(captureConsumers)}, State.Consumers={Utils.EnumerableToString(State.Consumers)}"); } } public Task<List<GuidId>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer) { List<GuidId> subscriptionIds = State.Consumers.Where(c => !c.IsFaulted && c.Consumer.Equals(streamConsumer)) .Select(c => c.SubscriptionId) .ToList(); return Task.FromResult(subscriptionIds); } public async Task FaultSubscription(GuidId subscriptionId) { PubSubSubscriptionState pubSubState = State.Consumers.FirstOrDefault(s => s.Equals(subscriptionId)); if (pubSubState == null) { return; } try { pubSubState.Fault(); if (logger.IsVerbose) logger.Verbose("Setting subscription {0} to a faulted state.", subscriptionId.Guid); await WriteStateAsync(); await NotifyProducersOfRemovedSubscription(pubSubState.SubscriptionId, pubSubState.Stream); } catch (Exception exc) { logger.Error(ErrorCode.Stream_SetSubscriptionToFaultedFailed, $"Failed to set subscription state to faulted. SubscriptionId {subscriptionId}", exc); // Corrupted state, deactivate grain. DeactivateOnIdle(); throw; } } private async Task NotifyProducersOfRemovedSubscription(GuidId subscriptionId, StreamId streamId) { int numProducers = State.Producers.Count; if (numProducers > 0) { if (logger.IsVerbose) logger.Verbose("Notifying {0} existing producers about unregistered consumer.", numProducers); // Notify producers about unregistered consumer. List<Task> tasks = State.Producers.Where(producerState => IsActiveProducer(producerState.Producer)) .Select(producerState => producerState.Producer.RemoveSubscriber(subscriptionId, streamId)) .ToList(); await Task.WhenAll(tasks); } } /// <summary> /// Try clear state will only clear the state if there are no producers or consumers. /// </summary> /// <returns></returns> private async Task<bool> TryClearState() { if (State.Producers.Count == 0 && State.Consumers.Count == 0) // + we already know that numProducers == 0 from previous if-clause { await ClearStateAsync(); //State contains no producers or consumers, remove it from storage return true; } return false; } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: $ * $Date: $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; using System.Globalization; using System.Text; namespace IBatisNet.Common.Logging.Impl { /// <summary> /// Logger sending everything to the trace output stream. /// </summary> public class TraceLogger: ILog { private bool _showDateTime = false; private bool _showLogName = false; private string _logName = string.Empty; private LogLevel _currentLogLevel = LogLevel.All; private string _dateTimeFormat = string.Empty; private bool _hasDateTimeFormat = false; /// <summary> /// /// </summary> /// <param name="logName"></param> /// <param name="logLevel"></param> /// <param name="showDateTime">Include the current time in the log message </param> /// <param name="showLogName">Include the instance name in the log message</param> /// <param name="dateTimeFormat">The date and time format to use in the log message </param> public TraceLogger( string logName, LogLevel logLevel , bool showDateTime, bool showLogName, string dateTimeFormat) { _logName = logName; _currentLogLevel = logLevel; _showDateTime = showDateTime; _showLogName = showLogName; _dateTimeFormat = dateTimeFormat; if (_dateTimeFormat != null && _dateTimeFormat.Length > 0) { _hasDateTimeFormat = true; } } /// <summary> /// Do the actual logging. /// This method assembles the message and write /// the content of the message accumulated in the specified /// StringBuffer to the appropriate output destination. The /// default implementation writes to System.Console.Error.<p/> /// </summary> /// <param name="level"></param> /// <param name="message"></param> /// <param name="e"></param> private void Write( LogLevel level, object message, Exception e ) { // Use a StringBuilder for better performance StringBuilder sb = new StringBuilder(); // Append date-time if so configured if ( _showDateTime ) { if ( _hasDateTimeFormat ) { sb.Append( DateTime.Now.ToString( _dateTimeFormat, CultureInfo.InvariantCulture )); } else { sb.Append( DateTime.Now ); } sb.Append( " " ); } // Append a readable representation of the log level sb.Append( string.Format( "[{0}]", level.ToString().ToUpper() ).PadRight( 8 ) ); // Append the name of the log instance if so configured if ( _showLogName ) { sb.Append( _logName ).Append( " - " ); } // Append the message sb.Append( message.ToString() ); // Append stack trace if not null if ( e != null ) { sb.AppendFormat( "\n{0}", e.ToString() ); } // Print to the appropriate destination System.Diagnostics.Trace.WriteLine( sb.ToString() ); } /// <summary> /// Is the given log level currently enabled ? /// </summary> /// <param name="level"></param> /// <returns></returns> private bool IsLevelEnabled( LogLevel level ) { int iLevel = (int)level; int iCurrentLogLevel = (int)_currentLogLevel; return ( iLevel >= iCurrentLogLevel ); } #region ILog Members /// <summary> /// Log a debug message. /// </summary> /// <param name="message"></param> public void Debug(object message) { Debug( message, null ); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="e"></param> public void Debug(object message, Exception e) { if ( IsLevelEnabled( LogLevel.Debug ) ) { Write( LogLevel.Debug, message, e ); } } /// <summary> /// /// </summary> /// <param name="message"></param> public void Error(object message) { Error( message, null ); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="e"></param> public void Error(object message, Exception e) { if ( IsLevelEnabled( LogLevel.Error ) ) { Write( LogLevel.Error, message, e ); } } /// <summary> /// /// </summary> /// <param name="message"></param> public void Fatal(object message) { Fatal( message, null ); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="e"></param> public void Fatal(object message, Exception e) { if ( IsLevelEnabled( LogLevel.Fatal ) ) { Write( LogLevel.Fatal, message, e ); } } /// <summary> /// /// </summary> /// <param name="message"></param> public void Info(object message) { Info( message, null ); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="e"></param> public void Info(object message, Exception e) { if ( IsLevelEnabled( LogLevel.Info ) ) { Write( LogLevel.Info, message, e ); } } /// <summary> /// /// </summary> /// <param name="message"></param> public void Warn(object message) { Warn( message, null ); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="e"></param> public void Warn(object message, Exception e) { if ( IsLevelEnabled( LogLevel.Warn ) ) { Write( LogLevel.Warn, message, e ); } } /// <summary> /// /// </summary> public bool IsDebugEnabled { get { return IsLevelEnabled( LogLevel.Debug ); } } /// <summary> /// /// </summary> public bool IsErrorEnabled { get { return IsLevelEnabled( LogLevel.Error ); } } /// <summary> /// /// </summary> public bool IsFatalEnabled { get { return IsLevelEnabled( LogLevel.Fatal ); } } /// <summary> /// /// </summary> public bool IsInfoEnabled { get { return IsLevelEnabled( LogLevel.Info ); } } /// <summary> /// /// </summary> public bool IsWarnEnabled { get { return IsLevelEnabled( LogLevel.Warn ); } } #endregion } }
using System; using HBus.Utilities; namespace HBus { /// <summary> /// Message type (part of flags byte) /// </summary> public enum MessageTypes { Normal = 0, Immediate = 1, AckResponse = 2, NackResponse = 3 } /// <summary> /// Message payload values /// </summary> public enum Payload { // ReSharper disable InconsistentNaming Bytes_0 = 0x00, Bytes_1 = 0x10, Bytes_2 = 0x20, Bytes_3 = 0x30, Bytes_4 = 0x40, Bytes_5 = 0x50, Bytes_6 = 0x60, Bytes_7 = 0x70, Bytes_8 = 0x80, Bytes_16 = 0x90, Bytes_32 = 0xA0, Bytes_64 = 0xB0, Bytes_128 = 0xC0, Bytes_256 = 0xD0, Bytes_512 = 0xE0, UserDefined = 0xF0 } /// <summary> /// External received message handler /// </summary> /// <param name="sender">Sender of message</param> /// <param name="args">Message arguments</param> public delegate void MessageHandler(object sender, MessageEventArgs args); /// <summary> /// Message arguments for event handler /// </summary> public class MessageEventArgs : EventArgs { //public string HwAddress { get; set; } public MessageEventArgs(Message message, int port) { Message = message; Port = port; //HwAddress = hwAddress; } public Message Message { get; set; } public int Port { get; set; } public override string ToString() { return string.Format("arg(message) = {0} from connector {1}", Message, Port); } } /// <summary> /// Home bus message packet /// Start = START_BYTE /// Flags = 7 6 5 4 3 2 1 0 /// 7 = PAYLOAD_3 /// 6 = PAYLOAD_2 /// 5 = PAYLOAD_1 /// 4 = PAYLOAD_0 /// 3 = ADDRESS_WIDTH_1 /// 2 = ADDRESS_WIDTH_0 /// 1 = MSG_TYPE_BIT_1 /// 0 = MSG_TYPE_BIT_0 /// PAYLOAD = PAYLOAD DATA LENGTH /// 0x00 = 0 bytes /// ... /// 0x80 = 8 bytes /// 0x90 = 16 bytes /// 0xA0 = 32 bytes /// 0xB0 = 64 bytes /// 0xC0 = 128 bytes /// 0xD0 = 256 bytes /// 0xE0 = 512 bytes /// 0xF0 = user defined length (2 bytes following) /// ADDRESS_WIDTH = Destination/source address width /// 0x00 (0000) = 0 byte (direct connection) /// 0x04 (0100) = 1 byte (255 addressable devices) /// 0x08 (1000) = 2 bytes (65535 addressable devices) /// 0x0C (1100) = 4 bytes (full address range (could be overlapped with other standards (ip, knx, etc). /// MSG_TYPES = 00 = NORMAL MESSAGE (WITH ACK RESPONSE) /// 01 = IMMEDIATE MESSAGE (WITHOUT ACK RESPONSE) /// 02 = ACK RESPONSE /// 03 = NACK_RESPONSE /// CRC is calculated on all bytes (excluding crc itself). /// </summary> public class Message { #region protected properties protected static int MinLength { get { return 5; //Start + Flags + Command + 2 * Crc } } protected static byte StartByte { get { return 0xAA; } } #endregion #region public properties //public const byte MessageLength = 5; //START + FLAGS + COMMAND + CRC x 2 public byte Start { get; protected set; } public byte Flags { get; protected set; } public Address Source { get; protected set; } public Address Destination { get; protected set; } public byte Command { get; protected set; } public byte[] Data { get; protected set; } public ushort Crc { get; protected set; } #endregion #region flags //Flags explained public Payload PayloadLength { get { return (Payload) (Flags & 0xF0); } } public AddressWidth AddressWidth { get { return (AddressWidth) (Flags & 0x0C); } } public MessageTypes MessageType { get { return (MessageTypes) (Flags & 0x03); } } #endregion #region constructors public Message(MessageTypes type, Address destination, Address source, byte command, byte[] data) { Start = StartByte; AddressWidth width; if ((destination == Address.Empty) || (source == Address.Empty)) width = AddressWidth.NoAddress; else width = Address.Width; //get payload var payload = LengthToPayload(data != null ? data.Length : 0); Flags = (byte) ((byte) type | (byte) width | (byte) payload); Destination = width != AddressWidth.NoAddress ? destination : Address.Empty; Source = width != AddressWidth.NoAddress ? source : Address.Empty; Command = command; Data = data; //Reset crc Crc = 0; } /// <summary> /// Default constructor /// </summary> /// <param name="buffer">buffer data</param> /// <param name="size">Buffer size</param> /// <param name="offset">Buffer start index</param> /// <exception cref="ArgumentException">Thrown when buffer size is wrong</exception> public Message(byte[] buffer, ref int size, ref int offset) { var oldOffset = offset; if ((buffer == null) || (buffer.Length < HBusSettings.MessageLength)) throw new ArgumentException("wrong buffer size"); //var array = new byte[length]; //if (length > 0 && buffer.Length > length) // Array.Copy(buffer, 0, array, 0, length); //else // array = buffer; Start = buffer[offset++]; Flags = buffer[offset++]; var payload = (Payload) (Flags & 0xF0); var width = (AddressWidth) (Flags & 0x0C); var dataLength = PayloadToLength(payload); //Set user Length if (dataLength < 0) dataLength = (buffer[offset++] << 8) | buffer[offset++]; //Set destination & source switch (width) { case AddressWidth.NoAddress: Destination = Address.Empty; Source = Address.Empty; break; case AddressWidth.OneByte: Destination = new Address(buffer[offset++]); Source = new Address(buffer[offset++]); break; case AddressWidth.TwoBytes: Destination = new Address((uint) (buffer[offset++] << 8) | buffer[offset++]); Source = new Address((uint) (buffer[offset++] << 8) | buffer[offset++]); break; case AddressWidth.FourBytes: Destination = new Address( (uint) ((buffer[offset++] << 24) | (buffer[offset++] << 16) | (buffer[offset++] << 8) | buffer[offset++])); Source = new Address( (uint) ((buffer[offset++] << 24) | (buffer[offset++] << 16) | (buffer[offset++] << 8) | buffer[offset++])); break; } //Set command Command = buffer[offset++]; if (dataLength > 0) { Data = new byte[dataLength]; for (var i = 0; i < dataLength; i++) Data[i] = buffer[offset + i]; offset += dataLength; } Crc = (ushort) ((buffer[offset++] << 8) | buffer[offset++]); //_readIndex = 0; size = offset - oldOffset; } #endregion #region methods /// <summary> /// Convert packet to buffer array /// </summary> /// <returns></returns> public byte[] ToArray() { var index = 0; //Set length var length = HBusSettings.MessageLength + (Data != null ? Data.Length : 0); if (AddressWidth == AddressWidth.OneByte) length += 2; if (AddressWidth == AddressWidth.TwoBytes) length += 4; if (AddressWidth == AddressWidth.FourBytes) length += 8; var lengthPayload = Data != null ? LengthToPayload(Data.Length) : Payload.Bytes_0; if (PayloadLength != lengthPayload) Flags = (byte) ((byte) AddressWidth | (byte) lengthPayload | (byte) MessageType); if (PayloadLength == Payload.UserDefined) length += 2; var buffer = new byte[length]; buffer[index++] = StartByte; buffer[index++] = Flags; if ((Data != null) && (lengthPayload == Payload.UserDefined)) { //Add data length buffer[index++] = (byte) ((Data.Length >> 8) & 0xff); buffer[index++] = (byte) (Data.Length & 0xff); } //Add destination & source //Set destination & source switch (AddressWidth) { case AddressWidth.OneByte: buffer[index++] = (byte) Destination.Value; buffer[index++] = (byte) Source.Value; break; case AddressWidth.TwoBytes: buffer[index++] = (byte) (Destination.Value >> 8); buffer[index++] = (byte) (Destination.Value & 0xff); buffer[index++] = (byte) (Source.Value >> 8); buffer[index++] = (byte) (Source.Value & 0xff); break; case AddressWidth.FourBytes: buffer[index++] = (byte) (Destination.Value >> 24); buffer[index++] = (byte) (Destination.Value >> 16); buffer[index++] = (byte) (Destination.Value >> 8); buffer[index++] = (byte) (Destination.Value & 0xff); buffer[index++] = (byte) (Source.Value >> 24); buffer[index++] = (byte) (Source.Value >> 16); buffer[index++] = (byte) (Source.Value >> 8); buffer[index++] = (byte) (Source.Value & 0xff); break; } //Add command buffer[index++] = Command; //Add payload if (Data != null) { for (var i = 0; i < Data.Length; i++) buffer[index + i] = Data[i]; index += Data.Length; } var crc = Crc != 0 ? Crc : Crc16.XModemCrc(ref buffer, 0, buffer.Length - 2); buffer[index++] = (byte) ((crc >> 8) & 0xFF); buffer[index] = (byte) (crc & 0xFF); //Return buffer array return buffer; } /// <summary> /// Convert message to string /// </summary> /// <returns></returns> public override string ToString() { return string.Format("{0} @{1} => {2}", MessageType, Source, Destination); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(Message)) return false; return Equals((Message) obj); } public bool Equals(Message other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return (other.Start == Start) && (other.Flags == Flags) && other.Source.Equals(Source) && other.Destination.Equals(Destination) && (other.Command == Command) && Equals(other.Data, Data); } public override int GetHashCode() { unchecked { var result = Start.GetHashCode(); result = (result*397) ^ Flags.GetHashCode(); result = (result*397) ^ Source.GetHashCode(); result = (result*397) ^ Destination.GetHashCode(); result = (result*397) ^ Command.GetHashCode(); result = (result*397) ^ (Data != null ? Data.GetHashCode() : 0); return result; } } public static bool operator ==(Message left, Message right) { return Equals(left, right); } public static bool operator !=(Message left, Message right) { return !Equals(left, right); } public static Message Parse(byte[] data, ref int length, ref int index) { //-------------------------------- //Check length //-------------------------------- if ((data == null) || (data.Length < MinLength)) return null; //-------------------------------- //Check start //-------------------------------- if (data[index] != StartByte) return null; Message msg; try { msg = new Message(data, ref length, ref index); } catch (Exception) { return null; } //-------------------------------- //return message //-------------------------------- return msg; } #endregion #region private methods private int PayloadToLength(Payload payload) { //Set Length if (payload < Payload.Bytes_16) return (byte) payload >> 4; //Fixed length switch (payload) { case Payload.Bytes_16: return 16; case Payload.Bytes_32: return 32; case Payload.Bytes_64: return 64; case Payload.Bytes_128: return 128; case Payload.Bytes_256: return 256; case Payload.Bytes_512: return 512; } return -1; } private Payload LengthToPayload(int length) { //Set Length if (length < 9) return (Payload) (length << 4); //Fixed lengths if (length == 16) return Payload.Bytes_16; if (length == 32) return Payload.Bytes_32; if (length == 64) return Payload.Bytes_64; if (length == 128) return Payload.Bytes_128; if (length == 256) return Payload.Bytes_256; if (length == 512) return Payload.Bytes_512; return Payload.UserDefined; } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.NestedTypesShouldNotBeVisibleAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.NestedTypesShouldNotBeVisibleAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class NestedTypesShouldNotBeVisibleTests { [Fact] public async Task CSharpDiagnosticPublicNestedClassAsync() { var code = @" public class Outer { public class Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpCA1034ResultAt(4, 18, "Inner")); } [Fact] public async Task BasicDiagnosticPublicNestedClassAsync() { var code = @" Public Class Outer Public Class Inner End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicCA1034ResultAt(3, 18, "Inner")); } [Fact] public async Task CSharpDiagnosticPublicNestedStructAsync() { var code = @" public class Outer { public struct Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpCA1034ResultAt(4, 19, "Inner")); } [Fact] public async Task BasicDiagnosticPublicNestedStructureAsync() { var code = @" Public Class Outer Public Structure Inner End Structure End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicCA1034ResultAt(3, 22, "Inner")); } [Fact] public async Task CSharpNoDiagnosticPublicNestedEnumAsync() { var code = @" public class Outer { public enum Inner { None = 0 } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticPublicNestedEnumAsync() { var code = @" Public Class Outer Public Enum Inner None = 0 End Enum End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicDiagnosticPublicTypeNestedInModuleAsync() { var code = @" Public Module Outer Public Class Inner End Class End Module "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicCA1034ModuleResultAt(3, 18, "Inner")); } [Fact, WorkItem(1347, "https://github.com/dotnet/roslyn-analyzers/issues/1347")] public async Task CSharpDiagnosticPublicNestedDelegateAsync() { var code = @" public class Outer { public delegate void Inner(); } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact, WorkItem(1347, "https://github.com/dotnet/roslyn-analyzers/issues/1347")] public async Task BasicDiagnosticPublicNestedDelegateAsync() { var code = @" Public Class Outer Delegate Sub Inner() End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticPrivateNestedTypeAsync() { var code = @" public class Outer { private class Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticPrivateNestedTypeAsync() { var code = @" Public Class Outer Private Class Inner End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticProtectedNestedTypeAsync() { var code = @" public class Outer { protected class Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticProtectedNestedTypeAsync() { var code = @" Public Class Outer Protected Class Inner End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticInternalNestedTypeAsync() { var code = @" public class Outer { internal class Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticFriendNestedTypeAsync() { var code = @" Public Class Outer Friend Class Inner End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticProtectedOrInternalNestedTypeAsync() { var code = @" public class Outer { protected internal class Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticProtectedOrFriendNestedTypeAsync() { var code = @" Public Class Outer Protected Friend Class Inner End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticNonPublicTypeNestedInModuleAsync() { var code = @" Public Module Outer Friend Class Inner End Class End Module "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticPublicNestedEnumeratorAsync() { var code = @" using System.Collections; public class Outer { public class MyEnumerator: IEnumerator { public bool MoveNext() { return true; } public object Current { get; } = null; public void Reset() {} } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticPublicTypeNestedInInternalTypeAsync() { var code = @" internal class Outer { public class Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticPublicTypeNestedInFriendTypeAsync() { var code = @" Friend Class Outer Public Class Inner End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticPublicNestedEnumeratorAsync() { var code = @" Imports System Imports System.Collections Public Class Outer Public Class MyEnumerator Implements IEnumerator Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext Return True End Function Public ReadOnly Property Current As Object Implements IEnumerator.Current Get Return Nothing End Get End Property Public Sub Reset() Implements IEnumerator.Reset End Sub End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpNoDiagnosticDataSetSpecialCasesAsync() { var code = @" using System.Data; public class MyDataSet : DataSet { public class MyDataTable : DataTable { } public class MyDataRow : DataRow { public MyDataRow(DataRowBuilder builder) : base(builder) { } } } "; await VerifyCS.VerifyAnalyzerAsync(code); } [Fact] public async Task BasicNoDiagnosticDataSetSpecialCasesAsync() { var code = @" Imports System.Data Public Class MyDataSet Inherits DataSet Public Class MyDataTable Inherits DataTable End Class Public Class MyDataRow Inherits DataRow Public Sub New(builder As DataRowBuilder) MyBase.New(builder) End Sub End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code); } [Fact] public async Task CSharpDiagnosticDataSetWithOtherNestedClassAsync() { var code = @" using System.Data; public class MyDataSet : DataSet { public class MyDataTable : DataTable { } public class MyDataRow : DataRow { public MyDataRow(DataRowBuilder builder) : base(builder) { } } public class Inner { } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpCA1034ResultAt(17, 18, "Inner")); } [Fact] public async Task BasicDiagnosticDataSetWithOtherNestedClassAsync() { var code = @" Imports System.Data Public Class MyDataSet Inherits DataSet Public Class MyDataTable Inherits DataTable End Class Public Class MyDataRow Inherits DataRow Public Sub New(builder As DataRowBuilder) MyBase.New(builder) End Sub End Class Public Class Inner End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicCA1034ResultAt(19, 18, "Inner")); } [Fact] public async Task CSharpDiagnosticNestedDataClassesWithinOtherClassAsync() { var code = @" using System.Data; public class Outer { public class MyDataTable : DataTable { } public class MyDataRow : DataRow { public MyDataRow(DataRowBuilder builder) : base(builder) { } } } "; await VerifyCS.VerifyAnalyzerAsync(code, GetCSharpCA1034ResultAt(6, 18, "MyDataTable"), GetCSharpCA1034ResultAt(10, 18, "MyDataRow")); } [Fact] public async Task BasicDiagnosticNestedDataClassesWithinOtherClassAsync() { var code = @" Imports System.Data Public Class Outer Public Class MyDataTable Inherits DataTable End Class Public Class MyDataRow Inherits DataRow Public Sub New(builder As DataRowBuilder) MyBase.New(builder) End Sub End Class End Class "; await VerifyVB.VerifyAnalyzerAsync(code, GetBasicCA1034ResultAt(5, 18, "MyDataTable"), GetBasicCA1034ResultAt(9, 18, "MyDataRow")); } public enum BuilderPatternVariant { Correct, CorrectWithNameEndsInBuilder, IncorrectWithPublicOuterConstructor, IncorrectWithProtectedOuterConstructor, IncorrectNotNamedBuilder, } [Theory, WorkItem(3033, "https://github.com/dotnet/roslyn-analyzers/issues/3033")] [InlineData(BuilderPatternVariant.Correct)] [InlineData(BuilderPatternVariant.CorrectWithNameEndsInBuilder)] [InlineData(BuilderPatternVariant.IncorrectWithPublicOuterConstructor)] [InlineData(BuilderPatternVariant.IncorrectWithProtectedOuterConstructor)] [InlineData(BuilderPatternVariant.IncorrectNotNamedBuilder)] public async Task CA1034_BuilderPatternVariantsAsync(BuilderPatternVariant variant) { string builderName = "Builder"; string outerClassCtorAccessibility = "private"; DiagnosticResult[] csharpExpectedDiagnostics = Array.Empty<DiagnosticResult>(); DiagnosticResult[] vbnetExpectedDiagnostics = Array.Empty<DiagnosticResult>(); switch (variant) { case BuilderPatternVariant.Correct: break; case BuilderPatternVariant.CorrectWithNameEndsInBuilder: builderName = "PizzaBuilder"; break; case BuilderPatternVariant.IncorrectWithPublicOuterConstructor: case BuilderPatternVariant.IncorrectWithProtectedOuterConstructor: csharpExpectedDiagnostics = new[] { GetCSharpCA1034ResultAt(13, 25, builderName), }; vbnetExpectedDiagnostics = new[] { GetBasicCA1034ResultAt(11, 33, builderName), }; outerClassCtorAccessibility = variant == BuilderPatternVariant.IncorrectWithProtectedOuterConstructor ? "protected" : "public"; break; case BuilderPatternVariant.IncorrectNotNamedBuilder: builderName = "InnerClass"; csharpExpectedDiagnostics = new[] { GetCSharpCA1034ResultAt(13, 25, builderName), }; vbnetExpectedDiagnostics = new[] { GetBasicCA1034ResultAt(11, 33, builderName), }; break; default: throw new ArgumentOutOfRangeException(nameof(variant)); } await VerifyCS.VerifyAnalyzerAsync($@" public class Pizza {{ public bool HasCheese {{ get; }} public bool HasBacon {{ get; }} {outerClassCtorAccessibility} Pizza(bool hasCheese, bool hasBacon) {{ HasCheese = hasCheese; HasBacon = hasBacon; }} public sealed class {builderName} {{ private bool hasCheese; private bool hasBacon; private {builderName}() {{ }} public static {builderName} Create() {{ return new {builderName}(); }} public {builderName} WithCheese() {{ hasCheese = true; return this; }} public {builderName} WithBacon() {{ hasBacon = true; return this; }} public Pizza ToPizza() {{ return new Pizza(hasCheese, hasBacon); }} }} }}", csharpExpectedDiagnostics); await VerifyVB.VerifyAnalyzerAsync($@" Public Class Pizza Public ReadOnly Property HasCheese As Boolean Public ReadOnly Property HasBacon As Boolean {outerClassCtorAccessibility} Sub New(ByVal hasCheese As Boolean, ByVal hasBacon As Boolean) Me.HasCheese = hasCheese Me.HasBacon = hasBacon End Sub Public NotInheritable Class {builderName} Private hasCheese As Boolean Private hasBacon As Boolean Private Sub New() End Sub Public Shared Function Create() As {builderName} Return New {builderName}() End Function Public Function WithCheese() As {builderName} hasCheese = True Return Me End Function Public Function WithBacon() As {builderName} hasBacon = True Return Me End Function Public Function ToPizza() As Pizza Return New Pizza(hasCheese, hasBacon) End Function End Class End Class ", vbnetExpectedDiagnostics); } [Fact, WorkItem(3033, "https://github.com/dotnet/roslyn-analyzers/issues/3033")] public async Task CA1034_BuilderPatternTooDeep_DiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@" public class Outer { public class Pizza { public bool HasCheese { get; } public bool HasBacon { get; } protected Pizza(bool hasCheese, bool hasBacon) { HasCheese = hasCheese; HasBacon = hasBacon; } public sealed class Builder { private bool hasCheese; private bool hasBacon; private Builder() { } public static Builder Create() { return new Builder(); } public Builder WithCheese() { hasCheese = true; return this; } public Builder WithBacon() { hasBacon = true; return this; } public Pizza ToPizza() { return new Pizza(hasCheese, hasBacon); } } } }", GetCSharpCA1034ResultAt(4, 18, "Pizza"), GetCSharpCA1034ResultAt(15, 29, "Builder")); await VerifyVB.VerifyAnalyzerAsync(@" Public Class Outer Public Class Pizza Public ReadOnly Property HasCheese As Boolean Public ReadOnly Property HasBacon As Boolean Protected Sub New(ByVal hasCheese As Boolean, ByVal hasBacon As Boolean) Me.HasCheese = hasCheese Me.HasBacon = hasBacon End Sub Public NotInheritable Class Builder Private hasCheese As Boolean Private hasBacon As Boolean Private Sub New() End Sub Public Shared Function Create() As Builder Return New Builder() End Function Public Function WithCheese() As Builder hasCheese = True Return Me End Function Public Function WithBacon() As Builder hasBacon = True Return Me End Function Public Function ToPizza() As Pizza Return New Pizza(hasCheese, hasBacon) End Function End Class End Class End Class ", GetBasicCA1034ResultAt(3, 18, "Pizza"), GetBasicCA1034ResultAt(12, 37, "Builder")); } private static DiagnosticResult GetCSharpCA1034ResultAt(int line, int column, string nestedTypeName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(NestedTypesShouldNotBeVisibleAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(nestedTypeName); private static DiagnosticResult GetBasicCA1034ResultAt(int line, int column, string nestedTypeName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(NestedTypesShouldNotBeVisibleAnalyzer.DefaultRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(nestedTypeName); private static DiagnosticResult GetBasicCA1034ModuleResultAt(int line, int column, string nestedTypeName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(NestedTypesShouldNotBeVisibleAnalyzer.VisualBasicModuleRule) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(nestedTypeName); } }
// 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.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Xunit.Abstractions; namespace Microsoft.DotNet.Docker.Tests { public class ImageScenarioVerifier { private readonly DockerHelper _dockerHelper; private readonly ProductImageData _imageData; private readonly bool _isWeb; private readonly ITestOutputHelper _outputHelper; public ImageScenarioVerifier( ProductImageData imageData, DockerHelper dockerHelper, ITestOutputHelper outputHelper, bool isWeb = false) { _dockerHelper = dockerHelper; _imageData = imageData; _isWeb = isWeb; _outputHelper = outputHelper; } public async Task Execute() { string appDir = CreateTestAppWithSdkImage(_isWeb ? "web" : "console"); List<string> tags = new List<string>(); InjectCustomTestCode(appDir); try { if (!_imageData.HasCustomSdk) { // Use `sdk` image to build and run test app string buildTag = BuildTestAppImage("build", appDir); tags.Add(buildTag); string dotnetRunArgs = _isWeb ? " --urls http://0.0.0.0:80" : string.Empty; await RunTestAppImage(buildTag, command: $"dotnet run{dotnetRunArgs}"); } // Use `sdk` image to publish FX dependent app and run with `runtime` or `aspnet` image string fxDepTag = BuildTestAppImage("fx_dependent_app", appDir); tags.Add(fxDepTag); bool runAsAdmin = _isWeb && !DockerHelper.IsLinuxContainerModeEnabled; await RunTestAppImage(fxDepTag, runAsAdmin: runAsAdmin); if (DockerHelper.IsLinuxContainerModeEnabled) { // Use `sdk` image to publish self contained app and run with `runtime-deps` image string selfContainedTag = BuildTestAppImage("self_contained_app", appDir, customBuildArgs: $"rid={_imageData.Rid}"); tags.Add(selfContainedTag); await RunTestAppImage(selfContainedTag, runAsAdmin: runAsAdmin); } } finally { tags.ForEach(tag => _dockerHelper.DeleteImage(tag)); Directory.Delete(appDir, true); } } private static void InjectCustomTestCode(string appDir) { string programFilePath = Path.Combine(appDir, "Program.cs"); SyntaxTree programTree = CSharpSyntaxTree.ParseText(File.ReadAllText(programFilePath)); string newContent; MethodDeclarationSyntax mainMethod = programTree.GetRoot().DescendantNodes() .OfType<MethodDeclarationSyntax>() .FirstOrDefault(method => method.Identifier.ValueText == "Main"); if (mainMethod is null) { // Handles project templates that use top-level statements instead of a Main method IEnumerable<SyntaxNode> nodes = programTree.GetRoot().ChildNodes(); IEnumerable<UsingDirectiveSyntax> usingDirectives = nodes.OfType<UsingDirectiveSyntax>(); IEnumerable<SyntaxNode> otherNodes = nodes.Except(usingDirectives); StringBuilder builder = new(); foreach (UsingDirectiveSyntax usingDir in usingDirectives) { builder.Append(usingDir.ToFullString()); } builder.AppendLine("var response = await new System.Net.Http.HttpClient().GetAsync(\"https://www.microsoft.com\");"); builder.AppendLine("response.EnsureSuccessStatusCode();"); foreach (SyntaxNode otherNode in otherNodes) { builder.Append(otherNode.ToFullString()); } newContent = builder.ToString(); } else { StatementSyntax testHttpsConnectivityStatement = SyntaxFactory.ParseStatement( "var task = new System.Net.Http.HttpClient().GetAsync(\"https://www.microsoft.com\");" + "task.Wait();" + "task.Result.EnsureSuccessStatusCode();"); MethodDeclarationSyntax newMainMethod = mainMethod.InsertNodesBefore( mainMethod.Body.ChildNodes().First(), new SyntaxNode[] { testHttpsConnectivityStatement }); SyntaxNode newRoot = programTree.GetRoot().ReplaceNode(mainMethod, newMainMethod); newContent = newRoot.ToFullString(); } File.WriteAllText(programFilePath, newContent); } private string BuildTestAppImage(string stageTarget, string contextDir, params string[] customBuildArgs) { string tag = _imageData.GetIdentifier(stageTarget); List<string> buildArgs = new List<string> { $"sdk_image={_imageData.GetImage(DotNetImageType.SDK, _dockerHelper)}" }; DotNetImageType runtimeImageType = _isWeb ? DotNetImageType.Aspnet : DotNetImageType.Runtime; buildArgs.Add($"runtime_image={_imageData.GetImage(runtimeImageType, _dockerHelper)}"); if (DockerHelper.IsLinuxContainerModeEnabled) { buildArgs.Add($"runtime_deps_image={_imageData.GetImage(DotNetImageType.Runtime_Deps, _dockerHelper)}"); } if (customBuildArgs != null) { buildArgs.AddRange(customBuildArgs); } _dockerHelper.Build( tag: tag, target: stageTarget, contextDir: contextDir, buildArgs: buildArgs.ToArray()); return tag; } private string CreateTestAppWithSdkImage(string appType) { string appDir = Path.Combine(Directory.GetCurrentDirectory(), $"{appType}App{DateTime.Now.ToFileTime()}"); string containerName = _imageData.GetIdentifier($"create-{appType}"); try { string targetFramework; if (_imageData.Version.Major < 5) { targetFramework = $"netcoreapp{_imageData.Version}"; } else { targetFramework = $"net{_imageData.Version}"; } _dockerHelper.Run( image: _imageData.GetImage(DotNetImageType.SDK, _dockerHelper), name: containerName, command: $"dotnet new {appType} --framework {targetFramework} --no-restore", workdir: "/app", skipAutoCleanup: true); _dockerHelper.Copy($"{containerName}:/app", appDir); string sourceDockerfileName = $"Dockerfile.{DockerHelper.DockerOS.ToLower()}"; File.Copy( Path.Combine(DockerHelper.TestArtifactsDir, sourceDockerfileName), Path.Combine(appDir, "Dockerfile")); string nuGetConfigFileName = "NuGet.config"; if (Config.IsNightlyRepo) { nuGetConfigFileName += ".nightly"; } File.Copy(Path.Combine(DockerHelper.TestArtifactsDir, nuGetConfigFileName), Path.Combine(appDir, "NuGet.config")); File.Copy(Path.Combine(DockerHelper.TestArtifactsDir, ".dockerignore"), Path.Combine(appDir, ".dockerignore")); } catch (Exception) { if (Directory.Exists(appDir)) { Directory.Delete(appDir, true); } throw; } finally { _dockerHelper.DeleteContainer(containerName); } return appDir; } private async Task RunTestAppImage(string image, bool runAsAdmin = false, string command = null) { string containerName = _imageData.GetIdentifier("app-run"); try { _dockerHelper.Run( image: image, name: containerName, detach: _isWeb, optionalRunArgs: _isWeb ? "-p 80" : string.Empty, runAsUser: runAsAdmin ? "ContainerAdministrator" : null, command: command); if (_isWeb && !Config.IsHttpVerificationDisabled) { await VerifyHttpResponseFromContainerAsync(containerName, _dockerHelper, _outputHelper); } } finally { _dockerHelper.DeleteContainer(containerName); } } public static async Task<HttpResponseMessage> GetHttpResponseFromContainerAsync(string containerName, DockerHelper dockerHelper, ITestOutputHelper outputHelper, int containerPort = 80, string pathAndQuery = null, Action<HttpResponseMessage> validateCallback = null) { int retries = 30; // Can't use localhost when running inside containers or Windows. string url = !Config.IsRunningInContainer && DockerHelper.IsLinuxContainerModeEnabled ? $"http://localhost:{dockerHelper.GetContainerHostPort(containerName, containerPort)}/{pathAndQuery}" : $"http://{dockerHelper.GetContainerAddress(containerName)}:{containerPort}/{pathAndQuery}"; using (HttpClient client = new HttpClient()) { while (retries > 0) { retries--; await Task.Delay(TimeSpan.FromSeconds(2)); HttpResponseMessage result = null; try { result = await client.GetAsync(url); outputHelper.WriteLine($"HTTP {result.StatusCode}\n{(await result.Content.ReadAsStringAsync())}"); if (null == validateCallback) { result.EnsureSuccessStatusCode(); } else { validateCallback(result); } // Store response in local that will not be disposed HttpResponseMessage returnResult = result; result = null; return returnResult; } catch (Exception ex) { outputHelper.WriteLine($"Request to {url} failed - retrying: {ex}"); } finally { result?.Dispose(); } } } throw new TimeoutException($"Timed out attempting to access the endpoint {url} on container {containerName}"); } public static async Task VerifyHttpResponseFromContainerAsync(string containerName, DockerHelper dockerHelper, ITestOutputHelper outputHelper, int containerPort = 80, string pathAndQuery = null) { (await GetHttpResponseFromContainerAsync( containerName, dockerHelper, outputHelper, containerPort, pathAndQuery)).Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Quidjibo.Configurations; using Quidjibo.Factories; using Quidjibo.Misc; using Quidjibo.Models; using Quidjibo.Pipeline; using Quidjibo.Pipeline.Contexts; using Quidjibo.Pipeline.Misc; using Quidjibo.Providers; namespace Quidjibo.Servers { public class QuidjiboServer : IQuidjiboServer { private readonly ICronProvider _cronProvider; private readonly ILogger _logger; private readonly IProgressProviderFactory _progressProviderFactory; private readonly IQuidjiboConfiguration _quidjiboConfiguration; private readonly IQuidjiboPipeline _quidjiboPipeline; private readonly IScheduleProviderFactory _scheduleProviderFactory; private readonly IWorkProviderFactory _workProviderFactory; public bool IsRunning { get; private set; } public QuidjiboServer( ILoggerFactory loggerFactory, IQuidjiboConfiguration quidjiboConfiguration, IWorkProviderFactory workProviderFactory, IScheduleProviderFactory scheduleProviderFactory, IProgressProviderFactory progressProviderFactory, ICronProvider cronProvider, IQuidjiboPipeline quidjiboPipeline) { _logger = loggerFactory.CreateLogger<QuidjiboServer>(); _workProviderFactory = workProviderFactory; _scheduleProviderFactory = scheduleProviderFactory; _quidjiboConfiguration = quidjiboConfiguration; _cronProvider = cronProvider; _quidjiboPipeline = quidjiboPipeline; _progressProviderFactory = progressProviderFactory; Worker = $"{Environment.GetEnvironmentVariable("COMPUTERNAME")}-{Guid.NewGuid()}"; } public string Worker { get; } public void Start() { lock (_syncRoot) { if (IsRunning) { return; } _logger.LogInformation("Starting Server {Worker}", Worker); _cts = new CancellationTokenSource(); _loopTasks = new List<Task>(); _throttle = new SemaphoreSlim(0, _quidjiboConfiguration.Throttle); _logger.LogInformation("EnableWorker = {EnableWorker}", _quidjiboConfiguration.EnableWorker); if (_quidjiboConfiguration.EnableWorker) { if (_quidjiboConfiguration.SingleLoop) { _logger.LogInformation("All queues can share the same loop"); var queues = string.Join(",", _quidjiboConfiguration.Queues); _loopTasks.Add(WorkLoopAsync(queues)); } else { _logger.LogInformation("Each queue will need a designated loop"); _loopTasks.AddRange(_quidjiboConfiguration.Queues.Select(WorkLoopAsync)); } } _logger.LogInformation("EnableScheduler = {EnableScheduler}", _quidjiboConfiguration.EnableScheduler); if (_quidjiboConfiguration.EnableScheduler) { _logger.LogInformation("Enabling scheduler"); _loopTasks.Add(ScheduleLoopAsync(_quidjiboConfiguration.Queues)); } _throttle.Release(_quidjiboConfiguration.Throttle); IsRunning = true; _logger.LogInformation("Started Worker {Worker}", Worker); } } public void Stop() { lock (_syncRoot) { if (!IsRunning) { return; } _cts?.Cancel(); _cts?.Dispose(); _loopTasks = null; IsRunning = false; _logger.LogInformation("Stopped Worker {Worker}", Worker); } } public void Dispose() { Stop(); } #region Internals private readonly object _syncRoot = new object(); private List<Task> _loopTasks; private CancellationTokenSource _cts; private SemaphoreSlim _throttle; private async Task WorkLoopAsync(string queue) { var pollingInterval = TimeSpan.FromSeconds(_quidjiboConfiguration.WorkPollingInterval ?? 45); var workProvider = await _workProviderFactory.CreateAsync(queue, _cts.Token); while (!_cts.IsCancellationRequested) { var items = new List<WorkItem>(0); try { _logger.LogTrace("Throttle Count : {ThrottleCount}", _throttle.CurrentCount); // throttle is important when there is more than one listener await _throttle.WaitAsync(_cts.Token); items = await workProvider.ReceiveAsync(Worker, _cts.Token); if (items.Count > 0) { _logger.LogDebug("Received {WorkItemCount} items.", items.Count); var tasks = items.Select(item => InvokePipelineAsync(workProvider, item)); await Task.WhenAll(tasks); } } catch (Exception exception) { _logger.LogWarning(0, exception, exception.Message); } finally { _throttle.Release(); } if (items == null || items.Count <= 0) { await Task.Delay(pollingInterval, _cts.Token); } } } private async Task ScheduleLoopAsync(string[] queues) { var pollingInterval = TimeSpan.FromSeconds(_quidjiboConfiguration.SchedulePollingInterval ?? 45); var scheduleProvider = await _scheduleProviderFactory.CreateAsync(queues, _cts.Token); while (!_cts.IsCancellationRequested) { try { var items = await scheduleProvider.ReceiveAsync(_cts.Token); foreach (var item in items) { var work = new WorkItem { Attempts = 0, CorrelationId = Guid.NewGuid(), Id = Guid.NewGuid(), Name = item.Name, Payload = item.Payload, Queue = item.Queue, ScheduleId = item.Id }; _logger.LogDebug("Enqueue the scheduled item : {Id}", item.Id); var workProvider = await _workProviderFactory.CreateAsync(work.Queue, _cts.Token); await workProvider.SendAsync(work, 1, _cts.Token); _logger.LogDebug("Update the schedule for the next run : {Id}", item.Id); item.EnqueueOn = _cronProvider.GetNextSchedule(item.CronExpression); item.EnqueuedOn = DateTime.UtcNow; await scheduleProvider.CompleteAsync(item, _cts.Token); } } catch (Exception exception) { _logger.LogWarning(0, exception, exception.Message); } finally { await Task.Delay(pollingInterval, _cts.Token); } } } private async Task InvokePipelineAsync(IWorkProvider provider, WorkItem item) { using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token)) { var progress = new QuidjiboProgress(); progress.ProgressChanged += async (sender, tracker) => { var progressProvider = await _progressProviderFactory.CreateAsync(item.Queue, _cts.Token); var progressItem = new ProgressItem { Id = Guid.NewGuid(), CorrelationId = item.CorrelationId, RecordedOn = DateTime.UtcNow, Name = item.Name, Queue = item.Queue, Note = tracker.Text, Value = tracker.Value, WorkId = item.Id }; await progressProvider.ReportAsync(progressItem, _cts.Token); }; var renewTask = RenewAsync(provider, item, linkedTokenSource.Token); var context = new QuidjiboContext { Item = item, WorkProvider = provider, Progress = progress, State = new PipelineState() }; try { await _quidjiboPipeline.StartAsync(context, linkedTokenSource.Token); if (context.State.Success) { await provider.CompleteAsync(item, linkedTokenSource.Token); _logger.LogDebug("Completed : {Id}", item.Id); } else { await provider.FaultAsync(item, linkedTokenSource.Token); _logger.LogError("Faulted : {Id}", item.Id); } } catch (Exception exception) { _logger.LogError("Faulted : {Id}, {Exception}", item.Id, exception); await provider.FaultAsync(item, linkedTokenSource.Token); } finally { _logger.LogDebug("Release : {Id}", item.Id); linkedTokenSource.Cancel(); await renewTask; await _quidjiboPipeline.EndAsync(context); } } } private async Task RenewAsync(IWorkProvider provider, WorkItem item, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { try { await Task.Delay(TimeSpan.FromSeconds(_quidjiboConfiguration.LockInterval), cancellationToken); await provider.RenewAsync(item, cancellationToken); _logger.LogDebug("Renewed : {Id}", item.Id); } catch (OperationCanceledException) { // ignore OperationCanceledExceptions } } } #endregion } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Collections.Generic; namespace Mono.Cecil { struct Range { public uint Start; public uint Length; public Range (uint index, uint length) { this.Start = index; this.Length = length; } } sealed class MetadataSystem { internal AssemblyNameReference [] AssemblyReferences; internal ModuleReference [] ModuleReferences; internal TypeDefinition [] Types; internal TypeReference [] TypeReferences; internal FieldDefinition [] Fields; internal MethodDefinition [] Methods; internal MemberReference [] MemberReferences; internal Dictionary<uint, Collection<uint>> NestedTypes; internal Dictionary<uint, uint> ReverseNestedTypes; internal Dictionary<uint, Collection<Row<uint, MetadataToken>>> Interfaces; internal Dictionary<uint, Row<ushort, uint>> ClassLayouts; internal Dictionary<uint, uint> FieldLayouts; internal Dictionary<uint, uint> FieldRVAs; internal Dictionary<MetadataToken, uint> FieldMarshals; internal Dictionary<MetadataToken, Row<ElementType, uint>> Constants; internal Dictionary<uint, Collection<MetadataToken>> Overrides; internal Dictionary<MetadataToken, Range []> CustomAttributes; internal Dictionary<MetadataToken, Range []> SecurityDeclarations; internal Dictionary<uint, Range> Events; internal Dictionary<uint, Range> Properties; internal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics; internal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes; internal Dictionary<MetadataToken, Range []> GenericParameters; internal Dictionary<uint, Collection<Row<uint, MetadataToken>>> GenericConstraints; internal Document [] Documents; internal Dictionary<uint, Collection<Row<uint, Range, Range, uint, uint, uint>>> LocalScopes; internal ImportDebugInformation [] ImportScopes; internal Dictionary<uint, uint> StateMachineMethods; internal Dictionary<MetadataToken, Row<Guid, uint, uint> []> CustomDebugInformations; static Dictionary<string, Row<ElementType, bool>> primitive_value_types; static void InitializePrimitives () { var types = new Dictionary<string, Row<ElementType, bool>> (18, StringComparer.Ordinal) { { "Void", new Row<ElementType, bool> (ElementType.Void, false) }, { "Boolean", new Row<ElementType, bool> (ElementType.Boolean, true) }, { "Char", new Row<ElementType, bool> (ElementType.Char, true) }, { "SByte", new Row<ElementType, bool> (ElementType.I1, true) }, { "Byte", new Row<ElementType, bool> (ElementType.U1, true) }, { "Int16", new Row<ElementType, bool> (ElementType.I2, true) }, { "UInt16", new Row<ElementType, bool> (ElementType.U2, true) }, { "Int32", new Row<ElementType, bool> (ElementType.I4, true) }, { "UInt32", new Row<ElementType, bool> (ElementType.U4, true) }, { "Int64", new Row<ElementType, bool> (ElementType.I8, true) }, { "UInt64", new Row<ElementType, bool> (ElementType.U8, true) }, { "Single", new Row<ElementType, bool> (ElementType.R4, true) }, { "Double", new Row<ElementType, bool> (ElementType.R8, true) }, { "String", new Row<ElementType, bool> (ElementType.String, false) }, { "TypedReference", new Row<ElementType, bool> (ElementType.TypedByRef, false) }, { "IntPtr", new Row<ElementType, bool> (ElementType.I, true) }, { "UIntPtr", new Row<ElementType, bool> (ElementType.U, true) }, { "Object", new Row<ElementType, bool> (ElementType.Object, false) }, }; Interlocked.CompareExchange (ref primitive_value_types, types, null); } public static void TryProcessPrimitiveTypeReference (TypeReference type) { if (type.Namespace != "System") return; var scope = type.scope; if (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference) return; Row<ElementType, bool> primitive_data; if (!TryGetPrimitiveData (type, out primitive_data)) return; type.etype = primitive_data.Col1; type.IsValueType = primitive_data.Col2; } public static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype) { etype = ElementType.None; if (type.Namespace != "System") return false; Row<ElementType, bool> primitive_data; if (TryGetPrimitiveData (type, out primitive_data)) { etype = primitive_data.Col1; return true; } return false; } static bool TryGetPrimitiveData (TypeReference type, out Row<ElementType, bool> primitive_data) { if (primitive_value_types == null) InitializePrimitives (); return primitive_value_types.TryGetValue (type.Name, out primitive_data); } public void Clear () { if (NestedTypes != null) NestedTypes = new Dictionary<uint, Collection<uint>> (capacity: 0); if (ReverseNestedTypes != null) ReverseNestedTypes = new Dictionary<uint, uint> (capacity: 0); if (Interfaces != null) Interfaces = new Dictionary<uint, Collection<Row<uint, MetadataToken>>> (capacity: 0); if (ClassLayouts != null) ClassLayouts = new Dictionary<uint, Row<ushort, uint>> (capacity: 0); if (FieldLayouts != null) FieldLayouts = new Dictionary<uint, uint> (capacity: 0); if (FieldRVAs != null) FieldRVAs = new Dictionary<uint, uint> (capacity: 0); if (FieldMarshals != null) FieldMarshals = new Dictionary<MetadataToken, uint> (capacity: 0); if (Constants != null) Constants = new Dictionary<MetadataToken, Row<ElementType, uint>> (capacity: 0); if (Overrides != null) Overrides = new Dictionary<uint, Collection<MetadataToken>> (capacity: 0); if (CustomAttributes != null) CustomAttributes = new Dictionary<MetadataToken, Range []> (capacity: 0); if (SecurityDeclarations != null) SecurityDeclarations = new Dictionary<MetadataToken, Range []> (capacity: 0); if (Events != null) Events = new Dictionary<uint, Range> (capacity: 0); if (Properties != null) Properties = new Dictionary<uint, Range> (capacity: 0); if (Semantics != null) Semantics = new Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> (capacity: 0); if (PInvokes != null) PInvokes = new Dictionary<uint, Row<PInvokeAttributes, uint, uint>> (capacity: 0); if (GenericParameters != null) GenericParameters = new Dictionary<MetadataToken, Range []> (capacity: 0); if (GenericConstraints != null) GenericConstraints = new Dictionary<uint, Collection<Row<uint, MetadataToken>>> (capacity: 0); Documents = Empty<Document>.Array; ImportScopes = Empty<ImportDebugInformation>.Array; if (LocalScopes != null) LocalScopes = new Dictionary<uint, Collection<Row<uint, Range, Range, uint, uint, uint>>> (capacity: 0); if (StateMachineMethods != null) StateMachineMethods = new Dictionary<uint, uint> (capacity: 0); } public AssemblyNameReference GetAssemblyNameReference (uint rid) { if (rid < 1 || rid > AssemblyReferences.Length) return null; return AssemblyReferences [rid - 1]; } public TypeDefinition GetTypeDefinition (uint rid) { if (rid < 1 || rid > Types.Length) return null; return Types [rid - 1]; } public void AddTypeDefinition (TypeDefinition type) { Types [type.token.RID - 1] = type; } public TypeReference GetTypeReference (uint rid) { if (rid < 1 || rid > TypeReferences.Length) return null; return TypeReferences [rid - 1]; } public void AddTypeReference (TypeReference type) { TypeReferences [type.token.RID - 1] = type; } public FieldDefinition GetFieldDefinition (uint rid) { if (rid < 1 || rid > Fields.Length) return null; return Fields [rid - 1]; } public void AddFieldDefinition (FieldDefinition field) { Fields [field.token.RID - 1] = field; } public MethodDefinition GetMethodDefinition (uint rid) { if (rid < 1 || rid > Methods.Length) return null; return Methods [rid - 1]; } public void AddMethodDefinition (MethodDefinition method) { Methods [method.token.RID - 1] = method; } public MemberReference GetMemberReference (uint rid) { if (rid < 1 || rid > MemberReferences.Length) return null; return MemberReferences [rid - 1]; } public void AddMemberReference (MemberReference member) { MemberReferences [member.token.RID - 1] = member; } public bool TryGetNestedTypeMapping (TypeDefinition type, out Collection<uint> mapping) { return NestedTypes.TryGetValue (type.token.RID, out mapping); } public void SetNestedTypeMapping (uint type_rid, Collection<uint> mapping) { NestedTypes [type_rid] = mapping; } public void RemoveNestedTypeMapping (TypeDefinition type) { NestedTypes.Remove (type.token.RID); } public bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring) { return ReverseNestedTypes.TryGetValue (type.token.RID, out declaring); } public void SetReverseNestedTypeMapping (uint nested, uint declaring) { ReverseNestedTypes [nested] = declaring; } public void RemoveReverseNestedTypeMapping (TypeDefinition type) { ReverseNestedTypes.Remove (type.token.RID); } public bool TryGetInterfaceMapping (TypeDefinition type, out Collection<Row<uint, MetadataToken>> mapping) { return Interfaces.TryGetValue (type.token.RID, out mapping); } public void SetInterfaceMapping (uint type_rid, Collection<Row<uint, MetadataToken>> mapping) { Interfaces [type_rid] = mapping; } public void RemoveInterfaceMapping (TypeDefinition type) { Interfaces.Remove (type.token.RID); } public void AddPropertiesRange (uint type_rid, Range range) { Properties.Add (type_rid, range); } public bool TryGetPropertiesRange (TypeDefinition type, out Range range) { return Properties.TryGetValue (type.token.RID, out range); } public void RemovePropertiesRange (TypeDefinition type) { Properties.Remove (type.token.RID); } public void AddEventsRange (uint type_rid, Range range) { Events.Add (type_rid, range); } public bool TryGetEventsRange (TypeDefinition type, out Range range) { return Events.TryGetValue (type.token.RID, out range); } public void RemoveEventsRange (TypeDefinition type) { Events.Remove (type.token.RID); } public bool TryGetGenericParameterRanges (IGenericParameterProvider owner, out Range [] ranges) { return GenericParameters.TryGetValue (owner.MetadataToken, out ranges); } public void RemoveGenericParameterRange (IGenericParameterProvider owner) { GenericParameters.Remove (owner.MetadataToken); } public bool TryGetCustomAttributeRanges (ICustomAttributeProvider owner, out Range [] ranges) { return CustomAttributes.TryGetValue (owner.MetadataToken, out ranges); } public void RemoveCustomAttributeRange (ICustomAttributeProvider owner) { CustomAttributes.Remove (owner.MetadataToken); } public bool TryGetSecurityDeclarationRanges (ISecurityDeclarationProvider owner, out Range [] ranges) { return SecurityDeclarations.TryGetValue (owner.MetadataToken, out ranges); } public void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner) { SecurityDeclarations.Remove (owner.MetadataToken); } public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out Collection<Row<uint, MetadataToken>> mapping) { return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping); } public void SetGenericConstraintMapping (uint gp_rid, Collection<Row<uint, MetadataToken>> mapping) { GenericConstraints [gp_rid] = mapping; } public void RemoveGenericConstraintMapping (GenericParameter generic_parameter) { GenericConstraints.Remove (generic_parameter.token.RID); } public bool TryGetOverrideMapping (MethodDefinition method, out Collection<MetadataToken> mapping) { return Overrides.TryGetValue (method.token.RID, out mapping); } public void SetOverrideMapping (uint rid, Collection<MetadataToken> mapping) { Overrides [rid] = mapping; } public void RemoveOverrideMapping (MethodDefinition method) { Overrides.Remove (method.token.RID); } public Document GetDocument (uint rid) { if (rid < 1 || rid > Documents.Length) return null; return Documents [rid - 1]; } public bool TryGetLocalScopes (MethodDefinition method, out Collection<Row<uint, Range, Range, uint, uint, uint>> scopes) { return LocalScopes.TryGetValue (method.MetadataToken.RID, out scopes); } public void SetLocalScopes (uint method_rid, Collection<Row<uint, Range, Range, uint, uint, uint>> records) { LocalScopes [method_rid] = records; } public ImportDebugInformation GetImportScope (uint rid) { if (rid < 1 || rid > ImportScopes.Length) return null; return ImportScopes [rid - 1]; } public bool TryGetStateMachineKickOffMethod (MethodDefinition method, out uint rid) { return StateMachineMethods.TryGetValue (method.MetadataToken.RID, out rid); } public TypeDefinition GetFieldDeclaringType (uint field_rid) { return BinaryRangeSearch (Types, field_rid, true); } public TypeDefinition GetMethodDeclaringType (uint method_rid) { return BinaryRangeSearch (Types, method_rid, false); } static TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field) { int min = 0; int max = types.Length - 1; while (min <= max) { int mid = min + ((max - min) / 2); var type = types [mid]; var range = field ? type.fields_range : type.methods_range; if (rid < range.Start) max = mid - 1; else if (rid >= range.Start + range.Length) min = mid + 1; else return type; } return null; } } }
/* ==================================================================== 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.Util { using System; using NPOI.SS.UserModel; using System.Drawing; using System.Collections.Generic; /** * Helper methods for when working with Usermodel sheets * * @author Yegor Kozlov */ public class SheetUtil { // /** // * Excel measures columns in units of 1/256th of a character width // * but the docs say nothing about what particular character is used. // * '0' looks to be a good choice. // */ private static char defaultChar = '0'; // /** // * This is the multiple that the font height is scaled by when determining the // * boundary of rotated text. // */ //private static double fontHeightMultiple = 2.0; /** * Dummy formula Evaluator that does nothing. * YK: The only reason of having this class is that * {@link NPOI.SS.UserModel.DataFormatter#formatCellValue(NPOI.SS.UserModel.Cell)} * returns formula string for formula cells. Dummy Evaluator Makes it to format the cached formula result. * * See Bugzilla #50021 */ private static IFormulaEvaluator dummyEvaluator = new DummyEvaluator(); public class DummyEvaluator : IFormulaEvaluator { public void ClearAllCachedResultValues() { } public void NotifySetFormula(ICell cell) { } public void NotifyDeleteCell(ICell cell) { } public void NotifyUpdateCell(ICell cell) { } public CellValue Evaluate(ICell cell) { return null; } public ICell EvaluateInCell(ICell cell) { return null; } public bool IgnoreMissingWorkbooks { get; set; } public void SetupReferencedWorkbooks(Dictionary<String, IFormulaEvaluator> workbooks) { } public void EvaluateAll() { } public CellType EvaluateFormulaCell(ICell cell) { return cell.CachedFormulaResultType; } public bool DebugEvaluationOutputForNextEval { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } public static IRow CopyRow(ISheet sourceSheet, int sourceRowIndex, ISheet targetSheet, int targetRowIndex) { // Get the source / new row IRow newRow = targetSheet.GetRow(targetRowIndex); IRow sourceRow = sourceSheet.GetRow(sourceRowIndex); // If the row exist in destination, push down all rows by 1 else create a new row if (newRow != null) { targetSheet.RemoveRow(newRow); } newRow = targetSheet.CreateRow(targetRowIndex); if (sourceRow == null) throw new ArgumentNullException("source row doesn't exist"); // Loop through source columns to add to new row for (int i = sourceRow.FirstCellNum; i < sourceRow.LastCellNum; i++) { // Grab a copy of the old/new cell ICell oldCell = sourceRow.GetCell(i); // If the old cell is null jump to next cell if (oldCell == null) { continue; } ICell newCell = newRow.CreateCell(i); if (oldCell.CellStyle != null) { // apply style from old cell to new cell newCell.CellStyle = oldCell.CellStyle; } // If there is a cell comment, copy if (oldCell.CellComment != null) { newCell.CellComment = oldCell.CellComment; } // If there is a cell hyperlink, copy if (oldCell.Hyperlink != null) { newCell.Hyperlink = oldCell.Hyperlink; } // Set the cell data type newCell.SetCellType(oldCell.CellType); // Set the cell data value switch (oldCell.CellType) { case CellType.Blank: newCell.SetCellValue(oldCell.StringCellValue); break; case CellType.Boolean: newCell.SetCellValue(oldCell.BooleanCellValue); break; case CellType.Error: newCell.SetCellErrorValue(oldCell.ErrorCellValue); break; case CellType.Formula: newCell.SetCellFormula(oldCell.CellFormula); break; case CellType.Numeric: newCell.SetCellValue(oldCell.NumericCellValue); break; case CellType.String: newCell.SetCellValue(oldCell.RichStringCellValue); break; } } // If there are are any merged regions in the source row, copy to new row for (int i = 0; i < sourceSheet.NumMergedRegions; i++) { CellRangeAddress cellRangeAddress = sourceSheet.GetMergedRegion(i); if (cellRangeAddress!=null && cellRangeAddress.FirstRow == sourceRow.RowNum) { CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum, (newRow.RowNum + (cellRangeAddress.LastRow - cellRangeAddress.FirstRow )), cellRangeAddress.FirstColumn, cellRangeAddress.LastColumn); targetSheet.AddMergedRegion(newCellRangeAddress); } } return newRow; } public static IRow CopyRow(ISheet sheet, int sourceRowIndex, int targetRowIndex) { if (sourceRowIndex == targetRowIndex) throw new ArgumentException("sourceIndex and targetIndex cannot be same"); // Get the source / new row IRow newRow = sheet.GetRow(targetRowIndex); IRow sourceRow = sheet.GetRow(sourceRowIndex); // If the row exist in destination, push down all rows by 1 else create a new row if (newRow != null) { sheet.ShiftRows(targetRowIndex, sheet.LastRowNum, 1); } newRow = sheet.CreateRow(targetRowIndex); newRow.Height = sourceRow.Height; //copy row height // Loop through source columns to add to new row for (int i = sourceRow.FirstCellNum; i < sourceRow.LastCellNum; i++) { // Grab a copy of the old/new cell ICell oldCell = sourceRow.GetCell(i); // If the old cell is null jump to next cell if (oldCell == null) { continue; } ICell newCell = newRow.CreateCell(i); if (oldCell.CellStyle != null) { // apply style from old cell to new cell newCell.CellStyle = oldCell.CellStyle; } // If there is a cell comment, copy if (oldCell.CellComment != null) { newCell.CellComment = oldCell.CellComment; } // If there is a cell hyperlink, copy if (oldCell.Hyperlink != null) { newCell.Hyperlink = oldCell.Hyperlink; } // Set the cell data type newCell.SetCellType(oldCell.CellType); // Set the cell data value switch (oldCell.CellType) { case CellType.Blank: newCell.SetCellValue(oldCell.StringCellValue); break; case CellType.Boolean: newCell.SetCellValue(oldCell.BooleanCellValue); break; case CellType.Error: newCell.SetCellErrorValue(oldCell.ErrorCellValue); break; case CellType.Formula: newCell.SetCellFormula(oldCell.CellFormula); break; case CellType.Numeric: newCell.SetCellValue(oldCell.NumericCellValue); break; case CellType.String: newCell.SetCellValue(oldCell.RichStringCellValue); break; } } // If there are are any merged regions in the source row, copy to new row for (int i = 0; i < sheet.NumMergedRegions; i++) { CellRangeAddress cellRangeAddress = sheet.GetMergedRegion(i); if (cellRangeAddress != null && cellRangeAddress.FirstRow == sourceRow.RowNum) { CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum, (newRow.RowNum + (cellRangeAddress.LastRow - cellRangeAddress.FirstRow )), cellRangeAddress.FirstColumn, cellRangeAddress.LastColumn); sheet.AddMergedRegion(newCellRangeAddress); } } return newRow; } /** * Compute width of a single cell * * @param cell the cell whose width is to be calculated * @param defaultCharWidth the width of a single character * @param formatter formatter used to prepare the text to be measured * @param useMergedCells whether to use merged cells * @return the width in pixels or -1 if cell is empty */ public static double GetCellWidth(ICell cell, int defaultCharWidth, DataFormatter formatter, bool useMergedCells) { ISheet sheet = cell.Sheet; IWorkbook wb = sheet.Workbook; IRow row = cell.Row; int column = cell.ColumnIndex; int colspan = 1; for (int i = 0; i < sheet.NumMergedRegions; i++) { CellRangeAddress region = sheet.GetMergedRegion(i); if (ContainsCell(region, row.RowNum, column)) { if (!useMergedCells) { // If we're not using merged cells, skip this one and move on to the next. return -1; } cell = row.GetCell(region.FirstColumn); colspan = 1 + region.LastColumn - region.FirstColumn; } } ICellStyle style = cell.CellStyle; CellType cellType = cell.CellType; IFont defaultFont = wb.GetFontAt((short)0); Font windowsFont = IFont2Font(defaultFont); // for formula cells we compute the cell width for the cached formula result if (cellType == CellType.Formula) cellType = cell.CachedFormulaResultType; IFont font = wb.GetFontAt(style.FontIndex); double width = -1; using (Bitmap bmp = new Bitmap(1,1)) using (Graphics g = Graphics.FromImage(bmp)) { if (cellType == CellType.String) { IRichTextString rt = cell.RichStringCellValue; String[] lines = rt.String.Split("\n".ToCharArray()); for (int i = 0; i < lines.Length; i++) { String txt = lines[i] + defaultChar; //AttributedString str = new AttributedString(txt); //copyAttributes(font, str, 0, txt.length()); windowsFont = IFont2Font(font); if (rt.NumFormattingRuns > 0) { // TODO: support rich text fragments } width = GetCellWidth(defaultCharWidth, colspan, style, width, txt, g, windowsFont, cell); } } else { String sval = null; if (cellType == CellType.Numeric) { // Try to get it formatted to look the same as excel try { sval = formatter.FormatCellValue(cell, dummyEvaluator); } catch (Exception) { sval = cell.NumericCellValue.ToString(); } } else if (cellType == CellType.Boolean) { sval = cell.BooleanCellValue.ToString().ToUpper(); } if (sval != null) { String txt = sval + defaultChar; //str = new AttributedString(txt); //copyAttributes(font, str, 0, txt.length()); windowsFont = IFont2Font(font); width = GetCellWidth(defaultCharWidth, colspan, style, width, txt, g, windowsFont, cell); } } } return width; } private static double GetCellWidth(int defaultCharWidth, int colspan, ICellStyle style, double width, string str, Graphics g, Font windowsFont, ICell cell) { //Rectangle bounds; double actualWidth; if (style.Rotation != 0) { double angle = style.Rotation * 2.0 * Math.PI / 360.0; SizeF sf = g.MeasureString(str, windowsFont); double x1 = Math.Abs(sf.Height * Math.Sin(angle)); double x2 = Math.Abs(sf.Width * Math.Cos(angle)); actualWidth = Math.Round(x1 + x2, 0, MidpointRounding.ToEven); //bounds = layout.getOutline(trans).getBounds(); } else { //bounds = layout.getBounds(); actualWidth = Math.Round(g.MeasureString(str, windowsFont, int.MaxValue, StringFormat.GenericTypographic).Width, 0, MidpointRounding.ToEven); } // entireWidth accounts for leading spaces which is excluded from bounds.getWidth() //double frameWidth = bounds.getX() + bounds.getWidth(); //width = Math.max(width, ((frameWidth / colspan) / defaultCharWidth) + style.getIndention()); width = Math.Max(width, (actualWidth / colspan / defaultCharWidth) + cell.CellStyle.Indention); return width; } // /** // * Drawing context to measure text // */ //private static FontRenderContext fontRenderContext = new FontRenderContext(null, true, true); /** * Compute width of a column and return the result * * @param sheet the sheet to calculate * @param column 0-based index of the column * @param useMergedCells whether to use merged cells * @return the width in pixels or -1 if all cells are empty */ public static double GetColumnWidth(ISheet sheet, int column, bool useMergedCells) { return GetColumnWidth(sheet, column, useMergedCells, sheet.FirstRowNum, sheet.LastRowNum); } /** * Compute width of a column based on a subset of the rows and return the result * * @param sheet the sheet to calculate * @param column 0-based index of the column * @param useMergedCells whether to use merged cells * @param firstRow 0-based index of the first row to consider (inclusive) * @param lastRow 0-based index of the last row to consider (inclusive) * @return the width in pixels or -1 if cell is empty */ public static double GetColumnWidth(ISheet sheet, int column, bool useMergedCells, int firstRow, int lastRow) { DataFormatter formatter = new DataFormatter(); int defaultCharWidth = GetDefaultCharWidth(sheet.Workbook); double width = -1; for (int rowIdx = firstRow; rowIdx <= lastRow; ++rowIdx) { IRow row = sheet.GetRow(rowIdx); if (row != null) { double cellWidth = GetColumnWidthForRow(row, column, defaultCharWidth, formatter, useMergedCells); width = Math.Max(width, cellWidth); } } return width; } /** * Get default character width * * @param wb the workbook to get the default character width from * @return default character width */ public static int GetDefaultCharWidth(IWorkbook wb) { IFont defaultFont = wb.GetFontAt((short)0); //AttributedString str = new AttributedString(String.valueOf(defaultChar)); //copyAttributes(defaultFont, str, 0, 1); //TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext); //int defaultCharWidth = (int)layout.getAdvance(); int defaultCharWidth = 0; Font font = IFont2Font(defaultFont); using (var image = new Bitmap(1, 1)) { using (var g = Graphics.FromImage(image)) { g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; defaultCharWidth = (int)g.MeasureString(new String(defaultChar, 1), font, int.MaxValue, StringFormat.GenericTypographic).Width; } } return defaultCharWidth; } /** * Compute width of a single cell in a row * Convenience method for {@link getCellWidth} * * @param row the row that contains the cell of interest * @param column the column number of the cell whose width is to be calculated * @param defaultCharWidth the width of a single character * @param formatter formatter used to prepare the text to be measured * @param useMergedCells whether to use merged cells * @return the width in pixels or -1 if cell is empty */ private static double GetColumnWidthForRow( IRow row, int column, int defaultCharWidth, DataFormatter formatter, bool useMergedCells) { if (row == null) { return -1; } ICell cell = row.GetCell(column); if (cell == null) { return -1; } return GetCellWidth(cell, defaultCharWidth, formatter, useMergedCells); } /** * Check if the Fonts are installed correctly so that Java can compute the size of * columns. * * If a Cell uses a Font which is not available on the operating system then Java may * fail to return useful Font metrics and thus lead to an auto-computed size of 0. * * This method allows to check if computing the sizes for a given Font will succeed or not. * * @param font The Font that is used in the Cell * @return true if computing the size for this Font will succeed, false otherwise */ public static bool CanComputeColumnWidth(IFont font) { //AttributedString str = new AttributedString("1w"); //copyAttributes(font, str, 0, "1w".length()); //TextLayout layout = new TextLayout(str.getIterator(), fontRenderContext); //if (layout.getBounds().getWidth() > 0) //{ // return true; //} return true; } // /** // * Copy text attributes from the supplied Font to Java2D AttributedString // */ //private static void copyAttributes(IFont font, AttributedString str, int startIdx, int endIdx) //{ // str.AddAttribute(TextAttribute.FAMILY, font.FontName, startIdx, endIdx); // str.AddAttribute(TextAttribute.SIZE, (float)font.FontHeightInPoints); // if (font.Boldweight == (short)FontBoldWeight.BOLD) str.AddAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx); // if (font.IsItalic) str.AddAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx); // if (font.Underline == (byte)FontUnderlineType.SINGLE) str.AddAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx); //} /// <summary> /// Convert HSSFFont to Font. /// </summary> /// <param name="font1">The font.</param> /// <returns></returns> internal static Font IFont2Font(IFont font1) { FontStyle style = FontStyle.Regular; if (font1.IsBold) { style |= FontStyle.Bold; } if (font1.IsItalic) style |= FontStyle.Italic; if (font1.Underline == FontUnderlineType.Single) { style |= FontStyle.Underline; } Font font = new Font(font1.FontName, (float)font1.FontHeightInPoints, style, GraphicsUnit.Point); return font; } /// <summary> /// Check if the cell is in the specified cell range /// </summary> /// <param name="cr">the cell range to check in</param> /// <param name="rowIx">the row to check</param> /// <param name="colIx">the column to check</param> /// <returns>return true if the range contains the cell [rowIx, colIx]</returns> [Obsolete("deprecated 3.15 beta 2. Use {@link CellRangeAddressBase#isInRange(int, int)}.")] public static bool ContainsCell(CellRangeAddress cr, int rowIx, int colIx) { return cr.IsInRange(rowIx, colIx); } /** * Generate a valid sheet name based on the existing one. Used when cloning sheets. * * @param srcName the original sheet name to * @return clone sheet name */ public static String GetUniqueSheetName(IWorkbook wb, String srcName) { if (wb.GetSheetIndex(srcName) == -1) { return srcName; } int uniqueIndex = 2; String baseName = srcName; int bracketPos = srcName.LastIndexOf('('); if (bracketPos > 0 && srcName.EndsWith(")")) { String suffix = srcName.Substring(bracketPos + 1, srcName.Length - bracketPos - 2); try { uniqueIndex = Int32.Parse(suffix.Trim()); uniqueIndex++; baseName = srcName.Substring(0, bracketPos).Trim(); } catch (FormatException) { // contents of brackets not numeric } } while (true) { // Try and find the next sheet name that is unique String index = (uniqueIndex++).ToString(); String name; if (baseName.Length + index.Length + 2 < 31) { name = baseName + " (" + index + ")"; } else { name = baseName.Substring(0, 31 - index.Length - 2) + "(" + index + ")"; } //If the sheet name is unique, then Set it otherwise Move on to the next number. if (wb.GetSheetIndex(name) == -1) { return name; } } } /** * Return the cell, taking account of merged regions. Allows you to find the * cell who's contents are Shown in a given position in the sheet. * * <p>If the cell at the given co-ordinates is a merged cell, this will * return the primary (top-left) most cell of the merged region.</p> * <p>If the cell at the given co-ordinates is not in a merged region, * then will return the cell itself.</p> * <p>If there is no cell defined at the given co-ordinates, will return * null.</p> */ public static ICell GetCellWithMerges(ISheet sheet, int rowIx, int colIx) { IRow r = sheet.GetRow(rowIx); if (r != null) { ICell c = r.GetCell(colIx); if (c != null) { // Normal, non-merged cell return c; } } for (int mr = 0; mr < sheet.NumMergedRegions; mr++) { CellRangeAddress mergedRegion = sheet.GetMergedRegion(mr); if (mergedRegion.IsInRange(rowIx, colIx)) { // The cell wanted is in this merged range // Return the primary (top-left) cell for the range r = sheet.GetRow(mergedRegion.FirstRow); if (r != null) { return r.GetCell(mergedRegion.FirstColumn); } } } // If we Get here, then the cell isn't defined, and doesn't // live within any merged regions return null; } } }
//------------------------------------------------------------------------------ // <copyright file="XDRSchema.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.Xml; using System.Collections; using System.Globalization; using System.ComponentModel; using System.Diagnostics; using System.Data.Common; internal sealed class XDRSchema : XMLSchema { internal String _schemaName; internal String _schemaUri; internal XmlElement _schemaRoot; internal DataSet _ds; private static char[] colonArray = new char[] {':'}; internal XDRSchema(DataSet ds, bool fInline) { _schemaUri = String.Empty; _schemaName = String.Empty; _schemaRoot = null; _ds = ds; } internal void LoadSchema(XmlElement schemaRoot, DataSet ds) { if (schemaRoot == null) return; _schemaRoot = schemaRoot; _ds = ds; _schemaName = schemaRoot.GetAttribute(Keywords.NAME); _schemaUri = ""; Debug.Assert(FEqualIdentity(schemaRoot, Keywords.XDR_SCHEMA, Keywords.XDRNS), "Illegal node"); // Get Locale and CaseSensitive properties if (_schemaName == null || _schemaName.Length == 0) _schemaName = "NewDataSet"; ds.Namespace = _schemaUri; // Walk all the top level Element tags. for (XmlNode n = schemaRoot.FirstChild; n != null; n = n.NextSibling) { if (!(n is XmlElement)) continue; XmlElement child = (XmlElement) n; if (FEqualIdentity(child, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS)) { HandleTable(child); } } _schemaName = XmlConvert.DecodeName(_schemaName); if (ds.Tables[_schemaName] == null) ds.DataSetName = _schemaName; } internal XmlElement FindTypeNode(XmlElement node) { string strType; XmlNode vn; XmlNode vnRoof; Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_SCHEMA, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS), "Invalid node type " + node.LocalName); if (FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS)) return node; strType = node.GetAttribute(Keywords.TYPE); if (FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) { if (strType == null || strType.Length == 0) return null; // Find an ELEMENTTYPE or ATTRIBUTETYPE with name=strType vn = node.OwnerDocument.FirstChild; vnRoof = node.OwnerDocument; while (vn != vnRoof) { if ((FEqualIdentity(vn, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS) && FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS)) || (FEqualIdentity(vn, Keywords.XDR_ATTRIBUTETYPE, Keywords.XDRNS) && FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS))) { if (vn is XmlElement && ((XmlElement)vn).GetAttribute(Keywords.NAME) == strType) return(XmlElement)vn; } // Move vn node if (vn.FirstChild != null) vn = vn.FirstChild; else if (vn.NextSibling != null) vn = vn.NextSibling; else { while (vn != vnRoof) { vn = vn.ParentNode; if (vn.NextSibling != null) { vn = vn.NextSibling; break; } } } } return null; } return null; } internal bool IsTextOnlyContent(XmlElement node) { Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS), "Invalid node type " + node.LocalName); string value = node.GetAttribute(Keywords.CONTENT); if (value == null || value.Length == 0) { string type = node.GetAttribute(Keywords.DT_TYPE, Keywords.DTNS); if (type != null && type.Length > 0) return true; return false; } if (value == Keywords.EMPTY || value == Keywords.ELTONLY || value == Keywords.ELEMENTONLY || value == Keywords.MIXED) return false; if (value == Keywords.TEXTONLY) return true; throw ExceptionBuilder.InvalidAttributeValue("content", value); } internal bool IsXDRField(XmlElement node, XmlElement typeNode) { int min = 1; int max = 1; if (!IsTextOnlyContent(typeNode)) return false; for (XmlNode n = typeNode.FirstChild; n != null; n = n.NextSibling) { if (FEqualIdentity(n, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(n, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) return false; } if (FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { GetMinMax(node, ref min, ref max); if (max == -1 || max > 1) return false; } return true; } internal DataTable HandleTable(XmlElement node) { XmlElement typeNode; Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS), "Invalid node type"); // Figure out if this really is a table. If not, bail out. typeNode = FindTypeNode(node); string occurs = node.GetAttribute(Keywords.MINOCCURS); if (occurs != null && occurs.Length > 0) if ((Convert.ToInt32(occurs, CultureInfo.InvariantCulture)>1) && (typeNode==null)){ return InstantiateSimpleTable(_ds, node); } occurs = node.GetAttribute(Keywords.MAXOCCURS); if (occurs != null && occurs.Length > 0) if ((string.Compare(occurs, "1" , StringComparison.Ordinal) != 0) && (typeNode==null)){ return InstantiateSimpleTable(_ds, node); } if (typeNode == null) return null; if (IsXDRField(node, typeNode)) return null; return InstantiateTable(_ds, node, typeNode); } private sealed class NameType : IComparable { public String name; public Type type; public NameType(String n, Type t) { name = n; type = t; } public int CompareTo(object obj) { return String.Compare(name, (string)obj, StringComparison.Ordinal); } }; // XDR spec: http://www.ltg.ed.ac.uk/~ht/XMLData-Reduced.htm // http://webdata/newspecs/schema/xdr_dt_schema.xml private static NameType[] mapNameTypeXdr = { new NameType("bin.base64" , typeof(Byte[]) ), /* XDR */ new NameType("bin.hex" , typeof(Byte[]) ), /* XDR */ new NameType("boolean" , typeof(bool) ), /* XDR */ new NameType("byte" , typeof(SByte) ), /* XDR */ new NameType("char" , typeof(Char) ), /* XDR */ new NameType("date" , typeof(DateTime)), /* XDR */ new NameType("dateTime" , typeof(DateTime)), /* XDR */ new NameType("dateTime.tz" , typeof(DateTime)), /* XDR */ new NameType("entities" , typeof(string) ), /* XDR */ new NameType("entity" , typeof(string) ), /* XDR */ new NameType("enumeration" , typeof(string) ), /* XDR */ new NameType("fixed.14.4" , typeof(Decimal) ), /* XDR */ new NameType("float" , typeof(Double) ), /* XDR */ new NameType("i1" , typeof(SByte) ), /* XDR */ new NameType("i2" , typeof(Int16) ), /* XDR */ new NameType("i4" , typeof(Int32) ), /* XDR */ new NameType("i8" , typeof(Int64) ), /* XDR */ new NameType("id" , typeof(string) ), /* XDR */ new NameType("idref" , typeof(string) ), /* XDR */ new NameType("idrefs" , typeof(string) ), /* XDR */ new NameType("int" , typeof(Int32) ), /* XDR */ new NameType("nmtoken" , typeof(string) ), /* XDR */ new NameType("nmtokens" , typeof(string) ), /* XDR */ new NameType("notation" , typeof(string) ), /* XDR */ new NameType("number" , typeof(Decimal) ), /* XDR */ new NameType("r4" , typeof(Single) ), /* XDR */ new NameType("r8" , typeof(Double) ), /* XDR */ new NameType("string" , typeof(string) ), /* XDR */ new NameType("time" , typeof(DateTime)), /* XDR */ new NameType("time.tz" , typeof(DateTime)), /* XDR */ new NameType("ui1" , typeof(Byte) ), /* XDR */ new NameType("ui2" , typeof(UInt16) ), /* XDR */ new NameType("ui4" , typeof(UInt32) ), /* XDR */ new NameType("ui8" , typeof(UInt64) ), /* XDR */ new NameType("uri" , typeof(string) ), /* XDR */ new NameType("uuid" , typeof(Guid) ), /* XDR */ }; private static NameType FindNameType(string name) { #if DEBUG for(int i = 1; i < mapNameTypeXdr.Length; ++i) { Debug.Assert((mapNameTypeXdr[i-1].CompareTo(mapNameTypeXdr[i].name)) < 0, "incorrect sorting"); } #endif int index = Array.BinarySearch(mapNameTypeXdr, name); if (index < 0) { #if DEBUG // Let's check that we realy don't have this name: foreach (NameType nt in mapNameTypeXdr) { Debug.Assert(nt.name != name, "FindNameType('" + name + "') -- failed. Existed name not found"); } #endif throw ExceptionBuilder.UndefinedDatatype(name); } Debug.Assert(mapNameTypeXdr[index].name == name, "FindNameType('" + name + "') -- failed. Wrong name found"); return mapNameTypeXdr[index]; } private static NameType enumerationNameType = FindNameType("enumeration"); private Type ParseDataType(string dt, string dtValues) { string strType = dt; string[] parts = dt.Split(colonArray); // ":" if (parts.Length > 2) { throw ExceptionBuilder.InvalidAttributeValue("type", dt); } else if (parts.Length == 2) { // strType = parts[1]; } NameType nt = FindNameType(strType); if (nt == enumerationNameType && (dtValues == null || dtValues.Length == 0)) throw ExceptionBuilder.MissingAttribute("type", Keywords.DT_VALUES); return nt.type; } internal string GetInstanceName(XmlElement node) { string instanceName; if (FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTETYPE, Keywords.XDRNS)) { instanceName = node.GetAttribute(Keywords.NAME); if (instanceName == null || instanceName.Length == 0) { throw ExceptionBuilder.MissingAttribute("Element", Keywords.NAME); } } else { instanceName = node.GetAttribute(Keywords.TYPE); if (instanceName == null || instanceName.Length == 0) throw ExceptionBuilder.MissingAttribute("Element", Keywords.TYPE); } return instanceName; } internal void HandleColumn(XmlElement node, DataTable table) { Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS), "Illegal node type"); string instanceName; string strName; Type type; string strType; string strValues; int minOccurs = 0; int maxOccurs = 1; string strDefault; DataColumn column; string strUse = node.GetAttribute(Keywords.USE); // Get the name if (node.Attributes.Count > 0) { string strRef = node.GetAttribute(Keywords.REF); if (strRef != null && strRef.Length>0) return; //skip ref nodes. B2 item strName = instanceName = GetInstanceName(node); column = table.Columns[instanceName, _schemaUri]; if (column != null) { if (column.ColumnMapping == MappingType.Attribute) { if (FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) throw ExceptionBuilder.DuplicateDeclaration(strName); } else { if (FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { throw ExceptionBuilder.DuplicateDeclaration(strName); } } instanceName = GenUniqueColumnName(strName, table); } } else { strName = instanceName = ""; } // Now get the type XmlElement typeNode = FindTypeNode(node); SimpleType xsdType = null; if (typeNode == null) { strType = node.GetAttribute(Keywords.TYPE); throw ExceptionBuilder.UndefinedDatatype(strType); } strType = typeNode.GetAttribute(Keywords.DT_TYPE, Keywords.DTNS); strValues = typeNode.GetAttribute(Keywords.DT_VALUES, Keywords.DTNS); if (strType == null || strType.Length == 0) { strType = ""; type = typeof(string); } else { type = ParseDataType(strType, strValues); // HACK: temp work around special types if (strType == "float") { strType = ""; } if (strType == "char") { strType = ""; xsdType = SimpleType.CreateSimpleType(StorageType.Char, type); } if (strType == "enumeration") { strType = ""; xsdType = SimpleType.CreateEnumeratedType(strValues); } if (strType == "bin.base64") { strType = ""; xsdType = SimpleType.CreateByteArrayType("base64"); } if (strType == "bin.hex") { strType = ""; xsdType = SimpleType.CreateByteArrayType("hex"); } } bool isAttribute = FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS); GetMinMax(node, isAttribute, ref minOccurs, ref maxOccurs); strDefault = null; // Does XDR has default? strDefault = node.GetAttribute(Keywords.DEFAULT); bool bNullable = false; column = new DataColumn(XmlConvert.DecodeName(instanceName), type, null, isAttribute ? MappingType.Attribute : MappingType.Element); SetProperties(column, node.Attributes); // xmlschema.SetProperties will skipp setting expressions column.XmlDataType = strType; column.SimpleType = xsdType; column.AllowDBNull = (minOccurs == 0) || bNullable; column.Namespace = (isAttribute) ? String.Empty : _schemaUri; // webdata 97925 // We will skip handling expression columns in SetProperties, so we need set the expressions here if (node.Attributes != null) { for (int i = 0; i < node.Attributes.Count; i++) { if (node.Attributes[i].NamespaceURI == Keywords.MSDNS) { if (node.Attributes[i].LocalName == "Expression"){ column.Expression = node.Attributes[i].Value; break; } } } } String targetNamespace = node.GetAttribute(Keywords.TARGETNAMESPACE); if (targetNamespace != null && targetNamespace.Length > 0) column.Namespace = targetNamespace; table.Columns.Add(column); if (strDefault != null && strDefault.Length != 0) try { column.DefaultValue = SqlConvert.ChangeTypeForXML(strDefault, type); } catch (System.FormatException) { throw ExceptionBuilder.CannotConvert(strDefault, type.FullName); } } internal void GetMinMax(XmlElement elNode, ref int minOccurs, ref int maxOccurs) { GetMinMax(elNode, false, ref minOccurs, ref maxOccurs); } internal void GetMinMax(XmlElement elNode, bool isAttribute, ref int minOccurs, ref int maxOccurs) { string occurs = elNode.GetAttribute(Keywords.MINOCCURS); if (occurs != null && occurs.Length > 0) { try { minOccurs = Int32.Parse(occurs, CultureInfo.InvariantCulture); } catch (Exception e) { // if (!ADP.IsCatchableExceptionType (e)) { throw; } throw ExceptionBuilder.AttributeValues("minOccurs", "0", "1"); } } occurs = elNode.GetAttribute(Keywords.MAXOCCURS); if (occurs != null && occurs.Length > 0) { int bZeroOrMore = string.Compare(occurs, Keywords.STAR , StringComparison.Ordinal); if (bZeroOrMore == 0) { maxOccurs = -1; } else { try { maxOccurs = Int32.Parse(occurs, CultureInfo.InvariantCulture); } catch (Exception e) { // if (!ADP.IsCatchableExceptionType (e)) { throw; } throw ExceptionBuilder.AttributeValues("maxOccurs", "1", Keywords.STAR); } if (maxOccurs != 1) { throw ExceptionBuilder.AttributeValues("maxOccurs", "1", Keywords.STAR); } } } } internal void HandleTypeNode(XmlElement typeNode, DataTable table, ArrayList tableChildren) { DataTable tableChild; for (XmlNode n = typeNode.FirstChild; n != null; n = n.NextSibling) { if (!(n is XmlElement)) continue; if (FEqualIdentity(n, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { tableChild = HandleTable((XmlElement) n); if (tableChild != null) { tableChildren.Add(tableChild); continue; } } if (FEqualIdentity(n, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS) || FEqualIdentity(n, Keywords.XDR_ELEMENT, Keywords.XDRNS)) { HandleColumn((XmlElement) n, table); continue; } } } internal DataTable InstantiateTable(DataSet dataSet, XmlElement node, XmlElement typeNode) { string typeName = ""; XmlAttributeCollection attrs = node.Attributes; DataTable table; int minOccurs = 1; int maxOccurs = 1; string keys = null; ArrayList tableChildren = new ArrayList(); if (attrs.Count > 0) { typeName = GetInstanceName(node); table = dataSet.Tables.GetTable(typeName, _schemaUri); if (table != null) { return table; } } table = new DataTable(XmlConvert.DecodeName(typeName)); // fxcop: new DataTable should inherit the CaseSensitive, Locale from DataSet and possibly updating during SetProperties table.Namespace = _schemaUri; GetMinMax(node, ref minOccurs, ref maxOccurs); table.MinOccurs = minOccurs; table.MaxOccurs = maxOccurs; _ds.Tables.Add(table); HandleTypeNode(typeNode, table, tableChildren); SetProperties(table, attrs); // check to see if we fave unique constraint if (keys != null) { string[] list = keys.TrimEnd(null).Split(null); int keyLength = list.Length; DataColumn[] cols = new DataColumn[keyLength]; for (int i = 0; i < keyLength; i++) { DataColumn col = table.Columns[list[i], _schemaUri]; if (col == null) throw ExceptionBuilder.ElementTypeNotFound(list[i]); cols[i] = col; } table.PrimaryKey = cols; } foreach(DataTable _tableChild in tableChildren) { DataRelation relation = null; DataRelationCollection childRelations = table.ChildRelations; for (int j = 0; j < childRelations.Count; j++) { if (!childRelations[j].Nested) continue; if (_tableChild == childRelations[j].ChildTable) relation = childRelations[j]; } if (relation!=null) continue; DataColumn parentKey = table.AddUniqueKey(); // foreign key in the child table DataColumn childKey = _tableChild.AddForeignKey(parentKey); // create relationship // setup relationship between parent and this table relation = new DataRelation(table.TableName + "_" + _tableChild.TableName, parentKey, childKey, true); relation.CheckMultipleNested = false; // disable the check for multiple nested parent relation.Nested = true; _tableChild.DataSet.Relations.Add(relation); relation.CheckMultipleNested = true; // enable the check for multiple nested parent } return table; } internal DataTable InstantiateSimpleTable(DataSet dataSet, XmlElement node) { string typeName; XmlAttributeCollection attrs = node.Attributes; DataTable table; int minOccurs = 1; int maxOccurs = 1; typeName = GetInstanceName(node); table = dataSet.Tables.GetTable(typeName, _schemaUri); if (table != null) { throw ExceptionBuilder.DuplicateDeclaration(typeName); } String tbName = XmlConvert.DecodeName(typeName); table = new DataTable(tbName); // fxcop: new DataTable will either inherit the CaseSensitive, Locale from DataSet or be set during SetProperties table.Namespace = _schemaUri; GetMinMax(node, ref minOccurs, ref maxOccurs); table.MinOccurs = minOccurs; table.MaxOccurs = maxOccurs; SetProperties(table, attrs); table.repeatableElement = true; HandleColumn((XmlElement) node, table); table.Columns[0].ColumnName = tbName + "_Column"; _ds.Tables.Add(table); return table; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.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. internal class DecoderNLS : Decoder { // Remember our encoding private Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _bytesUsed; internal DecoderNLS(Encoding encoding) { _encoding = encoding; _fallback = this._encoding.DecoderFallback; this.Reset(); } // This is used by our child deserializers internal DecoderNLS() { _encoding = null; this.Reset(); } public override void Reset() { _fallbackBuffer?.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid null fixed problem if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) return GetCharCount(pBytes + index, count, flush); } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Remember the flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encoding version, no flush by default return _encoding.GetCharCount(bytes, count, this); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); // Avoid empty input fixed problem if (bytes.Length == 0) bytes = new byte[1]; int charCount = chars.Length - charIndex; if (chars.Length == 0) chars = new char[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // Remember our flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encodings version return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (bytes.Length == 0) bytes = new byte[1]; if (chars.Length == 0) chars = new char[1]; // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &bytes[0]) { fixed (char* pChars = &chars[0]) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // We don't want to throw _mustFlush = flush; _throwOnOverflow = false; _bytesUsed = 0; // Do conversion charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); // Our data thingy are now full, we can return } public bool MustFlush { get { return _mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { _mustFlush = false; } } }
using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using JCG = J2N.Collections.Generic; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Replicator { /* * 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. */ /// <summary> /// A <see cref="IReplicationHandler"/> for replication of an index. Implements /// <see cref="RevisionReady"/> by copying the files pointed by the client resolver to /// the index <see cref="Store.Directory"/> and then touches the index with /// <see cref="IndexWriter"/> to make sure any unused files are deleted. /// </summary> /// <remarks> /// <b>NOTE:</b> This handler assumes that <see cref="IndexWriter"/> is not opened by /// another process on the index directory. In fact, opening an /// <see cref="IndexWriter"/> on the same directory to which files are copied can lead /// to undefined behavior, where some or all the files will be deleted, override /// other files or simply create a mess. When you replicate an index, it is best /// if the index is never modified by <see cref="IndexWriter"/>, except the one that is /// open on the source index, from which you replicate. /// <para/> /// This handler notifies the application via a provided <see cref="T:Func{bool?}"/> when an /// updated index commit was made available for it. /// <para/> /// @lucene.experimental /// </remarks> public class IndexReplicationHandler : IReplicationHandler { /// <summary> /// The component used to log messages to the <see cref="Util.InfoStream.Default"/> /// <see cref="Util.InfoStream"/>. /// </summary> public const string INFO_STREAM_COMPONENT = "IndexReplicationHandler"; private readonly Directory indexDirectory; private readonly Func<bool?> callback; private volatile IDictionary<string, IList<RevisionFile>> currentRevisionFiles; private volatile string currentVersion; private volatile InfoStream infoStream; //Note: LUCENENET Specific Utility Method private void WriteToInfoStream(params string[] messages) { if (!InfoStream.IsEnabled(INFO_STREAM_COMPONENT)) return; foreach (string message in messages) InfoStream.Message(INFO_STREAM_COMPONENT, message); } /// <summary> /// Returns the last <see cref="IndexCommit"/> found in the <see cref="Directory"/>, or /// <c>null</c> if there are no commits. /// </summary> /// <exception cref="IOException"></exception> public static IndexCommit GetLastCommit(Directory directory) { try { // IndexNotFoundException which we handle below if (DirectoryReader.IndexExists(directory)) { var commits = DirectoryReader.ListCommits(directory); return commits[commits.Count - 1]; } } catch (IndexNotFoundException) { // ignore the exception and return null } return null; } /// <summary> /// Verifies that the last file is segments_N and fails otherwise. It also /// removes and returns the file from the list, because it needs to be handled /// last, after all files. This is important in order to guarantee that if a /// reader sees the new segments_N, all other segment files are already on /// stable storage. /// <para/> /// The reason why the code fails instead of putting segments_N file last is /// that this indicates an error in the <see cref="IRevision"/> implementation. /// </summary> public static string GetSegmentsFile(IList<string> files, bool allowEmpty) { if (files.Count == 0) { if (allowEmpty) return null; throw IllegalStateException.Create("empty list of files not allowed"); } string segmentsFile = files[files.Count - 1]; //NOTE: Relying on side-effects outside? files.RemoveAt(files.Count - 1); if (!segmentsFile.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal) || segmentsFile.Equals(IndexFileNames.SEGMENTS_GEN, StringComparison.Ordinal)) { throw IllegalStateException.Create( string.Format("last file to copy+sync must be segments_N but got {0}; check your Revision implementation!", segmentsFile)); } return segmentsFile; } /// <summary> /// Cleanup the index directory by deleting all given files. Called when file /// copy or sync failed. /// </summary> public static void CleanupFilesOnFailure(Directory directory, IList<string> files) { foreach (string file in files) { try { directory.DeleteFile(file); } catch { // suppress any exception because if we're here, it means copy // failed, and we must cleanup after ourselves. } } } /// <summary> /// Cleans up the index directory from old index files. This method uses the /// last commit found by <see cref="GetLastCommit(Directory)"/>. If it matches the /// expected <paramref name="segmentsFile"/>, then all files not referenced by this commit point /// are deleted. /// </summary> /// <remarks> /// <b>NOTE:</b> This method does a best effort attempt to clean the index /// directory. It suppresses any exceptions that occur, as this can be retried /// the next time. /// </remarks> public static void CleanupOldIndexFiles(Directory directory, string segmentsFile) { try { IndexCommit commit = GetLastCommit(directory); // commit == null means weird IO errors occurred, ignore them // if there were any IO errors reading the expected commit point (i.e. // segments files mismatch), then ignore that commit either. if (commit != null && commit.SegmentsFileName.Equals(segmentsFile, StringComparison.Ordinal)) { ISet<string> commitFiles = new JCG.HashSet<string>(commit.FileNames) { IndexFileNames.SEGMENTS_GEN }; Regex matcher = IndexFileNames.CODEC_FILE_PATTERN; foreach (string file in directory.ListAll()) { if (!commitFiles.Contains(file) && (matcher.IsMatch(file) || file.StartsWith(IndexFileNames.SEGMENTS, StringComparison.Ordinal))) { try { directory.DeleteFile(file); } catch { // suppress, it's just a best effort } } } } } catch { // ignore any errors that happens during this state and only log it. this // cleanup will have a chance to succeed the next time we get a new // revision. } } /// <summary> /// Copies the provided list of files from the <paramref name="source"/> <see cref="Directory"/> to the /// <paramref name="target"/> <see cref="Directory"/>, if they are not the same. /// </summary> /// <exception cref="IOException"></exception> public static void CopyFiles(Directory source, Directory target, IList<string> files) { if (source.Equals(target)) return; foreach (string file in files) source.Copy(target, file, file, IOContext.READ_ONCE); } /// <summary> /// Writes <see cref="IndexFileNames.SEGMENTS_GEN"/> file to the directory, reading /// the generation from the given <paramref name="segmentsFile"/>. If it is <c>null</c>, /// this method deletes segments.gen from the directory. /// </summary> public static void WriteSegmentsGen(string segmentsFile, Directory directory) { if (segmentsFile != null) { SegmentInfos.WriteSegmentsGen(directory, SegmentInfos.GenerationFromSegmentsFileName(segmentsFile)); return; } try { directory.DeleteFile(IndexFileNames.SEGMENTS_GEN); } catch { // suppress any errors while deleting this file. } } /// <summary> /// Constructor with the given index directory and callback to notify when the /// indexes were updated. /// </summary> public IndexReplicationHandler(Directory indexDirectory, Func<bool?> callback) // LUCENENET TODO: API - shouldn't this be Action ? { this.InfoStream = InfoStream.Default; this.callback = callback; this.indexDirectory = indexDirectory; currentVersion = null; currentRevisionFiles = null; if (DirectoryReader.IndexExists(indexDirectory)) { IList<IndexCommit> commits = DirectoryReader.ListCommits(indexDirectory); IndexCommit commit = commits[commits.Count - 1]; currentVersion = IndexRevision.RevisionVersion(commit); currentRevisionFiles = IndexRevision.RevisionFiles(commit); WriteToInfoStream( string.Format("constructor(): currentVersion={0} currentRevisionFiles={1}", currentVersion, currentRevisionFiles), string.Format("constructor(): commit={0}", commit)); } } public virtual string CurrentVersion => currentVersion; public virtual IDictionary<string, IList<RevisionFile>> CurrentRevisionFiles => currentRevisionFiles; public virtual void RevisionReady(string version, IDictionary<string, IList<RevisionFile>> revisionFiles, IDictionary<string, IList<string>> copiedFiles, IDictionary<string, Directory> sourceDirectory) { if (revisionFiles.Count > 1) throw new ArgumentException(string.Format("this handler handles only a single source; got {0}", revisionFiles.Keys)); Directory clientDirectory = sourceDirectory.Values.First(); IList<string> files = copiedFiles.Values.First(); string segmentsFile = GetSegmentsFile(files, false); bool success = false; try { // copy files from the client to index directory CopyFiles(clientDirectory, indexDirectory, files); // fsync all copied files (except segmentsFile) indexDirectory.Sync(files); // now copy and fsync segmentsFile clientDirectory.Copy(indexDirectory, segmentsFile, segmentsFile, IOContext.READ_ONCE); indexDirectory.Sync(new[] { segmentsFile }); success = true; } finally { if (!success) { files.Add(segmentsFile); // add it back so it gets deleted too CleanupFilesOnFailure(indexDirectory, files); } } // all files have been successfully copied + sync'd. update the handler's state currentRevisionFiles = revisionFiles; currentVersion = version; WriteToInfoStream(string.Format("revisionReady(): currentVersion={0} currentRevisionFiles={1}", currentVersion, currentRevisionFiles)); // update the segments.gen file WriteSegmentsGen(segmentsFile, indexDirectory); // Cleanup the index directory from old and unused index files. // NOTE: we don't use IndexWriter.deleteUnusedFiles here since it may have // side-effects, e.g. if it hits sudden IO errors while opening the index // (and can end up deleting the entire index). It is not our job to protect // against those errors, app will probably hit them elsewhere. CleanupOldIndexFiles(indexDirectory, segmentsFile); // successfully updated the index, notify the callback that the index is // ready. if (callback != null) { try { callback.Invoke(); } catch (Exception e) { throw new IOException(e.ToString(), e); } } } /// <summary> /// Gets or sets the <see cref="Util.InfoStream"/> to use for logging messages. /// </summary> public virtual InfoStream InfoStream { get => infoStream; set => infoStream = value ?? InfoStream.NO_OUTPUT; } } }